@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/es2018.cjs.js CHANGED
@@ -1,9 +1,9 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.99
3
- * Mon, 08 Apr 2024 01:38:49 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-99/doc/
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
- "use strict";var Do=Object.create;var Ia=Object.defineProperty;var Ro=Object.getOwnPropertyDescriptor;var Lo=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,xo=Object.prototype.hasOwnProperty;var _o=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Lo(e))!xo.call(i,a)&&a!==t&&Ia(i,a,{get:()=>e[a],enumerable:!(s=Ro(e,a))||s.enumerable});return i};var No=(i,e,t)=>(t=i!=null?Do(Io(i)):{},_o(e||!i||!i.__esModule?Ia(t,"default",{value:i,enumerable:!0}):t,i));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js");const en="2.0.99";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH_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"})(exports.VideoFormat||(exports.VideoFormat={}));var se;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(se||(se={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var O;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(O||(O={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(exports.Surface||(exports.Surface={}));var Oo=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 Mo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Oo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,a,n;(n=(a=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([s.getCastState()])).pipe(r.filterChanged(),r.map(Bo),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const c=s.getCurrentSession();r.assertNonNullable(c);const u=c.getCastDevice(),d=(n=c.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.isNullable(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,s,a;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Bo=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return r.assertNever(i)}};var Zi=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ea(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ne=function(i){try{return!!i()}catch(e){return!0}},Vo=Ne,Di=!Vo(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),tn=Di,sn=Function.prototype,Bs=sn.call,Fo=tn&&sn.bind.bind(Bs,Bs),Oe=tn?Fo:function(i){return function(){return Bs.apply(i,arguments)}},an=Oe,Uo=an({}.toString),jo=an("".slice),Ri=function(i){return jo(Uo(i),8,-1)},Ho=Oe,Go=Ne,Yo=Ri,es=Object,qo=Ho("".split),zo=Go(function(){return!es("z").propertyIsEnumerable(0)})?function(i){return Yo(i)=="String"?qo(i,""):es(i)}:es,Li=function(i){return i==null},Wo=Li,Qo=TypeError,ta=function(i){if(Wo(i))throw Qo("Can't call method on "+i);return i},Ko=zo,Jo=ta,Yt=function(i){return Ko(Jo(i))},Ct={},ti=function(i){return i&&i.Math==Math&&i},be=ti(typeof globalThis=="object"&&globalThis)||ti(typeof window=="object"&&window)||ti(typeof self=="object"&&self)||ti(typeof Zi=="object"&&Zi)||function(){return this}()||Zi||Function("return this")(),Vs=typeof document=="object"&&document.all,Xo=typeof Vs=="undefined"&&Vs!==void 0,rn={all:Vs,IS_HTMLDDA:Xo},nn=rn,Zo=nn.all,de=nn.IS_HTMLDDA?function(i){return typeof i=="function"||i===Zo}:function(i){return typeof i=="function"},el=be,tl=de,xa=el.WeakMap,il=tl(xa)&&/native code/.test(String(xa)),_a=de,on=rn,sl=on.all,it=on.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:_a(i)||i===sl}:function(i){return typeof i=="object"?i!==null:_a(i)},al=Ne,st=!al(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Dt={},rl=be,Na=it,Fs=rl.document,nl=Na(Fs)&&Na(Fs.createElement),ln=function(i){return nl?Fs.createElement(i):{}},ol=st,ll=Ne,ul=ln,un=!ol&&!ll(function(){return Object.defineProperty(ul("div"),"a",{get:function(){return 7}}).a!=7}),cl=st,dl=Ne,cn=cl&&dl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),hl=it,fl=String,pl=TypeError,at=function(i){if(hl(i))return i;throw pl(fl(i)+" is not an object")},ml=Di,ii=Function.prototype.call,Me=ml?ii.bind(ii):function(){return ii.apply(ii,arguments)},ia={},ts=ia,is=be,vl=de,Oa=function(i){return vl(i)?i:void 0},sa=function(i,e){return arguments.length<2?Oa(ts[i])||Oa(is[i]):ts[i]&&ts[i][e]||is[i]&&is[i][e]},bl=Oe,aa=bl({}.isPrototypeOf),Sl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",dn=be,ss=Sl,Ma=dn.process,Ba=dn.Deno,Va=Ma&&Ma.versions||Ba&&Ba.version,Fa=Va&&Va.v8,me,Ti;Fa&&(me=Fa.split("."),Ti=me[0]>0&&me[0]<4?1:+(me[0]+me[1]));!Ti&&ss&&(me=ss.match(/Edge\/(\d+)/),(!me||me[1]>=74)&&(me=ss.match(/Chrome\/(\d+)/),me&&(Ti=+me[1])));var gl=Ti,Ua=gl,yl=Ne,Tl=be,El=Tl.String,hn=!!Object.getOwnPropertySymbols&&!yl(function(){var i=Symbol();return!El(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Ua&&Ua<41}),$l=hn,fn=$l&&!Symbol.sham&&typeof Symbol.iterator=="symbol",kl=sa,wl=de,Al=aa,Pl=fn,Cl=Object,pn=Pl?function(i){return typeof i=="symbol"}:function(i){var e=kl("Symbol");return wl(e)&&Al(e.prototype,Cl(i))},Dl=String,ra=function(i){try{return Dl(i)}catch(e){return"Object"}},Rl=de,Ll=ra,Il=TypeError,na=function(i){if(Rl(i))return i;throw Il(Ll(i)+" is not a function")},xl=na,_l=Li,Ii=function(i,e){var t=i[e];return _l(t)?void 0:xl(t)},as=Me,rs=de,ns=it,Nl=TypeError,Ol=function(i,e){var t,s;if(e==="string"&&rs(t=i.toString)&&!ns(s=as(t,i))||rs(t=i.valueOf)&&!ns(s=as(t,i))||e!=="string"&&rs(t=i.toString)&&!ns(s=as(t,i)))return s;throw Nl("Can't convert object to primitive value")},mn={exports:{}},ja=be,Ml=Object.defineProperty,Bl=function(i,e){try{Ml(ja,i,{value:e,configurable:!0,writable:!0})}catch(t){ja[i]=e}return e},Vl=be,Fl=Bl,Ha="__core-js_shared__",Ul=Vl[Ha]||Fl(Ha,{}),vn=Ul,Ga=vn;(mn.exports=function(i,e){return Ga[i]||(Ga[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 bn=mn.exports,jl=ta,Hl=Object,xi=function(i){return Hl(jl(i))},Gl=Oe,Yl=xi,ql=Gl({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return ql(Yl(e),t)},zl=Oe,Wl=0,Ql=Math.random(),Kl=zl(1 .toString),Sn=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Kl(++Wl+Ql,36)},Jl=be,Xl=bn,Ya=Be,Zl=Sn,eu=hn,tu=fn,Et=Jl.Symbol,os=Xl("wks"),iu=tu?Et.for||Et:Et&&Et.withoutSetter||Zl,Se=function(i){return Ya(os,i)||(os[i]=eu&&Ya(Et,i)?Et[i]:iu("Symbol."+i)),os[i]},su=Me,qa=it,za=pn,au=Ii,ru=Ol,nu=Se,ou=TypeError,lu=nu("toPrimitive"),uu=function(i,e){if(!qa(i)||za(i))return i;var t=au(i,lu),s;if(t){if(e===void 0&&(e="default"),s=su(t,i,e),!qa(s)||za(s))return s;throw ou("Can't convert object to primitive value")}return e===void 0&&(e="number"),ru(i,e)},cu=uu,du=pn,oa=function(i){var e=cu(i,"string");return du(e)?e:e+""},hu=st,fu=un,pu=cn,si=at,Wa=oa,mu=TypeError,ls=Object.defineProperty,vu=Object.getOwnPropertyDescriptor,us="enumerable",cs="configurable",ds="writable";Dt.f=hu?pu?function(e,t,s){if(si(e),t=Wa(t),si(s),typeof e=="function"&&t==="prototype"&&"value"in s&&ds in s&&!s[ds]){var a=vu(e,t);a&&a[ds]&&(e[t]=s.value,s={configurable:cs in s?s[cs]:a[cs],enumerable:us in s?s[us]:a[us],writable:!1})}return ls(e,t,s)}:ls:function(e,t,s){if(si(e),t=Wa(t),si(s),fu)try{return ls(e,t,s)}catch(a){}if("get"in s||"set"in s)throw mu("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var _i=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},bu=st,Su=Dt,gu=_i,qt=bu?function(i,e,t){return Su.f(i,e,gu(1,t))}:function(i,e,t){return i[e]=t,i},yu=bn,Tu=Sn,Qa=yu("keys"),la=function(i){return Qa[i]||(Qa[i]=Tu(i))},ua={},Eu=il,gn=be,$u=it,ku=qt,hs=Be,fs=vn,wu=la,Au=ua,Ka="Object already initialized",Us=gn.TypeError,Pu=gn.WeakMap,Ei,jt,$i,Cu=function(i){return $i(i)?jt(i):Ei(i,{})},Du=function(i){return function(e){var t;if(!$u(e)||(t=jt(e)).type!==i)throw Us("Incompatible receiver, "+i+" required");return t}};if(Eu||fs.state){var Te=fs.state||(fs.state=new Pu);Te.get=Te.get,Te.has=Te.has,Te.set=Te.set,Ei=function(i,e){if(Te.has(i))throw Us(Ka);return e.facade=i,Te.set(i,e),e},jt=function(i){return Te.get(i)||{}},$i=function(i){return Te.has(i)}}else{var vt=wu("state");Au[vt]=!0,Ei=function(i,e){if(hs(i,vt))throw Us(Ka);return e.facade=i,ku(i,vt,e),e},jt=function(i){return hs(i,vt)?i[vt]:{}},$i=function(i){return hs(i,vt)}}var Ru={set:Ei,get:jt,has:$i,enforce:Cu,getterFor:Du},Lu=Di,yn=Function.prototype,Ja=yn.apply,Xa=yn.call,Iu=typeof Reflect=="object"&&Reflect.apply||(Lu?Xa.bind(Ja):function(){return Xa.apply(Ja,arguments)}),xu=Ri,_u=Oe,Tn=function(i){if(xu(i)==="Function")return _u(i)},En={},$n={},kn={}.propertyIsEnumerable,wn=Object.getOwnPropertyDescriptor,Nu=wn&&!kn.call({1:2},1);$n.f=Nu?function(e){var t=wn(this,e);return!!t&&t.enumerable}:kn;var Ou=st,Mu=Me,Bu=$n,Vu=_i,Fu=Yt,Uu=oa,ju=Be,Hu=un,Za=Object.getOwnPropertyDescriptor;En.f=Ou?Za:function(e,t){if(e=Fu(e),t=Uu(t),Hu)try{return Za(e,t)}catch(s){}if(ju(e,t))return Vu(!Mu(Bu.f,e,t),e[t])};var Gu=Ne,Yu=de,qu=/#|\.prototype\./,zt=function(i,e){var t=Wu[zu(i)];return t==Ku?!0:t==Qu?!1:Yu(e)?Gu(e):!!e},zu=zt.normalize=function(i){return String(i).replace(qu,".").toLowerCase()},Wu=zt.data={},Qu=zt.NATIVE="N",Ku=zt.POLYFILL="P",Ju=zt,er=Tn,Xu=na,Zu=Di,ec=er(er.bind),An=function(i,e){return Xu(i),e===void 0?i:Zu?ec(i,e):function(){return i.apply(e,arguments)}},ai=be,tc=Iu,ic=Tn,sc=de,ac=En.f,rc=Ju,bt=ia,nc=An,St=qt,tr=Be,oc=function(i){var e=function(t,s,a){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,a)}return tc(i,this,arguments)};return e.prototype=i.prototype,e},Ni=function(i,e){var t=i.target,s=i.global,a=i.stat,n=i.proto,o=s?ai:a?ai[t]:(ai[t]||{}).prototype,l=s?bt:bt[t]||St(bt,t,{})[t],c=l.prototype,u,d,h,f,p,b,m,v,S;for(f in e)u=rc(s?f:t+(a?".":"#")+f,i.forced),d=!u&&o&&tr(o,f),b=l[f],d&&(i.dontCallGetSet?(S=ac(o,f),m=S&&S.value):m=o[f]),p=d&&m?m:e[f],!(d&&typeof b==typeof p)&&(i.bind&&d?v=nc(p,ai):i.wrap&&d?v=oc(p):n&&sc(p)?v=ic(p):v=p,(i.sham||p&&p.sham||b&&b.sham)&&St(v,"sham",!0),St(l,f,v),n&&(h=t+"Prototype",tr(bt,h)||St(bt,h,{}),St(bt[h],f,p),i.real&&c&&(u||!c[f])&&St(c,f,p)))},js=st,lc=Be,Pn=Function.prototype,uc=js&&Object.getOwnPropertyDescriptor,ca=lc(Pn,"name"),cc=ca&&function(){}.name==="something",dc=ca&&(!js||js&&uc(Pn,"name").configurable),hc={EXISTS:ca,PROPER:cc,CONFIGURABLE:dc},Cn={},fc=Math.ceil,pc=Math.floor,mc=Math.trunc||function(e){var t=+e;return(t>0?pc:fc)(t)},vc=mc,da=function(i){var e=+i;return e!==e||e===0?0:vc(e)},bc=da,Sc=Math.max,gc=Math.min,yc=function(i,e){var t=bc(i);return t<0?Sc(t+e,0):gc(t,e)},Tc=da,Ec=Math.min,$c=function(i){return i>0?Ec(Tc(i),9007199254740991):0},kc=$c,ha=function(i){return kc(i.length)},wc=Yt,Ac=yc,Pc=ha,ir=function(i){return function(e,t,s){var a=wc(e),n=Pc(a),o=Ac(s,n),l;if(i&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in a)&&a[o]===t)return i||o||0;return!i&&-1}},Cc={includes:ir(!0),indexOf:ir(!1)},Dc=Oe,ps=Be,Rc=Yt,Lc=Cc.indexOf,Ic=ua,sr=Dc([].push),xc=function(i,e){var t=Rc(i),s=0,a=[],n;for(n in t)!ps(Ic,n)&&ps(t,n)&&sr(a,n);for(;e.length>s;)ps(t,n=e[s++])&&(~Lc(a,n)||sr(a,n));return a},Dn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],_c=xc,Nc=Dn,Oc=Object.keys||function(e){return _c(e,Nc)},Mc=st,Bc=cn,Vc=Dt,Fc=at,Uc=Yt,jc=Oc;Cn.f=Mc&&!Bc?Object.defineProperties:function(e,t){Fc(e);for(var s=Uc(t),a=jc(t),n=a.length,o=0,l;n>o;)Vc.f(e,l=a[o++],s[l]);return e};var Hc=sa,Gc=Hc("document","documentElement"),Yc=at,qc=Cn,ar=Dn,zc=ua,Wc=Gc,Qc=ln,Kc=la,rr=">",nr="<",Hs="prototype",Gs="script",Rn=Kc("IE_PROTO"),ms=function(){},Ln=function(i){return nr+Gs+rr+i+nr+"/"+Gs+rr},or=function(i){i.write(Ln("")),i.close();var e=i.parentWindow.Object;return i=null,e},Jc=function(){var i=Qc("iframe"),e="java"+Gs+":",t;return i.style.display="none",Wc.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Ln("document.F=Object")),t.close(),t.F},ri,bi=function(){try{ri=new ActiveXObject("htmlfile")}catch(e){}bi=typeof document!="undefined"?document.domain&&ri?or(ri):Jc():or(ri);for(var i=ar.length;i--;)delete bi[Hs][ar[i]];return bi()};zc[Rn]=!0;var In=Object.create||function(e,t){var s;return e!==null?(ms[Hs]=Yc(e),s=new ms,ms[Hs]=null,s[Rn]=e):s=bi(),t===void 0?s:qc.f(s,t)},Xc=Ne,Zc=!Xc(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),ed=Be,td=de,id=xi,sd=la,ad=Zc,lr=sd("IE_PROTO"),Ys=Object,rd=Ys.prototype,xn=ad?Ys.getPrototypeOf:function(i){var e=id(i);if(ed(e,lr))return e[lr];var t=e.constructor;return td(t)&&e instanceof t?t.prototype:e instanceof Ys?rd:null},nd=qt,_n=function(i,e,t,s){return s&&s.enumerable?i[e]=t:nd(i,e,t),i},od=Ne,ld=de,ud=it,cd=In,ur=xn,dd=_n,hd=Se,qs=hd("iterator"),Nn=!1,Ie,vs,bs;[].keys&&(bs=[].keys(),"next"in bs?(vs=ur(ur(bs)),vs!==Object.prototype&&(Ie=vs)):Nn=!0);var fd=!ud(Ie)||od(function(){var i={};return Ie[qs].call(i)!==i});fd?Ie={}:Ie=cd(Ie);ld(Ie[qs])||dd(Ie,qs,function(){return this});var On={IteratorPrototype:Ie,BUGGY_SAFARI_ITERATORS:Nn},pd=Se,md=pd("toStringTag"),Mn={};Mn[md]="z";var fa=String(Mn)==="[object z]",vd=fa,bd=de,Si=Ri,Sd=Se,gd=Sd("toStringTag"),yd=Object,Td=Si(function(){return arguments}())=="Arguments",Ed=function(i,e){try{return i[e]}catch(t){}},Oi=vd?Si:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Ed(e=yd(i),gd))=="string"?t:Td?Si(e):(s=Si(e))=="Object"&&bd(e.callee)?"Arguments":s},$d=fa,kd=Oi,wd=$d?{}.toString:function(){return"[object "+kd(this)+"]"},Ad=fa,Pd=Dt.f,Cd=qt,Dd=Be,Rd=wd,Ld=Se,cr=Ld("toStringTag"),Bn=function(i,e,t,s){if(i){var a=t?i:i.prototype;Dd(a,cr)||Pd(a,cr,{configurable:!0,value:e}),s&&!Ad&&Cd(a,"toString",Rd)}},Id=On.IteratorPrototype,xd=In,_d=_i,Nd=Bn,Od=Ct,Md=function(){return this},Bd=function(i,e,t,s){var a=e+" Iterator";return i.prototype=xd(Id,{next:_d(+!s,t)}),Nd(i,a,!1,!0),Od[a]=Md,i},Vd=Ni,Fd=Me,Vn=hc,Ud=Bd,jd=xn,Hd=Bn,dr=_n,Gd=Se,hr=Ct,Fn=On,Yd=Vn.PROPER;Vn.CONFIGURABLE;Fn.IteratorPrototype;var ni=Fn.BUGGY_SAFARI_ITERATORS,Ss=Gd("iterator"),fr="keys",oi="values",pr="entries",qd=function(){return this},zd=function(i,e,t,s,a,n,o){Ud(t,e,s);var l=function(S){if(S===a&&f)return f;if(!ni&&S in d)return d[S];switch(S){case fr:return function(){return new t(this,S)};case oi:return function(){return new t(this,S)};case pr:return function(){return new t(this,S)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,h=d[Ss]||d["@@iterator"]||a&&d[a],f=!ni&&h||l(a),p=e=="Array"&&d.entries||h,b,m,v;if(p&&(b=jd(p.call(new i)),b!==Object.prototype&&b.next&&(Hd(b,c,!0,!0),hr[c]=qd)),Yd&&a==oi&&h&&h.name!==oi&&(u=!0,f=function(){return Fd(h,this)}),a)if(m={values:l(oi),keys:n?f:l(fr),entries:l(pr)},o)for(v in m)(ni||u||!(v in d))&&dr(d,v,m[v]);else Vd({target:e,proto:!0,forced:ni||u},m);return o&&d[Ss]!==f&&dr(d,Ss,f,{name:a}),hr[e]=f,m},Wd=function(i,e){return{value:i,done:e}},Qd=Yt,mr=Ct,Un=Ru;Dt.f;var Kd=zd,li=Wd,jn="Array Iterator",Jd=Un.set,Xd=Un.getterFor(jn);Kd(Array,"Array",function(i,e){Jd(this,{type:jn,target:Qd(i),index:0,kind:e})},function(){var i=Xd(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,li(void 0,!0)):t=="keys"?li(s,!1):t=="values"?li(e[s],!1):li([s,e[s]],!1)},"values");mr.Arguments=mr.Array;var Zd=Se,eh=Ct,th=Zd("iterator"),ih=Array.prototype,sh=function(i){return i!==void 0&&(eh.Array===i||ih[th]===i)},ah=Oi,vr=Ii,rh=Li,nh=Ct,oh=Se,lh=oh("iterator"),Hn=function(i){if(!rh(i))return vr(i,lh)||vr(i,"@@iterator")||nh[ah(i)]},uh=Me,ch=na,dh=at,hh=ra,fh=Hn,ph=TypeError,mh=function(i,e){var t=arguments.length<2?fh(i):e;if(ch(t))return dh(uh(t,i));throw ph(hh(i)+" is not iterable")},vh=Me,br=at,bh=Ii,Sh=function(i,e,t){var s,a;br(i);try{if(s=bh(i,"return"),!s){if(e==="throw")throw t;return t}s=vh(s,i)}catch(n){a=!0,s=n}if(e==="throw")throw t;if(a)throw s;return br(s),t},gh=An,yh=Me,Th=at,Eh=ra,$h=sh,kh=ha,Sr=aa,wh=mh,Ah=Hn,gr=Sh,Ph=TypeError,gi=function(i,e){this.stopped=i,this.result=e},yr=gi.prototype,Ch=function(i,e,t){var s=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),c=gh(e,s),u,d,h,f,p,b,m,v=function(y){return u&&gr(u,"normal",y),new gi(!0,y)},S=function(y){return a?(Th(y),l?c(y[0],y[1],v):c(y[0],y[1])):l?c(y,v):c(y)};if(n)u=i.iterator;else if(o)u=i;else{if(d=Ah(i),!d)throw Ph(Eh(i)+" is not iterable");if($h(d)){for(h=0,f=kh(i);f>h;h++)if(p=S(i[h]),p&&Sr(yr,p))return p;return new gi(!1)}u=wh(i,d)}for(b=n?i.next:u.next;!(m=yh(b,u)).done;){try{p=S(m.value)}catch(y){gr(u,"throw",y)}if(typeof p=="object"&&p&&Sr(yr,p))return p}return new gi(!1)},Dh=oa,Rh=Dt,Lh=_i,Ih=function(i,e,t){var s=Dh(e);s in i?Rh.f(i,s,Lh(0,t)):i[s]=t},xh=Ni,_h=Ch,Nh=Ih;xh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _h(e,function(s,a){Nh(t,s,a)},{AS_ENTRIES:!0}),t}});var Oh=ia,Mh=Oh.Object.fromEntries,Bh={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},Vh=Bh,Fh=be,Uh=Oi,jh=qt,Tr=Ct,Hh=Se,Er=Hh("toStringTag");for(var gs in Vh){var $r=Fh[gs],ys=$r&&$r.prototype;ys&&Uh(ys)!==Er&&jh(ys,Er,gs),Tr[gs]=Tr.Array}var Gh=Mh,Yh=Gh,qh=Yh,zh=qh,ki=ea(zh),Z;(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"})(Z||(Z={}));var ve=(i,e=0,t=Z.OFFSET_P)=>{switch(t){case Z.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Z.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case Z.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:r.assertNever(t)}return i};const kr=(i,e)=>{var t;switch(e){case Z.OFFSET_P:return NaN;case Z.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case Z.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:r.assertNever(e)}};var P=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class K{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$),this.state=e,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||r.isNonNullable(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 Wh=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(i)}};var R;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(R||(R={}));const Qh=5,Kh=5,Jh=500,wr=7e3;class Xh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new K(R.STOPPED),this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==R.STOPPED&&(this.videoState.startTransitionTo(R.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===O.Requested&&s!==R.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case R.PLAYING:case R.PAUSED:case R.READY:break;case R.STOPPED:this.videoState.startTransitionTo(R.READY),this.prepare();break;default:r.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case R.PLAYING:break;case R.PAUSED:this.videoState.startTransitionTo(R.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case R.READY:this.videoState.startTransitionTo(R.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case R.STOPPED:this.videoState.startTransitionTo(R.READY),this.prepare();break;default:r.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case R.PLAYING:this.videoState.startTransitionTo(R.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case R.PAUSED:break;case R.READY:this.videoState.startTransitionTo(R.PAUSED),this.videoState.setState(R.PAUSED);break;case R.STOPPED:this.videoState.startTransitionTo(R.READY),this.prepare();break;default:r.assertNever(s)}break}default:r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Wh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Jh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===O.Applying||Math.abs(l-n)>Qh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.value,l=this.params.output.isBuffering$.getValue(),c=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==c&&this.params.output.isBuffering$.next(c),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Kh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const s=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(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(R.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(R.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.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:O.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)===R.PAUSED||e===R.PLAYING)&&(this.videoState.setState(R.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===R.PLAYING||e===R.PAUSED)&&(this.videoState.setState(R.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===R.READY&&this.videoState.setState(R.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==R.STOPPED&&this.videoState.setState(R.STOPPED)}handleRemoteVolumeChange(e){var t,s;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(s=e.muted)!==null&&s!==void 0?s:a.muted};(n.volume!==a.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController: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 a,n,o;switch(e){case exports.VideoFormat.MPEG:{const d=s[e];r.assertNonNullable(d);const h=r.getHighestQuality(Object.keys(d));r.assertNonNullable(h);const f=d[h];r.assertNonNullable(f),a=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const d=s[e];r.assertNonNullable(d),a=d.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const d=s[e];r.assertNonNullable(d),a=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const d=s[e];r.assertNonNullable(d),a=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const d=s[e];r.assertNonNullable(d),a=ve(d.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:u}=this.params.meta;return r.isNonNullable(c)&&(l.metadata.title=c),r.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===O.Applying||s.state===O.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((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(wr).subscribe(()=>n(`timeout(${wr})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===O.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const pa=i=>{i.removeAttribute("src"),i.load()},Zh=i=>{try{i.pause(),i.playbackRate=0,pa(i),i.remove()}catch(e){console.error(e)}};class ef{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 zs=window.WeakMap?new WeakMap:new ef,rt=i=>{let e=i.querySelector("video");const t=!!e;return e?pa(e):(e=document.createElement("video"),i.appendChild(e)),zs.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},nt=i=>{const e=zs.get(i);zs.delete(i),e?pa(i):Zh(i)},Re=(i,e,t,{equal:s=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=i.getState(),l=e(),c=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.subscribe(d=>{const h=i.getState();s(d,h)&&i.setState(d)},n)),s(l,o)||(t(o),c&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},n)),u},Wt=(i,e,t)=>Re(e,()=>i.loop,s=>{r.isNonNullable(s)&&(i.loop=s)},{onError:t}),ot=(i,e,t,s)=>Re(e,()=>({muted:i.muted,volume:i.volume}),a=>{r.isNonNullable(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),Rt=(i,e,t,s)=>Re(e,()=>i.playbackRate,a=>{r.isNonNullable(a)&&(i.playbackRate=a)},{changed$:t,onError:s}),tf=i=>["__",i.language,i.label].join("|"),sf=(i,e)=>{if(i.id===e)return!0;const[t,s,a]=e.split("|");return i.language===s&&i.label===a};class Ge{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Re(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(Re(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(Re(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(Re(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),r.filterChanged((s,a)=>s.length===a.length&&s.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),r.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),r.filterChanged()).subscribe(this.current$));const t=s=>{var a,n;return this.applyCueSettings((n=(a=s.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(s=>{var a,n;(a=s.track)===null||a===void 0||a.addEventListener("cuechange",t);const o=l=>{var c,u,d,h,f;const p=(u=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(s=>{var a;(a=s.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const a=s;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ge.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:a,label:n}=e,o=e.id?e.id:tf(e),l=this.externalTracks.has(o),c=o.includes("auto");return l?{id:o,type:"external",isAuto:c,language:a,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:c,language:a,label:n,url:(s=this.internalTracks.get(o))===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:a,isAuto:n})=>!this.internalTracks.has(s)&&!t.some(([,o])=>o.language===a&&o.isAuto===n)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(a=>a.id===s)).forEach(([,s])=>this.detach(s))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!sf(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){r.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),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 ma{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 Gn=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},Ar=i=>{const e=Gn(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},af=i=>{const e=Gn(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},rf=3;var nf=(i,e,t=rf)=>{let s=0,a=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,a=l,!t)return{from:s,to:a};for(let c=n-1;c>=0;c--)i.end(c)+t>=s&&(s=i.start(c));for(let c=n+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:s,to:a}};const lt=i=>{const e=E=>r.fromEvent(i,E).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=r.merge(...t.map(E=>r.fromEvent(i,E))).pipe(r.map(E=>E.type==="ended"?i.readyState<2:i.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(i,"progress"),r.fromEvent(i,"timeupdate")).pipe(r.map(()=>nf(i.buffered,i.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),l=r.fromEvent(i,"volumechange").pipe(r.map(()=>({muted:i.muted,volume:i.volume}))),c=r.fromEvent(i,"ratechange").pipe(r.map(()=>i.playbackRate)),u=r.fromEvent(i,"error").pipe(r.filter(()=>!!(i.error||i.played.length)),r.map(()=>{var E;const T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(E=i.error)!==null&&E!==void 0?E:void 0}})),d=r.fromEvent(i,"timeupdate").pipe(r.map(()=>i.currentTime)),h=new r.Subject,f=.3;let p;d.subscribe(E=>{i.loop&&r.isNonNullable(p)&&r.isNonNullable(E)&&p>=i.duration-f&&E<=f&&h.next(p),p=E});const b=r.fromEvent(i,"enterpictureinpicture"),m=r.fromEvent(i,"leavepictureinpicture"),v=new r.ValueSubject(af(i));b.subscribe(()=>v.next(!0)),m.subscribe(()=>v.next(!1));const S=new r.ValueSubject(Ar(i));return r.fromEvent(i,"fullscreenchange").pipe(r.map(()=>Ar(i))).subscribe(S),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:r.fromEvent(i,"durationchange").pipe(r.map(()=>i.duration)),isBuffering$:s,currentBuffer$:a,volumeState$:l,playbackRateState$:c,inPiP$:v,inFullscreen$:S}};var Mi=i=>{switch(i){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}},of=Ni,lf=xi,uf=ha,cf=da;of({target:"Array",proto:!0},{at:function(e){var t=lf(this),s=uf(t),a=cf(e),n=a>=0?a:s+a;return n<0||n>=s?void 0:t[n]}});var df=sa,Yn=df,hf=Yn,ff=hf("Array","at"),pf=ff,mf=pf,vf=mf,bf=vf,De=ea(bf);let va=!1,Le={};const Sf=i=>{va=i},gf=()=>{Le={}},yf=i=>{i(Le)},ui=(i,e)=>{var t;va&&(Le.meta=(t=Le.meta)!==null&&t!==void 0?t:{},Le.meta[i]=e)};class ke{constructor(e){this.name=e}next(e){var t,s;if(!va)return;Le.series=(t=Le.series)!==null&&t!==void 0?t:{};const a=(s=Le.series[this.name])!==null&&s!==void 0?s:[];a.push([Date.now(),e]),Le.series[this.name]=a}}var et;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(et||(et={}));const Tf=new ke("best_bitrate"),Ef=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class $f{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const kf='Assertion "ABR Tracks is empty array" failed',Bi=(i,{container:e,throughput:t,tuning:s,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:c,history:u,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var f,p,b,m,v;r.assertNotEmptyArray(i,kf);const S=s.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},E=y&&r.videoSizeToQuality(y),T=s.considerPlaybackRate&&r.isNonNullable(l)?l:1,$=i.filter(D=>!r.isInvariantQuality(D.quality)).sort((D,w)=>r.isHigher(D.quality,w.quality)?-1:1),x=(p=De($,-1))===null||p===void 0?void 0:p.quality,_=(b=De($,0))===null||b===void 0?void 0:b.quality,V=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&r.isLower(a.max,a.min)||r.isNonNullable(a.min)&&_&&r.isHigher(a.min,_)||r.isNonNullable(a.max)&&x&&r.isLower(a.max,x),N=T*Ef(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),F={},C=$.filter(D=>(E?r.isLower(D.quality,E):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(D.bitrate)?t-n>=D.bitrate*N:!0)?s.lazyQualitySwitch&&r.isNonNullable(s.minBufferToSwitchUp)&&c&&!r.isInvariantQuality(c.quality)&&(o!=null?o:0)<s.minBufferToSwitchUp&&r.isHigher(D.quality,c.quality)?(F[D.quality]=et.Buffer,!1):!!d&&r.isHigherOrEqual(D.quality,d)?(F[D.quality]=et.DroppedFramesLimit,!1):V||(r.isNullable(a.max)||r.isLowerOrEqual(D.quality,a.max))&&(r.isNullable(a.min)||r.isHigherOrEqual(D.quality,a.min))?!0:(F[D.quality]=et.FitsQualityLimits,!1):(F[D.quality]=et.FitsThroughput,!1):(F[D.quality]=et.FitsContainer,!1))[0];C&&C.bitrate&&Tf.next(C.bitrate);const A=(m=C!=null?C:$[Math.ceil(($.length-1)/2)])!==null&&m!==void 0?m:i[0];A.quality!==((v=u==null?void 0:u.last)===null||v===void 0?void 0:v.quality)&&h({message:`
6
+ "use strict";var Do=Object.create;var Ia=Object.defineProperty;var Lo=Object.getOwnPropertyDescriptor;var Ro=Object.getOwnPropertyNames;var Io=Object.getPrototypeOf,_o=Object.prototype.hasOwnProperty;var xo=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of Ro(e))!_o.call(i,a)&&a!==t&&Ia(i,a,{get:()=>e[a],enumerable:!(s=Lo(e,a))||s.enumerable});return i};var No=(i,e,t)=>(t=i!=null?Do(Io(i)):{},xo(e||!i||!i.__esModule?Ia(t,"default",{value:i,enumerable:!0}):t,i));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js");const en="2.0.100";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH_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"})(exports.VideoFormat||(exports.VideoFormat={}));var se;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(se||(se={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var x;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(x||(x={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(exports.Surface||(exports.Surface={}));var Oo=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 Mo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Oo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,a,n;(n=(a=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(r.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([s.getCastState()])).pipe(r.filterChanged(),r.map(Bo),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const c=s.getCurrentSession();r.assertNonNullable(c);const u=c.getCastDevice(),d=(n=c.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.isNullable(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,s,a;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Bo=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return r.assertNever(i)}};var Zi=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ea(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ne=function(i){try{return!!i()}catch(e){return!0}},Vo=Ne,Di=!Vo(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),tn=Di,sn=Function.prototype,Bs=sn.call,Fo=tn&&sn.bind.bind(Bs,Bs),Oe=tn?Fo:function(i){return function(){return Bs.apply(i,arguments)}},an=Oe,Uo=an({}.toString),jo=an("".slice),Li=function(i){return jo(Uo(i),8,-1)},Ho=Oe,Go=Ne,Yo=Li,es=Object,qo=Ho("".split),zo=Go(function(){return!es("z").propertyIsEnumerable(0)})?function(i){return Yo(i)=="String"?qo(i,""):es(i)}:es,Ri=function(i){return i==null},Wo=Ri,Qo=TypeError,ta=function(i){if(Wo(i))throw Qo("Can't call method on "+i);return i},Ko=zo,Jo=ta,Yt=function(i){return Ko(Jo(i))},Ct={},ti=function(i){return i&&i.Math==Math&&i},be=ti(typeof globalThis=="object"&&globalThis)||ti(typeof window=="object"&&window)||ti(typeof self=="object"&&self)||ti(typeof Zi=="object"&&Zi)||function(){return this}()||Zi||Function("return this")(),Vs=typeof document=="object"&&document.all,Xo=typeof Vs=="undefined"&&Vs!==void 0,rn={all:Vs,IS_HTMLDDA:Xo},nn=rn,Zo=nn.all,de=nn.IS_HTMLDDA?function(i){return typeof i=="function"||i===Zo}:function(i){return typeof i=="function"},el=be,tl=de,_a=el.WeakMap,il=tl(_a)&&/native code/.test(String(_a)),xa=de,on=rn,sl=on.all,it=on.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:xa(i)||i===sl}:function(i){return typeof i=="object"?i!==null:xa(i)},al=Ne,st=!al(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Dt={},rl=be,Na=it,Fs=rl.document,nl=Na(Fs)&&Na(Fs.createElement),ln=function(i){return nl?Fs.createElement(i):{}},ol=st,ll=Ne,ul=ln,un=!ol&&!ll(function(){return Object.defineProperty(ul("div"),"a",{get:function(){return 7}}).a!=7}),cl=st,dl=Ne,cn=cl&&dl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),hl=it,fl=String,pl=TypeError,at=function(i){if(hl(i))return i;throw pl(fl(i)+" is not an object")},ml=Di,ii=Function.prototype.call,Me=ml?ii.bind(ii):function(){return ii.apply(ii,arguments)},ia={},ts=ia,is=be,vl=de,Oa=function(i){return vl(i)?i:void 0},sa=function(i,e){return arguments.length<2?Oa(ts[i])||Oa(is[i]):ts[i]&&ts[i][e]||is[i]&&is[i][e]},bl=Oe,aa=bl({}.isPrototypeOf),Sl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",dn=be,ss=Sl,Ma=dn.process,Ba=dn.Deno,Va=Ma&&Ma.versions||Ba&&Ba.version,Fa=Va&&Va.v8,me,Ti;Fa&&(me=Fa.split("."),Ti=me[0]>0&&me[0]<4?1:+(me[0]+me[1]));!Ti&&ss&&(me=ss.match(/Edge\/(\d+)/),(!me||me[1]>=74)&&(me=ss.match(/Chrome\/(\d+)/),me&&(Ti=+me[1])));var gl=Ti,Ua=gl,yl=Ne,Tl=be,El=Tl.String,hn=!!Object.getOwnPropertySymbols&&!yl(function(){var i=Symbol();return!El(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Ua&&Ua<41}),$l=hn,fn=$l&&!Symbol.sham&&typeof Symbol.iterator=="symbol",kl=sa,wl=de,Al=aa,Pl=fn,Cl=Object,pn=Pl?function(i){return typeof i=="symbol"}:function(i){var e=kl("Symbol");return wl(e)&&Al(e.prototype,Cl(i))},Dl=String,ra=function(i){try{return Dl(i)}catch(e){return"Object"}},Ll=de,Rl=ra,Il=TypeError,na=function(i){if(Ll(i))return i;throw Il(Rl(i)+" is not a function")},_l=na,xl=Ri,Ii=function(i,e){var t=i[e];return xl(t)?void 0:_l(t)},as=Me,rs=de,ns=it,Nl=TypeError,Ol=function(i,e){var t,s;if(e==="string"&&rs(t=i.toString)&&!ns(s=as(t,i))||rs(t=i.valueOf)&&!ns(s=as(t,i))||e!=="string"&&rs(t=i.toString)&&!ns(s=as(t,i)))return s;throw Nl("Can't convert object to primitive value")},mn={exports:{}},ja=be,Ml=Object.defineProperty,Bl=function(i,e){try{Ml(ja,i,{value:e,configurable:!0,writable:!0})}catch(t){ja[i]=e}return e},Vl=be,Fl=Bl,Ha="__core-js_shared__",Ul=Vl[Ha]||Fl(Ha,{}),vn=Ul,Ga=vn;(mn.exports=function(i,e){return Ga[i]||(Ga[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 bn=mn.exports,jl=ta,Hl=Object,_i=function(i){return Hl(jl(i))},Gl=Oe,Yl=_i,ql=Gl({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return ql(Yl(e),t)},zl=Oe,Wl=0,Ql=Math.random(),Kl=zl(1 .toString),Sn=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Kl(++Wl+Ql,36)},Jl=be,Xl=bn,Ya=Be,Zl=Sn,eu=hn,tu=fn,Et=Jl.Symbol,os=Xl("wks"),iu=tu?Et.for||Et:Et&&Et.withoutSetter||Zl,Se=function(i){return Ya(os,i)||(os[i]=eu&&Ya(Et,i)?Et[i]:iu("Symbol."+i)),os[i]},su=Me,qa=it,za=pn,au=Ii,ru=Ol,nu=Se,ou=TypeError,lu=nu("toPrimitive"),uu=function(i,e){if(!qa(i)||za(i))return i;var t=au(i,lu),s;if(t){if(e===void 0&&(e="default"),s=su(t,i,e),!qa(s)||za(s))return s;throw ou("Can't convert object to primitive value")}return e===void 0&&(e="number"),ru(i,e)},cu=uu,du=pn,oa=function(i){var e=cu(i,"string");return du(e)?e:e+""},hu=st,fu=un,pu=cn,si=at,Wa=oa,mu=TypeError,ls=Object.defineProperty,vu=Object.getOwnPropertyDescriptor,us="enumerable",cs="configurable",ds="writable";Dt.f=hu?pu?function(e,t,s){if(si(e),t=Wa(t),si(s),typeof e=="function"&&t==="prototype"&&"value"in s&&ds in s&&!s[ds]){var a=vu(e,t);a&&a[ds]&&(e[t]=s.value,s={configurable:cs in s?s[cs]:a[cs],enumerable:us in s?s[us]:a[us],writable:!1})}return ls(e,t,s)}:ls:function(e,t,s){if(si(e),t=Wa(t),si(s),fu)try{return ls(e,t,s)}catch(a){}if("get"in s||"set"in s)throw mu("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var xi=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},bu=st,Su=Dt,gu=xi,qt=bu?function(i,e,t){return Su.f(i,e,gu(1,t))}:function(i,e,t){return i[e]=t,i},yu=bn,Tu=Sn,Qa=yu("keys"),la=function(i){return Qa[i]||(Qa[i]=Tu(i))},ua={},Eu=il,gn=be,$u=it,ku=qt,hs=Be,fs=vn,wu=la,Au=ua,Ka="Object already initialized",Us=gn.TypeError,Pu=gn.WeakMap,Ei,jt,$i,Cu=function(i){return $i(i)?jt(i):Ei(i,{})},Du=function(i){return function(e){var t;if(!$u(e)||(t=jt(e)).type!==i)throw Us("Incompatible receiver, "+i+" required");return t}};if(Eu||fs.state){var Te=fs.state||(fs.state=new Pu);Te.get=Te.get,Te.has=Te.has,Te.set=Te.set,Ei=function(i,e){if(Te.has(i))throw Us(Ka);return e.facade=i,Te.set(i,e),e},jt=function(i){return Te.get(i)||{}},$i=function(i){return Te.has(i)}}else{var vt=wu("state");Au[vt]=!0,Ei=function(i,e){if(hs(i,vt))throw Us(Ka);return e.facade=i,ku(i,vt,e),e},jt=function(i){return hs(i,vt)?i[vt]:{}},$i=function(i){return hs(i,vt)}}var Lu={set:Ei,get:jt,has:$i,enforce:Cu,getterFor:Du},Ru=Di,yn=Function.prototype,Ja=yn.apply,Xa=yn.call,Iu=typeof Reflect=="object"&&Reflect.apply||(Ru?Xa.bind(Ja):function(){return Xa.apply(Ja,arguments)}),_u=Li,xu=Oe,Tn=function(i){if(_u(i)==="Function")return xu(i)},En={},$n={},kn={}.propertyIsEnumerable,wn=Object.getOwnPropertyDescriptor,Nu=wn&&!kn.call({1:2},1);$n.f=Nu?function(e){var t=wn(this,e);return!!t&&t.enumerable}:kn;var Ou=st,Mu=Me,Bu=$n,Vu=xi,Fu=Yt,Uu=oa,ju=Be,Hu=un,Za=Object.getOwnPropertyDescriptor;En.f=Ou?Za:function(e,t){if(e=Fu(e),t=Uu(t),Hu)try{return Za(e,t)}catch(s){}if(ju(e,t))return Vu(!Mu(Bu.f,e,t),e[t])};var Gu=Ne,Yu=de,qu=/#|\.prototype\./,zt=function(i,e){var t=Wu[zu(i)];return t==Ku?!0:t==Qu?!1:Yu(e)?Gu(e):!!e},zu=zt.normalize=function(i){return String(i).replace(qu,".").toLowerCase()},Wu=zt.data={},Qu=zt.NATIVE="N",Ku=zt.POLYFILL="P",Ju=zt,er=Tn,Xu=na,Zu=Di,ec=er(er.bind),An=function(i,e){return Xu(i),e===void 0?i:Zu?ec(i,e):function(){return i.apply(e,arguments)}},ai=be,tc=Iu,ic=Tn,sc=de,ac=En.f,rc=Ju,bt=ia,nc=An,St=qt,tr=Be,oc=function(i){var e=function(t,s,a){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,a)}return tc(i,this,arguments)};return e.prototype=i.prototype,e},Ni=function(i,e){var t=i.target,s=i.global,a=i.stat,n=i.proto,o=s?ai:a?ai[t]:(ai[t]||{}).prototype,l=s?bt:bt[t]||St(bt,t,{})[t],c=l.prototype,u,d,h,f,p,b,m,v,S;for(f in e)u=rc(s?f:t+(a?".":"#")+f,i.forced),d=!u&&o&&tr(o,f),b=l[f],d&&(i.dontCallGetSet?(S=ac(o,f),m=S&&S.value):m=o[f]),p=d&&m?m:e[f],!(d&&typeof b==typeof p)&&(i.bind&&d?v=nc(p,ai):i.wrap&&d?v=oc(p):n&&sc(p)?v=ic(p):v=p,(i.sham||p&&p.sham||b&&b.sham)&&St(v,"sham",!0),St(l,f,v),n&&(h=t+"Prototype",tr(bt,h)||St(bt,h,{}),St(bt[h],f,p),i.real&&c&&(u||!c[f])&&St(c,f,p)))},js=st,lc=Be,Pn=Function.prototype,uc=js&&Object.getOwnPropertyDescriptor,ca=lc(Pn,"name"),cc=ca&&function(){}.name==="something",dc=ca&&(!js||js&&uc(Pn,"name").configurable),hc={EXISTS:ca,PROPER:cc,CONFIGURABLE:dc},Cn={},fc=Math.ceil,pc=Math.floor,mc=Math.trunc||function(e){var t=+e;return(t>0?pc:fc)(t)},vc=mc,da=function(i){var e=+i;return e!==e||e===0?0:vc(e)},bc=da,Sc=Math.max,gc=Math.min,yc=function(i,e){var t=bc(i);return t<0?Sc(t+e,0):gc(t,e)},Tc=da,Ec=Math.min,$c=function(i){return i>0?Ec(Tc(i),9007199254740991):0},kc=$c,ha=function(i){return kc(i.length)},wc=Yt,Ac=yc,Pc=ha,ir=function(i){return function(e,t,s){var a=wc(e),n=Pc(a),o=Ac(s,n),l;if(i&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in a)&&a[o]===t)return i||o||0;return!i&&-1}},Cc={includes:ir(!0),indexOf:ir(!1)},Dc=Oe,ps=Be,Lc=Yt,Rc=Cc.indexOf,Ic=ua,sr=Dc([].push),_c=function(i,e){var t=Lc(i),s=0,a=[],n;for(n in t)!ps(Ic,n)&&ps(t,n)&&sr(a,n);for(;e.length>s;)ps(t,n=e[s++])&&(~Rc(a,n)||sr(a,n));return a},Dn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],xc=_c,Nc=Dn,Oc=Object.keys||function(e){return xc(e,Nc)},Mc=st,Bc=cn,Vc=Dt,Fc=at,Uc=Yt,jc=Oc;Cn.f=Mc&&!Bc?Object.defineProperties:function(e,t){Fc(e);for(var s=Uc(t),a=jc(t),n=a.length,o=0,l;n>o;)Vc.f(e,l=a[o++],s[l]);return e};var Hc=sa,Gc=Hc("document","documentElement"),Yc=at,qc=Cn,ar=Dn,zc=ua,Wc=Gc,Qc=ln,Kc=la,rr=">",nr="<",Hs="prototype",Gs="script",Ln=Kc("IE_PROTO"),ms=function(){},Rn=function(i){return nr+Gs+rr+i+nr+"/"+Gs+rr},or=function(i){i.write(Rn("")),i.close();var e=i.parentWindow.Object;return i=null,e},Jc=function(){var i=Qc("iframe"),e="java"+Gs+":",t;return i.style.display="none",Wc.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Rn("document.F=Object")),t.close(),t.F},ri,bi=function(){try{ri=new ActiveXObject("htmlfile")}catch(e){}bi=typeof document!="undefined"?document.domain&&ri?or(ri):Jc():or(ri);for(var i=ar.length;i--;)delete bi[Hs][ar[i]];return bi()};zc[Ln]=!0;var In=Object.create||function(e,t){var s;return e!==null?(ms[Hs]=Yc(e),s=new ms,ms[Hs]=null,s[Ln]=e):s=bi(),t===void 0?s:qc.f(s,t)},Xc=Ne,Zc=!Xc(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),ed=Be,td=de,id=_i,sd=la,ad=Zc,lr=sd("IE_PROTO"),Ys=Object,rd=Ys.prototype,_n=ad?Ys.getPrototypeOf:function(i){var e=id(i);if(ed(e,lr))return e[lr];var t=e.constructor;return td(t)&&e instanceof t?t.prototype:e instanceof Ys?rd:null},nd=qt,xn=function(i,e,t,s){return s&&s.enumerable?i[e]=t:nd(i,e,t),i},od=Ne,ld=de,ud=it,cd=In,ur=_n,dd=xn,hd=Se,qs=hd("iterator"),Nn=!1,Ie,vs,bs;[].keys&&(bs=[].keys(),"next"in bs?(vs=ur(ur(bs)),vs!==Object.prototype&&(Ie=vs)):Nn=!0);var fd=!ud(Ie)||od(function(){var i={};return Ie[qs].call(i)!==i});fd?Ie={}:Ie=cd(Ie);ld(Ie[qs])||dd(Ie,qs,function(){return this});var On={IteratorPrototype:Ie,BUGGY_SAFARI_ITERATORS:Nn},pd=Se,md=pd("toStringTag"),Mn={};Mn[md]="z";var fa=String(Mn)==="[object z]",vd=fa,bd=de,Si=Li,Sd=Se,gd=Sd("toStringTag"),yd=Object,Td=Si(function(){return arguments}())=="Arguments",Ed=function(i,e){try{return i[e]}catch(t){}},Oi=vd?Si:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Ed(e=yd(i),gd))=="string"?t:Td?Si(e):(s=Si(e))=="Object"&&bd(e.callee)?"Arguments":s},$d=fa,kd=Oi,wd=$d?{}.toString:function(){return"[object "+kd(this)+"]"},Ad=fa,Pd=Dt.f,Cd=qt,Dd=Be,Ld=wd,Rd=Se,cr=Rd("toStringTag"),Bn=function(i,e,t,s){if(i){var a=t?i:i.prototype;Dd(a,cr)||Pd(a,cr,{configurable:!0,value:e}),s&&!Ad&&Cd(a,"toString",Ld)}},Id=On.IteratorPrototype,_d=In,xd=xi,Nd=Bn,Od=Ct,Md=function(){return this},Bd=function(i,e,t,s){var a=e+" Iterator";return i.prototype=_d(Id,{next:xd(+!s,t)}),Nd(i,a,!1,!0),Od[a]=Md,i},Vd=Ni,Fd=Me,Vn=hc,Ud=Bd,jd=_n,Hd=Bn,dr=xn,Gd=Se,hr=Ct,Fn=On,Yd=Vn.PROPER;Vn.CONFIGURABLE;Fn.IteratorPrototype;var ni=Fn.BUGGY_SAFARI_ITERATORS,Ss=Gd("iterator"),fr="keys",oi="values",pr="entries",qd=function(){return this},zd=function(i,e,t,s,a,n,o){Ud(t,e,s);var l=function(S){if(S===a&&f)return f;if(!ni&&S in d)return d[S];switch(S){case fr:return function(){return new t(this,S)};case oi:return function(){return new t(this,S)};case pr:return function(){return new t(this,S)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,h=d[Ss]||d["@@iterator"]||a&&d[a],f=!ni&&h||l(a),p=e=="Array"&&d.entries||h,b,m,v;if(p&&(b=jd(p.call(new i)),b!==Object.prototype&&b.next&&(Hd(b,c,!0,!0),hr[c]=qd)),Yd&&a==oi&&h&&h.name!==oi&&(u=!0,f=function(){return Fd(h,this)}),a)if(m={values:l(oi),keys:n?f:l(fr),entries:l(pr)},o)for(v in m)(ni||u||!(v in d))&&dr(d,v,m[v]);else Vd({target:e,proto:!0,forced:ni||u},m);return o&&d[Ss]!==f&&dr(d,Ss,f,{name:a}),hr[e]=f,m},Wd=function(i,e){return{value:i,done:e}},Qd=Yt,mr=Ct,Un=Lu;Dt.f;var Kd=zd,li=Wd,jn="Array Iterator",Jd=Un.set,Xd=Un.getterFor(jn);Kd(Array,"Array",function(i,e){Jd(this,{type:jn,target:Qd(i),index:0,kind:e})},function(){var i=Xd(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,li(void 0,!0)):t=="keys"?li(s,!1):t=="values"?li(e[s],!1):li([s,e[s]],!1)},"values");mr.Arguments=mr.Array;var Zd=Se,eh=Ct,th=Zd("iterator"),ih=Array.prototype,sh=function(i){return i!==void 0&&(eh.Array===i||ih[th]===i)},ah=Oi,vr=Ii,rh=Ri,nh=Ct,oh=Se,lh=oh("iterator"),Hn=function(i){if(!rh(i))return vr(i,lh)||vr(i,"@@iterator")||nh[ah(i)]},uh=Me,ch=na,dh=at,hh=ra,fh=Hn,ph=TypeError,mh=function(i,e){var t=arguments.length<2?fh(i):e;if(ch(t))return dh(uh(t,i));throw ph(hh(i)+" is not iterable")},vh=Me,br=at,bh=Ii,Sh=function(i,e,t){var s,a;br(i);try{if(s=bh(i,"return"),!s){if(e==="throw")throw t;return t}s=vh(s,i)}catch(n){a=!0,s=n}if(e==="throw")throw t;if(a)throw s;return br(s),t},gh=An,yh=Me,Th=at,Eh=ra,$h=sh,kh=ha,Sr=aa,wh=mh,Ah=Hn,gr=Sh,Ph=TypeError,gi=function(i,e){this.stopped=i,this.result=e},yr=gi.prototype,Ch=function(i,e,t){var s=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),c=gh(e,s),u,d,h,f,p,b,m,v=function(y){return u&&gr(u,"normal",y),new gi(!0,y)},S=function(y){return a?(Th(y),l?c(y[0],y[1],v):c(y[0],y[1])):l?c(y,v):c(y)};if(n)u=i.iterator;else if(o)u=i;else{if(d=Ah(i),!d)throw Ph(Eh(i)+" is not iterable");if($h(d)){for(h=0,f=kh(i);f>h;h++)if(p=S(i[h]),p&&Sr(yr,p))return p;return new gi(!1)}u=wh(i,d)}for(b=n?i.next:u.next;!(m=yh(b,u)).done;){try{p=S(m.value)}catch(y){gr(u,"throw",y)}if(typeof p=="object"&&p&&Sr(yr,p))return p}return new gi(!1)},Dh=oa,Lh=Dt,Rh=xi,Ih=function(i,e,t){var s=Dh(e);s in i?Lh.f(i,s,Rh(0,t)):i[s]=t},_h=Ni,xh=Ch,Nh=Ih;_h({target:"Object",stat:!0},{fromEntries:function(e){var t={};return xh(e,function(s,a){Nh(t,s,a)},{AS_ENTRIES:!0}),t}});var Oh=ia,Mh=Oh.Object.fromEntries,Bh={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},Vh=Bh,Fh=be,Uh=Oi,jh=qt,Tr=Ct,Hh=Se,Er=Hh("toStringTag");for(var gs in Vh){var $r=Fh[gs],ys=$r&&$r.prototype;ys&&Uh(ys)!==Er&&jh(ys,Er,gs),Tr[gs]=Tr.Array}var Gh=Mh,Yh=Gh,qh=Yh,zh=qh,ki=ea(zh),Z;(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"})(Z||(Z={}));var ve=(i,e=0,t=Z.OFFSET_P)=>{switch(t){case Z.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Z.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case Z.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:r.assertNever(t)}return i};const kr=(i,e)=>{var t;switch(e){case Z.OFFSET_P:return NaN;case Z.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case Z.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:r.assertNever(e)}};var P=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class K{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.merge(this.transitionEnded$,this.forceChanged$),this.state=e,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||r.isNonNullable(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 Wh=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return r.assertNever(i)}};var L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const Qh=5,Kh=5,Jh=500,wr=7e3;class Xh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new K(L.STOPPED),this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===x.Requested&&s!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(s)}break}default:r.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Wh(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Jh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===x.Applying||Math.abs(l-n)>Qh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.value,l=this.params.output.isBuffering$.getValue(),c=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==c&&this.params.output.isBuffering$.next(c),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Kh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const s=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(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(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.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:x.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)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,s;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(s=e.muted)!==null&&s!==void 0?s:a.muted};(n.volume!==a.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController: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 a,n,o;switch(e){case exports.VideoFormat.MPEG:{const d=s[e];r.assertNonNullable(d);const h=r.getHighestQuality(Object.keys(d));r.assertNonNullable(h);const f=d[h];r.assertNonNullable(f),a=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const d=s[e];r.assertNonNullable(d),a=d.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const d=s[e];r.assertNonNullable(d),a=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const d=s[e];r.assertNonNullable(d),a=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const d=s[e];r.assertNonNullable(d),a=ve(d.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:r.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:u}=this.params.meta;return r.isNonNullable(c)&&(l.metadata.title=c),r.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===x.Applying||s.state===x.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((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(wr).subscribe(()=>n(`timeout(${wr})`)))});Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===x.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const pa=i=>{i.removeAttribute("src"),i.load()},Zh=i=>{try{i.pause(),i.playbackRate=0,pa(i),i.remove()}catch(e){console.error(e)}};class ef{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 zs=window.WeakMap?new WeakMap:new ef,rt=i=>{let e=i.querySelector("video");const t=!!e;return e?pa(e):(e=document.createElement("video"),i.appendChild(e)),zs.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},nt=i=>{const e=zs.get(i);zs.delete(i),e?pa(i):Zh(i)},Le=(i,e,t,{equal:s=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=i.getState(),l=e(),c=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.subscribe(d=>{const h=i.getState();s(d,h)&&i.setState(d)},n)),s(l,o)||(t(o),c&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},n)),u},Wt=(i,e,t)=>Le(e,()=>i.loop,s=>{r.isNonNullable(s)&&(i.loop=s)},{onError:t}),ot=(i,e,t,s)=>Le(e,()=>({muted:i.muted,volume:i.volume}),a=>{r.isNonNullable(a)&&(i.muted=a.muted,i.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),Lt=(i,e,t,s)=>Le(e,()=>i.playbackRate,a=>{r.isNonNullable(a)&&(i.playbackRate=a)},{changed$:t,onError:s}),tf=i=>["__",i.language,i.label].join("|"),sf=(i,e)=>{if(i.id===e)return!0;const[t,s,a]=e.split("|");return i.language===s&&i.label===a};class Ge{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Le(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(Le(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(Le(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:a})),this.subscription.add(Le(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),r.filterChanged((s,a)=>s.length===a.length&&s.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),r.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),r.filterChanged()).subscribe(this.current$));const t=s=>{var a,n;return this.applyCueSettings((n=(a=s.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(s=>{var a,n;(a=s.track)===null||a===void 0||a.addEventListener("cuechange",t);const o=l=>{var c,u,d,h,f;const p=(u=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(s=>{var a;(a=s.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const a=s;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ge.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:a,label:n}=e,o=e.id?e.id:tf(e),l=this.externalTracks.has(o),c=o.includes("auto");return l?{id:o,type:"external",isAuto:c,language:a,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:c,language:a,label:n,url:(s=this.internalTracks.get(o))===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:a,isAuto:n})=>!this.internalTracks.has(s)&&!t.some(([,o])=>o.language===a&&o.isAuto===n)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(a=>a.id===s)).forEach(([,s])=>this.detach(s))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!sf(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){r.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){r.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),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 ma{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 Gn=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},Ar=i=>{const e=Gn(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},af=i=>{const e=Gn(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},rf=3;var nf=(i,e,t=rf)=>{let s=0,a=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,a=l,!t)return{from:s,to:a};for(let c=n-1;c>=0;c--)i.end(c)+t>=s&&(s=i.start(c));for(let c=n+1;c<i.length;c++)i.start(c)-t<=a&&(a=i.end(c))}}return{from:s,to:a}};const lt=i=>{const e=T=>r.fromEvent(i,T).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=r.merge(...t.map(T=>r.fromEvent(i,T))).pipe(r.map(T=>T.type==="ended"?i.readyState<2:i.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(i,"progress"),r.fromEvent(i,"timeupdate")).pipe(r.map(()=>nf(i.buffered,i.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),l=r.fromEvent(i,"volumechange").pipe(r.map(()=>({muted:i.muted,volume:i.volume}))),c=r.fromEvent(i,"ratechange").pipe(r.map(()=>i.playbackRate)),u=r.fromEvent(i,"error").pipe(r.filter(()=>!!(i.error||i.played.length)),r.map(()=>{var T;const E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(T=i.error)!==null&&T!==void 0?T:void 0}})),d=r.fromEvent(i,"timeupdate").pipe(r.map(()=>i.currentTime)),h=new r.Subject,f=.3;let p;d.subscribe(T=>{i.loop&&r.isNonNullable(p)&&r.isNonNullable(T)&&p>=i.duration-f&&T<=f&&h.next(p),p=T});const b=r.fromEvent(i,"enterpictureinpicture"),m=r.fromEvent(i,"leavepictureinpicture"),v=new r.ValueSubject(af(i));b.subscribe(()=>v.next(!0)),m.subscribe(()=>v.next(!1));const S=new r.ValueSubject(Ar(i));return r.fromEvent(i,"fullscreenchange").pipe(r.map(()=>Ar(i))).subscribe(S),{playing$:o,pause$:e("pause").pipe(r.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:r.fromEvent(i,"durationchange").pipe(r.map(()=>i.duration)),isBuffering$:s,currentBuffer$:a,volumeState$:l,playbackRateState$:c,inPiP$:v,inFullscreen$:S}};var Mi=i=>{switch(i){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}},of=Ni,lf=_i,uf=ha,cf=da;of({target:"Array",proto:!0},{at:function(e){var t=lf(this),s=uf(t),a=cf(e),n=a>=0?a:s+a;return n<0||n>=s?void 0:t[n]}});var df=sa,Yn=df,hf=Yn,ff=hf("Array","at"),pf=ff,mf=pf,vf=mf,bf=vf,De=ea(bf);let va=!1,Re={};const Sf=i=>{va=i},gf=()=>{Re={}},yf=i=>{i(Re)},ui=(i,e)=>{var t;va&&(Re.meta=(t=Re.meta)!==null&&t!==void 0?t:{},Re.meta[i]=e)};class ke{constructor(e){this.name=e}next(e){var t,s;if(!va)return;Re.series=(t=Re.series)!==null&&t!==void 0?t:{};const a=(s=Re.series[this.name])!==null&&s!==void 0?s:[];a.push([Date.now(),e]),Re.series[this.name]=a}}var et;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(et||(et={}));const Tf=new ke("best_bitrate"),Ef=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class $f{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const kf='Assertion "ABR Tracks is empty array" failed',Bi=(i,{container:e,throughput:t,tuning:s,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:c,history:u,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var f,p,b,m,v;r.assertNotEmptyArray(i,kf);const S=s.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*s.containerSizeFactor,height:e.height*S*s.containerSizeFactor},T=y&&r.videoSizeToQuality(y),E=s.considerPlaybackRate&&r.isNonNullable(l)?l:1,$=i.filter(D=>!r.isInvariantQuality(D.quality)).sort((D,w)=>r.isHigher(D.quality,w.quality)?-1:1),N=(p=De($,-1))===null||p===void 0?void 0:p.quality,O=(b=De($,0))===null||b===void 0?void 0:b.quality,V=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&r.isLower(a.max,a.min)||r.isNonNullable(a.min)&&O&&r.isHigher(a.min,O)||r.isNonNullable(a.max)&&N&&r.isLower(a.max,N),_=E*Ef(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),F={},C=$.filter(D=>(T?r.isLower(D.quality,T):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(D.bitrate)?t-n>=D.bitrate*_:!0)?s.lazyQualitySwitch&&r.isNonNullable(s.minBufferToSwitchUp)&&c&&!r.isInvariantQuality(c.quality)&&(o!=null?o:0)<s.minBufferToSwitchUp&&r.isHigher(D.quality,c.quality)?(F[D.quality]=et.Buffer,!1):!!d&&r.isHigherOrEqual(D.quality,d)?(F[D.quality]=et.DroppedFramesLimit,!1):V||(r.isNullable(a.max)||r.isLowerOrEqual(D.quality,a.max))&&(r.isNullable(a.min)||r.isHigherOrEqual(D.quality,a.min))?!0:(F[D.quality]=et.FitsQualityLimits,!1):(F[D.quality]=et.FitsThroughput,!1):(F[D.quality]=et.FitsContainer,!1))[0];C&&C.bitrate&&Tf.next(C.bitrate);const A=(m=C!=null?C:$[Math.ceil(($.length-1)/2)])!==null&&m!==void 0?m:i[0];A.quality!==((v=u==null?void 0:u.last)===null||v===void 0?void 0:v.quality)&&h({message:`
7
7
  [available tracks]
8
8
  ${i.map(D=>`{ id: ${D.id}, quality: ${D.quality}, bitrate: ${D.bitrate} }`).join(`
9
9
  `)}
@@ -13,13 +13,13 @@
13
13
  `)}
14
14
 
15
15
  [limit params]
16
- containerQualityLimit: ${E},
16
+ containerQualityLimit: ${T},
17
17
  throughput: ${t},
18
18
  reserve: ${n},
19
19
  playbackRate: ${l},
20
- playbackRateFactor: ${T},
20
+ playbackRateFactor: ${E},
21
21
  forwardBufferHealth: ${o},
22
- bitrateFactor: ${N},
22
+ bitrateFactor: ${_},
23
23
  minBufferToSwitchUp: ${s.minBufferToSwitchUp},
24
24
  droppedVideoMaxQualityLimit: ${d},
25
25
  limitsAreInvalid: ${V},
@@ -34,7 +34,7 @@
34
34
  [selected track] ${A==null?void 0:A.quality}
35
35
  `});const Y=A&&u&&u.history[A.id]&&r.now()-u.history[A.id]<=s.trackCooldown&&(!u.last||A.id!==u.last.id);if(A!=null&&A.id&&u&&!Y&&u.recordSelection(A),Y&&(u!=null&&u.last)){const D=u.last;return u==null||u.recordSwitch(D),h({message:`
36
36
  [last selected] ${D==null?void 0:D.quality}
37
- `}),D}return u==null||u.recordSwitch(A),A};var Pe=i=>new URL(i).hostname;const Pr=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 ut=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!Pr(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return Pr(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function ae(){return r.now()}function qn(i){return ae()-i}function Cr(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,a=o=>s.test(o);return{resolve:(o,l,c=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return c&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function wf(i,e,t){const s=(...a)=>{t.apply(null,a),i.removeEventListener(e,s)};i.addEventListener(e,s)}function yi(i,e,t,s){const a=window.XMLHttpRequest;let n,o,l,c=!1,u=0,d,h,f=!1,p="arraybuffer",b=7e3,m=2e3,v=()=>{if(c)return;r.assertNonNullable(d);const C=qn(d);let A;if(C<m){A=m-C,setTimeout(v,A);return}m*=2,m>b&&(m=b),o&&o.abort(),o=new a,x()};const S=C=>(n=C,j),y=C=>(h=C,j),E=()=>(p="json",j),T=()=>{if(!c){if(--u>=0){v(),s&&s();return}c=!0,h&&h(),t&&t()}},$=C=>(f=C,j),x=()=>{d=ae(),o=new a,o.open("get",i);let C=0,A,Y=0;const D=()=>(r.assertNonNullable(d),Math.max(d,Math.max(A||0,Y||0)));if(n&&o.addEventListener("progress",w=>{const U=ae();n.updateChunk&&w.loaded>C&&(n.updateChunk(D(),w.loaded-C),C=w.loaded,A=U)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(c)return;r.assertNonNullable(o);const w=o.status;if(w>=200&&w<300){if(o.response.byteLength&&n){const U=o.response.byteLength-C;U&&n.updateChunk&&n.updateChunk(D(),U)}o.responseType==="json"&&!Object.values(o.response).length?T():(h&&h(),e(o.response))}else T()}),o.addEventListener("error",()=>{T()}),f){const w=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=ae(),o.removeEventListener("readystatechange",w))};o.addEventListener("readystatechange",w)}return o.responseType=p,o.send(),j},j={withBitrateReporting:S,withParallel:$,withJSONResponse:E,withRetryCount:C=>(u=C,j),withRetryInterval:(C,A)=>(r.isNonNullable(C)&&(m=C),r.isNonNullable(A)&&(b=A),j),withTimeout:C=>(l=C,j),withFinally:y,send:x,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return j}const Af=100,Pf=2e3,Cf=500;let Df=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-Cf;if(t-e>Pf){let s=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const c=n.bytes*o/l;a+=c,n.start=t,n.bytes-=c}}}if(a>0&&s>0){const n=a*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(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>Af&&(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 Rf{constructor(e,t,s,a,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=a,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=ae(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=c=>{e._complete=1,e._responseData=c,e._downloadTime=ae()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=yi(t,n,()=>a("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_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=ae();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,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=a,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=a,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const ci=1e4,Ts=3,Lf=6e4,If=10,xf=1,_f=500;class Nf{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 Df(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Cr(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=Cr(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 a;s!==0&&(a=t.buffered.start(s-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let s,a,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!a||n.bitrate>a.bitrate)&&(a=n):(!s||s.bitrate>n.bitrate)&&(s=n));return a||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{wf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Rf(Ts,ci,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:a}=this.params;let n=!1,o=null,l=null,c=null,u=null,d=!1;const h=()=>{const T=n&&(!d||d===this.rep);return T||t("Not running!"),T},f=(T,$,x)=>{c&&c.abort(),c=yi(this.urlResolver.resolve(T,!1),$,x,()=>this._retryCallback()).withTimeout(ci).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ts).withFinally(()=>{c=null}).send()},p=(T,$,x)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),$,x,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=T=>{const $=s.playbackRate;s.playbackRate!==T&&(t(`Playback rate switch: ${$}=>${T}`),s.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const x=ae()-1e4;let _=0;for(let N=0;N<this.bufferStates.length;N++){const F=this.bufferStates[N];T=Math.min(T,F.buf),F.ts<x&&_++}this.bufferStates.splice(0,_),t(`update playback rate; minBuffer=${T} drop=${_} jitter=${this.sourceJitter}`);let V=T-xf;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?b(1.15):V>1?b(1.1):V>.3?b(1.05):b(1)}},S=T=>{let $;const x=()=>$&&$.start?$.start.length:0,_=w=>$.start[w]/1e3,V=w=>$.dur[w]/1e3,N=w=>$.fragIndex+w,F=(w,U)=>({chunkIdx:N(w),startTS:_(w),dur:V(w),discontinuity:U}),j=()=>{let w=0;if($&&$.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=U;this.sourceJitter>1&&(J+=this.sourceJitter-1);let ee=$.dur.length-1;for(;ee>=0&&(J-=$.dur[ee],!(J<=0));--ee);w=Math.min(ee,$.dur.length-1-W),w=Math.max(w,0)}return F(w,!0)},C=w=>{const U=x();if(!(U<=0)){if(r.isNonNullable(w)){for(let W=0;W<U;W++)if(_(W)>w)return F(W)}return j()}},A=w=>{const U=x(),W=w?w.chunkIdx+1:0,J=W-$.fragIndex;if(!(U<=0)){if(!w||J<0||J-U>If)return t(`Resync: offset=${J} bChunks=${U} chunk=`+JSON.stringify(w)),j();if(!(J>=U))return F(W-$.fragIndex,!1)}},Y=(w,U,W)=>{u&&u.abort(),u=yi(this.urlResolver.resolve(w,!0,this.lowLatency),U,W,()=>this._retryCallback()).withTimeout(ci).withRetryCount(Ts).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,U)=>{Y(T,W=>{if(!h())return;$=W;const J=!!$.lowLatency;J!==this.lowLatency&&m(J);let ee=0;for(let ge=0;ge<$.dur.length;++ge)ee+=$.dur[ge];ee>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/$.dur.length)),a({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,w(C(U))},()=>this._handleNetworkError())},nextChunk:A}},y=()=>{n=!1,l&&l.abort(),c&&c.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{const{videoElement:$,logger:x}=this.params;let _=S(e.jidxUrl),V,N,F,j,C=0,A,Y,D;const w=()=>{A&&(clearTimeout(A),A=void 0);const B=Math.max(_f,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=C+B,re=ae(),ne=Math.min(1e4,ie-re);C=re;const dt=()=>{u||h()&&_.seek(()=>{h()&&(C=ae(),U(),w())})};ne>0?A=window.setTimeout(()=>{this.paused?w():dt()},ne):dt()},U=()=>{let B;for(;B=_.nextChunk(j);)j=B,Lt(B);const ie=_.nextChunk(F);if(ie){if(F&&ie.discontinuity){x("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}ge(ie)}else w()},W=(B,ie)=>{if(!h()||!this.sourceBuffer)return;let re,ne,dt;const It=Ce=>{window.setTimeout(()=>{h()&&W(B,ie)},Ce)};if(this.sourceBuffer.updating)x("Source buffer is updating; delaying appendBuffer"),It(100);else{const Ce=ae(),oe=$.currentTime;!this.paused&&$.buffered.length>1&&Y===oe&&Ce-D>500&&(x("Stall suspected; trying to fix"),this._fixupStall()),Y!==oe&&(Y=oe,D=Ce);const ht=this._getBufferSizeSec();if(ht>30)x(`Buffered ${ht} seconds; delaying appendBuffer`),It(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:Ce,buf:ht}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(xt){if(xt.name==="QuotaExceededError")x("QuotaExceededError; delaying appendBuffer"),dt=this.sourceBuffer.buffered.length,dt!==0&&(re=this.sourceBuffer.buffered.start(0),ne=oe,ne-re>4&&this.sourceBuffer.remove(re,ne-3)),It(1e3);else throw xt}}},J=()=>{N&&V&&(x([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(F)]),W(N,function(){N=null,U()}))},ee=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),ge=B=>{h()&&p(ee(B),(ie,re)=>{if(h()){if(re/=1e3,N=ie,F=B,o=B.startTS,re){const ne=Math.min(10,B.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ne:ne}J()}},()=>this._handleNetworkError())},Lt=B=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(B),!1)))},ct=B=>{h()&&(e.cachedHeader=B,W(B,()=>{V=!0,J()}))};n=!0,_.seek(B=>{if(h()){if(C=ae(),!B){w();return}j=B,!r.isNullable(T)||B.startTS>T?ge(B):(F=B,U())}},T),e.cachedHeader?ct(e.cachedHeader):f(e.headerUrl,ct,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,p,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),b=h/this.bitrate,p>10&&b>.8||p>15&&b>.5||p>20&&b>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const b=ae();if(this.chunkRateEstimator.addInterval(f,b,p)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:b-f,speed:v}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,c=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(c&&h>l&&qn(o)<3e4)return;s(h)}c=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=ae();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=yi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ci).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;ut(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,l.push(c))}),l.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.bitrate}),l):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=n(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))},Lf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class zn{constructor(){this.onDroopedVideoFramesLimit$=new r.Subject,this.subscription=new r.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new r.Subject,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&&!r.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),a=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(a-n)/a;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&r.isHigher(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(r.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=r.interval(this.droppedFramesChecker.checkTime).pipe(r.filter(()=>this.playing),r.filter(()=>{const a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(r.debounce(this.droppedFramesChecker.checkTime)),s=r.merge(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 a=(s=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>r.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:a}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 I;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(I||(I={}));const Of=[I.PAUSED,I.PLAYING,I.READY],Mf=[I.PAUSED,I.PLAYING,I.READY];class Bf{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(I.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Ge,this.droppedFramesManager=new zn,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new ma,this._dashCb=a=>{var n,o,l,c;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,d=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Mi(h.name))!==null&&o!==void 0?o:r.videoSizeToQuality(h.video),b=h.bitrate/1e3,m={...h.video};if(!p)continue;const v={id:f,quality:p,bitrate:b,size:m};d.push({track:v,representation:h})}this.representations$.next(d),this.params.output.availableVideoTracks$.next(d.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===I.MANIFEST_READY&&this.videoState.setState(I.MANIFEST_READY);break}case"qualitySwitch":{const u=a.quality,d=(c=this.representations$.getValue().find(({representation:h})=>h===u))===null||c===void 0?void 0:c.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),r.isNonNullable(d)&&this.params.output.currentVideoTrack$.next(d);break}case"bandwidth":{const{size:u,duration:d}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,d);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration||0),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(c)};`}),o===exports.PlaybackState.STOPPED){a!==I.STOPPED&&(this.videoState.startTransitionTo(I.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(I.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Mf.includes(a)&&(u||d)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&c.state===O.Requested&&Of.includes(a)){this.seek(c.position-this.liveOffset.getTotalPausedTime());return}switch(a){case I.STOPPED:this.videoState.startTransitionTo(I.MANIFEST_READY),this.dash.attachSource(ve(this.params.source.url));return;case I.MANIFEST_READY:this.videoState.startTransitionTo(I.READY),this.prepare();break;case I.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(I.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(I.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(I.PAUSED)})}return;case I.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(I.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case I.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(I.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(I.PAUSED)}),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.dash.reinit(ve(this.params.source.url,h))}return;default:return r.assertNever(a)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=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(Pe(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=lt(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(r.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===I.READY&&this.videoState.setState(I.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(I.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===O.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(I.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(Wt(this.video,this.params.desiredState.isLooped,t)).add(ot(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Rt(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:a}})=>{const n=a&&r.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case I.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case I.MANIFEST_READY:case I.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case I.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case I.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.observableFrom(["init"])).pipe(r.debounce(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),nt(this.video)}createLiveDashPlayer(){const e=new Nf({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,a,n,o;const l=this.representations$.getValue(),c=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(a=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!u&&r.isNonNullable(c)?c:Bi(l.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}),h=d==null?void 0:d.id,f=this.params.desiredState.videoTrack.getTransition(),p=(n=this.params.desiredState.videoTrack.getState())===null||n===void 0?void 0:n.id,b=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(f||h!==p)&&this.setVideoTrack(d),b&&this.setAutoQuality(u),f||b||h!==p){const m=(o=l.find(({track:v})=>v.id===h))===null||o===void 0?void 0:o.representation;r.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:a})=>a.id===e.id))===null||t===void 0?void 0:t.representation;r.assertNonNullable(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(),a=t===exports.PlaybackState.PAUSED&&s===I.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ve(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var te;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(te||(te={}));var $e;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})($e||($e={}));var wi;(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"})(wi||(wi={}));var ce;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ce||(ce={}));var L;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(L||(L={}));var At;(function(i){i.MP4="mp4",i.WEBM="webm"})(At||(At={}));var Ai;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Ai||(Ai={}));var z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));var $t=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const a=i.start(s)*1e3,n=i.end(s)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Vf=300,Ff=(i,e=Vf)=>new r.Observable(t=>{const{width:s,height:a}=i.getBoundingClientRect();if(t.next({width:s,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(r.debounceFn(o=>{const l=o[0];if(!l)return;let c,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,c=l.contentBoxSize[0].inlineSize):l.contentRect&&(c=l.contentRect.width,u=l.contentRect.height),r.isNonNullable(c)&&r.isNonNullable(u)&&t.next({width:c,height:u})},e));return n.observe(i),()=>n.disconnect()});class Dr{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 a=0,n=s.length;a<n;a++)if(s[a].callback===t){s.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let a=0,n=s.length;a<n;a++){const o=s[a];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Wn extends Dr{constructor(){super(),this.listeners||Dr.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Qn=class{constructor(){Object.defineProperty(this,"signal",{value:new Wn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let 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(a){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&&(Qn.prototype[Symbol.toStringTag]="AbortController",Wn.prototype[Symbol.toStringTag]="AbortSignal");function Kn(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 Uf(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Kn({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,d){let h;d&&d.signal&&(h=d.signal,delete d.signal);const f=new t(u,d);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(c,u)=>{const d=n&&n.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(d.aborted)return Promise.reject(h);const f=new Promise((p,b)=>{d.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(c,u)])}return o(c,u)},Request:n}}const Vi=Kn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jn=Vi?Uf({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ht=Vi?Jn.fetch:window.fetch;Vi?Jn.Request:window.Request;const wt=Vi?Qn:window.AbortController;var Ws=(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 jf=(i,e={})=>{const s=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Hf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Rr=Hf?jf:window.requestIdleCallback;var Es,$s;const Gf=16;let Xn=!1;try{Xn=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(($s=(Es=navigator.userAgent.match(/Version\/(\d+)/))===null||Es===void 0?void 0:Es[1])!==null&&$s!==void 0?$s:"",10)<=Gf}catch(i){console.error(i)}class Yf{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const 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:r.ErrorCategory.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 a={operation:"append",data:e,signal:t,callback:s};this.queue.push(a),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:s,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let s;Xn&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!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(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r.assertNever(t)}}}var Lr=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class he{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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Zn extends he{}class qf extends he{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 zf extends he{parseChildrenBoxes(){return Ye(this.content)}}class Wf extends he{parseChildrenBoxes(){return Ye(this.content)}}class Qf extends he{constructor(e){super(e),this.data=this.content}}class Ve extends he{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Kf extends Ve{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 a=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:c})}}}class Jf extends he{parseChildrenBoxes(){return Ye(this.content)}}class Xf extends he{parseChildrenBoxes(){return Ye(this.content)}}var tt;(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"})(tt||(tt={}));class Zf extends Ve{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=tt.MONOSCOPIC;break;case 1:this.stereoMode=tt.TOP_BOTTOM;break;case 2:this.stereoMode=tt.LEFT_RIGHT;break;case 3:this.stereoMode=tt.STEREO_CUSTOM;break;case 4:this.stereoMode=tt.RIGHT_LEFT;break}this.cursor+=1}}class ep extends Ve{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class tp extends Ve{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class ip extends he{parseChildrenBoxes(){return Ye(this.content)}}class sp extends Ve{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 ap extends he{parseChildrenBoxes(){return Ye(this.content)}}class rp extends he{parseChildrenBoxes(){return Ye(this.content)}}class np extends Ve{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class op extends he{parseChildrenBoxes(){return Ye(this.content)}}class lp extends Ve{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 up extends Ve{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 cp extends Ve{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 dp={ftyp:qf,moov:zf,moof:Wf,mdat:Qf,sidx:Kf,trak:Jf,mdia:ip,mfhd:np,tkhd:sp,traf:op,tfhd:lp,tfdt:up,trun:cp,minf:ap,sv3d:Xf,st3d:Zf,prhd:ep,proj:rp,equi:tp,unknown:Zn};class hp{createBox(e,t){const s=dp[e];return s?new s(t):new Zn(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Fi.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Fi=new hp;function Ft(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(o=>o.charCodeAt(0));let a=i.byteOffset,n=[];for(;a<t.byteLength;){if(t[a]===s[n.length]?n.push(t[a]):n=[],n.length===4){const l=new DataView(i.buffer,a-7,4).getUint32(0);return a-7+l>i.buffer.byteLength?null:Fi.createBox(e,new DataView(i.buffer,a-7))}a++}return null}function Qs(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const a=Ft(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(a)t.push(a),s=a.source.byteOffset+a.size;else break}return t}function Ye(i){const e=[];let t=0;for(;t<i.byteLength;){const s=Fi.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const fp=new TextDecoder("ascii"),pp=i=>fp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",mp=i=>{const e=Fi.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:L.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},vp=i=>{const e=Qs(i,"mdat"),t=Qs(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],a=e[e.length-1],n=s.source.byteOffset,l=a.source.byteOffset-s.source.byteOffset+a.size;return new DataView(i.buffer,n,l)},bp=(i,e)=>{const t=Qs(i,"traf"),s=t[t.length-1].children.find(c=>c.type==="tfhd"),a=t[t.length-1].children.find(c=>c.type==="tfdt"),n=t[t.length-1].children.find(c=>c.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((c,u)=>c+u,0):o=s.defaultSampleDuration*n.sampleCount,(Number(a.baseMediaDecodeTime)+o)/e*1e3},Sp=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Ai.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ft(i,"sv3d")){e.is3dVideo=!0;const s=Ft(i,"st3d");s&&(e.stereoMode=s.stereoMode);const a=Ft(i,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=Ft(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},gp={validateData:pp,parseInit:Sp,getIndexRange:()=>{},parseSegments:mp,parseFeedableSegmentChunk:vp,getSegmentEndTime:bp};var g;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.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"})(g||(g={}));var k;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(k||(k={}));const Ir={[g.EBML]:{type:k.Master},[g.EBMLVersion]:{type:k.UnsignedInteger},[g.EBMLReadVersion]:{type:k.UnsignedInteger},[g.EBMLMaxIDLength]:{type:k.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[g.DocType]:{type:k.String},[g.DocTypeVersion]:{type:k.UnsignedInteger},[g.DocTypeReadVersion]:{type:k.UnsignedInteger},[g.Void]:{type:k.Binary},[g.Segment]:{type:k.Master},[g.SeekHead]:{type:k.Master},[g.Seek]:{type:k.Master},[g.SeekID]:{type:k.Binary},[g.SeekPosition]:{type:k.UnsignedInteger},[g.Info]:{type:k.Master},[g.TimestampScale]:{type:k.UnsignedInteger},[g.Duration]:{type:k.Float},[g.Tracks]:{type:k.Master},[g.TrackEntry]:{type:k.Master},[g.Video]:{type:k.Master},[g.Projection]:{type:k.Master},[g.ProjectionType]:{type:k.UnsignedInteger},[g.ProjectionPrivate]:{type:k.Master},[g.Chapters]:{type:k.Master},[g.Cluster]:{type:k.Master},[g.Timestamp]:{type:k.UnsignedInteger},[g.SilentTracks]:{type:k.Master},[g.SilentTrackNumber]:{type:k.UnsignedInteger},[g.Position]:{type:k.UnsignedInteger},[g.PrevSize]:{type:k.UnsignedInteger},[g.SimpleBlock]:{type:k.Binary},[g.BlockGroup]:{type:k.Master},[g.EncryptedBlock]:{type:k.Binary},[g.Attachments]:{type:k.Master},[g.Tags]:{type:k.Master},[g.Cues]:{type:k.Master},[g.CuePoint]:{type:k.Master},[g.CueTime]:{type:k.UnsignedInteger},[g.CueTrackPositions]:{type:k.Master},[g.CueTrack]:{type:k.UnsignedInteger},[g.CueClusterPosition]:{type:k.UnsignedInteger},[g.CueRelativePosition]:{type:k.UnsignedInteger},[g.CueDuration]:{type:k.UnsignedInteger},[g.CueBlockNumber]:{type:k.UnsignedInteger},[g.CueCodecState]:{type:k.UnsignedInteger},[g.CueReference]:{type:k.Master},[g.CueRefTime]:{type:k.UnsignedInteger}},eo=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=Pi(i,t),a=s in Ir,n=a?Ir[s].type:k.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const c=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,d=Pi(c),h=u*2**((l-1)*8)+d,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:a?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},Pi=(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},we=(i,e)=>{switch(e){case k.SignedInteger:return i.getInt8(0);case k.UnsignedInteger:return Pi(i);case k.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(i);case k.UTF8:return new TextDecoder("utf-8").decode(i);case k.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case k.Master:return i;case k.Binary:return i;default:r.assertNever(e)}},Pt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),a=eo(s);if(!e(a))return;a.type===k.Master&&Pt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},yp=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,s;const a=eo(i);return Pt(a.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=we(l,o):n===g.DocType?t=we(l,o):n===g.DocTypeReadVersion&&(s=we(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},to=[g.Info,g.SeekHead,g.Tracks,g.TrackEntry,g.Video,g.Projection,g.ProjectionType,g.ProjectionPrivate,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],Tp=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],Ep=i=>{let e,t,s,a,n=!1,o=!1,l=!1,c,u,d=!1;const h=0;return Pt(i,({tag:f,type:p,value:b,valueSize:m})=>{if(f===g.SeekID){const v=we(b,p);u=Pi(v)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=b.byteOffset,t=b.byteOffset+m):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?s=we(b,p):f===g.Duration?a=we(b,p):f===g.SeekPosition&&u===g.Cues?c=we(b,p):f===g.Tracks?Pt(b,({tag:v,type:S,value:y})=>v===g.ProjectionType?(d=we(y,S)===1,!1):!0):n&&o&&to.includes(f)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:h,projectionType:Ai.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},$p=i=>{if(r.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kp=(i,e)=>{let t=!1,s=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return Pt(i,({tag:l,type:c,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&a(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=we(u,c));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=we(u,c));break;default:t&&to.includes(l)&&(s=!0)}return!(t&&s)}),o&&a(o)&&n.push(o),n.map((l,c)=>{const{time:u,position:d}=l,h=n[c+1];return{status:L.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},wp=i=>{let e=0,t=!1;try{Pt(i,s=>s.tag===g.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Tp.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ap={validateData:yp,parseInit:Ep,getIndexRange:$p,parseSegments:kp,parseFeedableSegmentChunk:wp};var Pp=it,Cp=Ri,Dp=Se,Rp=Dp("match"),Lp=function(i){var e;return Pp(i)&&((e=i[Rp])!==void 0?!!e:Cp(i)=="RegExp")},Ip=Oi,xp=String,_p=function(i){if(Ip(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return xp(i)},Np=at,Op=function(){var i=Np(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},Mp=Me,Bp=Be,Vp=aa,Fp=Op,xr=RegExp.prototype,Up=function(i){var e=i.flags;return e===void 0&&!("flags"in xr)&&!Bp(i,"flags")&&Vp(xr,i)?Mp(Fp,i):e},ba=Oe,jp=xi,Hp=Math.floor,ks=ba("".charAt),Gp=ba("".replace),ws=ba("".slice),Yp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qp=/\$([$&'`]|\d{1,2})/g,zp=function(i,e,t,s,a,n){var o=t+i.length,l=s.length,c=qp;return a!==void 0&&(a=jp(a),c=Yp),Gp(n,c,function(u,d){var h;switch(ks(d,0)){case"$":return"$";case"&":return i;case"`":return ws(e,0,t);case"'":return ws(e,o);case"<":h=a[ws(d,1,-1)];break;default:var f=+d;if(f===0)return u;if(f>l){var p=Hp(f/10);return p===0?u:p<=l?s[p-1]===void 0?ks(d,1):s[p-1]+ks(d,1):u}h=s[f-1]}return h===void 0?"":h})},Wp=Ni,Qp=Me,Sa=Oe,_r=ta,Kp=de,Jp=Li,Xp=Lp,gt=_p,Zp=Ii,em=Up,tm=zp,im=Se,sm=im("replace"),am=TypeError,io=Sa("".indexOf),rm=Sa("".replace),Nr=Sa("".slice),nm=Math.max,Or=function(i,e,t){return t>i.length?-1:e===""?t:io(i,e,t)};Wp({target:"String",proto:!0},{replaceAll:function(e,t){var s=_r(this),a,n,o,l,c,u,d,h,f,p=0,b=0,m="";if(!Jp(e)){if(a=Xp(e),a&&(n=gt(_r(em(e))),!~io(n,"g")))throw am("`.replaceAll` does not allow non-global regexes");if(o=Zp(e,sm),o)return Qp(o,e,s,t);if(a)return rm(gt(s),e,t)}for(l=gt(s),c=gt(e),u=Kp(t),u||(t=gt(t)),d=c.length,h=nm(1,d),p=Or(l,c,0);p!==-1;)f=u?gt(t(c,p,l)):tm(c,l,p,[],void 0,t),m+=Nr(l,b,p)+f,b=p+d,p=Or(l,c,p+h);return b<l.length&&(m+=Nr(l,b)),m}});var om=Yn,lm=om("String","replaceAll"),um=lm,cm=um,dm=cm,hm=dm,Mr=ea(hm);const fm=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Br=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const c=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(c)?0:c)*l},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),a=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],a),hours:e(s==null?void 0:s[6],a),minutes:e(s==null?void 0:s[7],a),seconds:e(s==null?void 0:s[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Tt=(i,e)=>{let t=i;t=Mr(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(s)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=Mr(t,o,(l,c)=>r.isNullable(n)?l:r.isNullable(c)?n:n.padStart(parseInt(c,10),"0"))}return t},pm=(i,e)=>{var t,s,a,n,o,l,c,u,d,h,f,p,b,m,v,S,y,E,T,$,x,_,V,N,F,j,C,A,Y,D,w,U,W,J,ee,ge,Lt,ct,B,ie,re,ne;const It=new DOMParser().parseFromString(i,"application/xml"),Ce={video:[],audio:[],text:[]},oe=It.children[0],ht=oe.getElementsByTagName("Period")[0],xt=(a=(s=(t=oe.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&a!==void 0?a:"",uo=ht.children,co=oe.getAttribute("type")==="dynamic",Ta=oe.getAttribute("availabilityStartTime"),ho=Ta?new Date(Ta).getTime():void 0;let qe;const Ea=oe.getAttribute("mediaPresentationDuration"),$a=ht.getAttribute("duration"),Ui=oe.getElementsByTagName("vk:Attrs")[0],ka=Ui==null?void 0:Ui.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Ea)qe=Br(Ea);else if($a){const fe=Br($a);r.isNonNullable(fe)&&(qe=fe)}else ka&&(qe=parseInt(ka,10));let fo=0;const ji=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],po=ji.includes(wi.WEBM_AS_IN_FFMPEG)||ji.includes(wi.WEBM_AS_IN_SPEC)?At.WEBM:At.MP4;for(const fe of uo){const Qt=fe.getAttribute("mimeType"),mo=fe.getAttribute("codecs"),wa=(l=fe.getAttribute("contentType"))!==null&&l!==void 0?l:Qt==null?void 0:Qt.split("/")[0],vo=(u=(c=fe.getAttribute("profiles"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[],Aa=fe.querySelectorAll("Representation"),bo=fe.querySelector("SegmentTemplate");if(wa===te.TEXT){for(const X of Aa){const Fe=X.getAttribute("id")||"",Kt=fe.getAttribute("lang"),ft=(f=(h=(d=X.querySelector("BaseURL"))===null||d===void 0?void 0:d.textContent)===null||h===void 0?void 0:h.trim())!==null&&f!==void 0?f:"",Hi=new URL(ft||xt,e).toString(),Gi=Fe.includes("_auto");Ce[te.TEXT].push({id:Fe,lang:Kt,isAuto:Gi,kind:te.TEXT,url:Hi})}continue}for(const X of Aa){const Fe=(p=X.getAttribute("mimeType"))!==null&&p!==void 0?p:Qt,Kt=(m=(b=X.getAttribute("codecs"))!==null&&b!==void 0?b:mo)!==null&&m!==void 0?m:"",ft=(S=(v=X.getAttribute("contentType"))!==null&&v!==void 0?v:Fe==null?void 0:Fe.split("/")[0])!==null&&S!==void 0?S:wa,Hi=(E=(y=fe.getAttribute("profiles"))===null||y===void 0?void 0:y.split(","))!==null&&E!==void 0?E:[],Gi=parseInt((T=X.getAttribute("width"))!==null&&T!==void 0?T:"",10),Pa=parseInt(($=X.getAttribute("height"))!==null&&$!==void 0?$:"",10),Ca=parseInt((x=X.getAttribute("bandwidth"))!==null&&x!==void 0?x:"",10)/1e3,Da=(_=X.getAttribute("frameRate"))!==null&&_!==void 0?_:"",So=(V=X.getAttribute("quality"))!==null&&V!==void 0?V:void 0,go=Da?fm(Da):void 0,yo=(N=X.getAttribute("id"))!==null&&N!==void 0?N:(fo++).toString(10),To=ft==="video"?`${Pa}p`:ft==="audio"?`${Ca}Kbps`:Kt,Eo=`${yo}@${To}`,$o=(C=(j=(F=X.querySelector("BaseURL"))===null||F===void 0?void 0:F.textContent)===null||j===void 0?void 0:j.trim())!==null&&C!==void 0?C:"",Ra=new URL($o||xt,e).toString(),ko=[...ji,...vo,...Hi];let Yi;const wo=X.querySelector("SegmentBase"),ze=(A=X.querySelector("SegmentTemplate"))!==null&&A!==void 0?A:bo;if(wo){const We=(D=(Y=X.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&D!==void 0?D:"",[Qe,zi]=We.split("-").map(pt=>parseInt(pt,10)),Ue={from:Qe,to:zi},_t=(w=X.querySelector("SegmentBase"))===null||w===void 0?void 0:w.getAttribute("indexRange"),[Wi,Jt]=_t?_t.split("-").map(pt=>parseInt(pt,10)):[],Nt=_t?{from:Wi,to:Jt}:void 0;Yi={type:ce.BYTE_RANGE,url:Ra,initRange:Ue,indexRange:Nt}}else if(ze){const We={representationId:(U=X.getAttribute("id"))!==null&&U!==void 0?U:void 0,bandwidth:(W=X.getAttribute("bandwidth"))!==null&&W!==void 0?W:void 0},Qe=parseInt((J=ze.getAttribute("timescale"))!==null&&J!==void 0?J:"",10),zi=(ee=ze.getAttribute("initialization"))!==null&&ee!==void 0?ee:"",Ue=ze.getAttribute("media"),_t=(Lt=parseInt((ge=ze.getAttribute("startNumber"))!==null&&ge!==void 0?ge:"",10))!==null&&Lt!==void 0?Lt:1,Wi=Tt(zi,We);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Jt=(ct=ze.querySelectorAll("SegmentTimeline S"))!==null&&ct!==void 0?ct:[],Nt=[];let pt=0,Qi="",Ki=0;if(Jt.length){let Xt=_t,pe=0;for(const mt of Jt){const ye=parseInt((B=mt.getAttribute("d"))!==null&&B!==void 0?B:"",10),Ke=parseInt((ie=mt.getAttribute("r"))!==null&&ie!==void 0?ie:"",10)||0,Zt=parseInt((re=mt.getAttribute("t"))!==null&&re!==void 0?re:"",10);pe=Number.isFinite(Zt)?Zt:pe;const Ji=ye/Qe*1e3,Xi=pe/Qe*1e3;for(let ei=0;ei<Ke+1;ei++){const Po=Tt(Ue,{...We,segmentNumber:Xt.toString(10),segmentTime:(pe+ei*ye).toString(10)}),La=(Xi!=null?Xi:0)+ei*Ji,Co=La+Ji;Xt++,Nt.push({time:{from:La,to:Co},url:Po})}pe+=(Ke+1)*ye,pt+=(Ke+1)*Ji}Ki=pe/Qe*1e3,Qi=Tt(Ue,{...We,segmentNumber:Xt.toString(10),segmentTime:pe.toString(10)})}else if(r.isNonNullable(qe)){const pe=parseInt((ne=ze.getAttribute("duration"))!==null&&ne!==void 0?ne:"",10)/Qe*1e3,mt=Math.ceil(qe/pe);let ye=0;for(let Ke=1;Ke<mt;Ke++){const Zt=Tt(Ue,{...We,segmentNumber:Ke.toString(10),segmentTime:ye.toString(10)});Nt.push({time:{from:ye,to:ye+pe},url:Zt}),ye+=pe}Ki=ye,Qi=Tt(Ue,{...We,segmentNumber:mt.toString(10),segmentTime:ye.toString(10)})}const Ao={time:{from:Ki,to:1/0},url:Qi};Yi={type:ce.TEMPLATE,baseUrl:Ra,segmentTemplateUrl:Ue,initUrl:Wi,totalSegmentsDurationMs:pt,segments:Nt,nextSegmentBeyondManifest:Ao,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ft||!Fe)continue;const qi={video:te.VIDEO,audio:te.AUDIO,text:te.TEXT}[ft];qi&&Ce[qi].push({id:Eo,kind:qi,segmentReference:Yi,profiles:ko,duration:qe,bitrate:Ca,mime:Fe,codecs:Kt,width:Gi,height:Pa,fps:go,quality:So})}}return{dynamic:co,liveAvailabilityStartTime:ho,duration:qe,container:po,representations:Ce}},mm=({id:i,width:e,height:t,bitrate:s,fps:a,quality:n})=>{var o;const l=(o=n?Mi(n):void 0)!==null&&o!==void 0?o:r.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:s,size:{width:e,height:t},fps:a}},vm=({id:i,bitrate:e})=>({id:i,bitrate:e}),bm=(i,e,t)=>{var s;const a=e.indexOf(t);return(s=De(i,Math.round(i.length*a/e.length)))!==null&&s!==void 0?s:De(i,-1)},Sm=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Vr=i=>"size"in i,yt=i=>i.type===ce.TEMPLATE,Ks=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class Fr{constructor(e,t,s,a,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:c,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.playingRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new wt,this.destroyAbortController=new wt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(h){const f=this.representations.get(h);r.assertNonNullable(f,`Cannot find representation ${h}`),this.playingRepresentationId=h,this.downloadingRepresentationId=h,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${f.mime}; codecs="${f.codecs}"`),this.sourceBufferTaskQueue=new Yf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Lr(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(f,"high",!0);const p=this.initData.get(f.id),b=this.segments.get(f.id),m=this.parsedInitData.get(f.id);r.assertNonNullable(p,"No init buffer for starting representation"),r.assertNonNullable(b,"No segments for starting representation"),p instanceof ArrayBuffer&&(this.searchGaps(b,f),yield this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(h){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return;this.switchingToRepresentationId=h;const f=this.representations.get(h);r.assertNonNullable(f,`No such representation ${h}`);let p=this.segments.get(h),b=this.initData.get(h);if(r.isNullable(b)||r.isNullable(p)?yield this.loadInit(f,"high",!1):b instanceof Promise&&(yield b),p=this.segments.get(h),r.assertNonNullable(p,"No segments for starting representation"),b=this.initData.get(h),!b||!(b instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield this.sourceBufferTaskQueue.append(b,this.downloadAbortController.signal);const m=this.getCurrentPosition();r.isNonNullable(m)&&(this.isLive||(p.forEach(v=>v.status=L.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=r.abortable(this.destroyAbortController.signal,async function*(h){var f;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return;for(const y of this.representations.keys()){const E=h.find(x=>x.id===y);E&&this.representations.set(y,E);const T=this.representations.get(y);if(!T||!yt(T.segmentReference))return;const $=this.getActualLiveStartingSegments(T.segmentReference);this.segments.set(T.id,$)}const p=(f=this.switchingToRepresentationId)!==null&&f!==void 0?f:this.downloadingRepresentationId,b=this.representations.get(p);r.assertNonNullable(b);const m=this.segments.get(p);r.assertNonNullable(m,"No segments for starting representation");const v=this.initData.get(p);if(r.assertNonNullable(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,b),yield this.sourceBufferTaskQueue.append(v,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isActiveLowLatency=c,this.isLive=!!(d!=null&&d.dynamic),this.container=s,s){case At.MP4:this.containerParser=gp;break;case At.WEBM:this.containerParser=Ap;break;default:r.assertNever(s)}this.initData=new Map(a.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(h=>[h.id,h])),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 wt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const a=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=$t(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Lr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=$t(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(l.includes(a))u="high";else{const d=De(l,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===L.FED&&!l.length&&$t(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=De(s,-1);c&&c.status===L.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}searchGaps(e,t){this.gaps=[];let s=0;const a=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:n.time.from+a}),s=n.time.to;r.isNonNullable(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,a=[];let n=0,o=t.length-1;do a.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<s&&o>=0);return this.liveInitialAdditionalOffset=n-s,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(a=>a.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,a,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!yt(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>({...h,status:L.NONE,size:void 0})),c=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(a=De(c,-1))===null||a===void 0?void 0:a.time.to)!==null&&n!==void 0?n:0,d=l==null?void 0:l.findIndex(h=>Math.floor(u)>=Math.floor(h.time.from)&&Math.floor(u)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;const h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{const h=l.slice(d+1);this.segments.set(o.id,[...c,...h])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const a=s.segmentReference;if(!yt(a))return;const n=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),o=Tt(a.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],c=l.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));c&&(c.time.to=e.segment.time.to),!!l.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||l.push({status:L.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,s,a;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(c=>c.time.from<=e&&c.time.to>=e);return(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const a=e.findIndex(({status:h,time:{from:f,to:p}},b)=>{const m=f<=s&&p>=s,v=f>s||m||b===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+S||p<=s+S;return(h===L.NONE||h===L.PARTIALLY_EJECTED&&v&&y&&this.sourceBuffer&&!Ws(this.sourceBuffer.buffered,s))&&v&&y});if(a===-1)return[];if(t!==ce.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,l=0;const c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=u||l<=d);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===L.NONE||f.status===L.PARTIALLY_EJECTED)c.push(f);else break}return c}async loadSegments(e,t,s="auto"){t.segmentReference.type===ce.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=L.DOWNLOADING;const a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);const{range:n,url:o,signal:l,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(await r.abortable(l,async function*(){const d=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const d=await this.fetcher.fetch(o,{range:n,signal:l,onProgress:c,priority:s,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(h,l),a.segment.status=L.DOWNLOADED,this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){if(!Ks(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const c of e)c.status=L.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:a,url:n,signal:o,onProgress:l}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await r.abortable(o,async function*(){const c=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,c))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:a,onProgress:l,signal:o,priority:s}),this.failedDownloads=0}catch(c){if(!Ks(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}}prepareByteRangeFetchSegmentParams(e,t){if(yt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,a={from:De(e,0).byte.from,to:De(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:s,range:a,signal:n,onProgress:(c,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:a?a.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}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 a=s.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},l=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:d,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});l.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:a,signal:n,onProgress:u,onProgressTasks:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(s=$t((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:a,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:c}=l;if(l.representationId===t){if(n.aborted){a();continue}if(l.loadedBytes=s,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(u);d!=null&&d.byteLength&&(c.status=L.PARTIALLY_FED,l.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),l.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:a,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const c=l.segmentReference.type,u=e.byteLength;for(const d of this.activeSegments){const{segment:h}=d,f=c===ce.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(d.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const m=f?h.byte.from-s:0,v=f?h.byte.to-s:e.byteLength,S=m<a,y=v<=a;if(h.status===L.DOWNLOADING&&S&&y){h.status=L.DOWNLOADED;const E=new DataView(e.buffer,e.byteOffset+m,p);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(d,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(d.loadedBytes=Math.min(p,a-m),d.loadedBytes>d.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+m+d.feedingBytes,d.loadedBytes-d.feedingBytes),T=d.loadedBytes===p?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(h.status=L.PARTIALLY_FED,d.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then($=>{if(n.aborted)o();else if($)d.fedBytes+=T.byteLength,d.fedBytes===p&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=L.FED,Vr(e.segment)&&(e.segment.size=e.fedBytes);for(const a of this.representations.values())if(a.id!==t)for(const n of(s=this.segments.get(a.id))!==null&&s!==void 0?s:[])n.status===L.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=L.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===L.PARTIALLY_FED||e.status===L.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=L.NONE),e.status=L.PARTIALLY_EJECTED):e.status=L.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[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Rr(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async l=>{if(!l)return;const{init:c,dataView:u,segments:d}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h);let f=d;this.isLive&&yt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=0,n=1/0,o=-1/0,l=!1;const c=u=>{var d;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h=Vr(u)?(d=u.size)!==null&&d!==void 0?d:0:u.byte.to-u.byte.from;a+=h};for(const u of this.segments.values())for(const d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status===L.FED&&c(d)}if(l=isFinite(n)&&isFinite(o),!l){a=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status===L.FED&&c(d)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const d=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===L.NONE&&Math.round(p.time.from)<=Math.round(d)&&Math.round(p.time.to)>=Math.round(h)){n=d,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const h of d)h.time.from>e+u&&h.status===L.FED&&c(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 a={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){a=void 0;break}l>s.time.from&&l<s.time.to&&(a.from=l),o<s.time.to&&o>s.time.from&&(a.to=o)}}a&&a.to-a.from>1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Rr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const a=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:a,to:n})}const t=1;for(const s of this.segments.values())for(const a of s){const{status:n}=a;if(n!==L.FED&&n!==L.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.time.to),c=e.some(d=>d.from-t<=o&&d.to+t>=l),u=e.filter(d=>o>=d.from-t&&o<=d.to+t||l>=d.from-t&&l<=d.to+t);c||(u.length===1?a.status=L.PARTIALLY_EJECTED:a.status=L.NONE)}}}var Js=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},gm=i=>{var e,t;const s=i.get("X-Delivery-Type"),a=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},kt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(kt||(kt={}));class ym{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new wt,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=Js(n));const o=yield Ht(n,{signal:this.abortAllController.signal}).catch(Ot);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?kt.HEADER:kt.PARAM,range:o,onProgress:l,priority:c="auto",signal:u,measureThroughput:d=!0,isLowLatency:h=!1}={}){var f,p;let b=a;const m=new Headers;if(o)switch(n){case kt.HEADER:{m.append("Range",`bytes=${o.from}-${o.to}`);break}case kt.PARAM:{const A=new URL(b,location.href);A.searchParams.append("bytes",`${o.from}-${o.to}`),b=A.toString();break}default:r.assertNever(n)}this.requestQuic&&(b=Js(b));let v=this.abortAllController.signal,S;if(u){const A=new wt;if(S=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{A.abort()}catch(Y){Ot(Y)}}),this.abortAllController.signal.aborted||u.aborted)try{A.abort()}catch(Y){Ot(Y)}v=A.signal}const y=r.now(),E=yield Ht(b,{priority:c,headers:m,signal:v}).catch(Ot),T=r.now();if(!E)return S==null||S.unsubscribe(),null;if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!E.ok||!E.body)return S==null||S.unsubscribe(),Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`));if(this.onHeadersReceived(E.headers),!l&&!d)return S==null||S.unsubscribe(),E.arrayBuffer();const[$,x]=E.body.tee(),_=$.getReader();d&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(x,h));let V=0,N=new Uint8Array(0),F=!1;const j=A=>{S==null||S.unsubscribe(),F=!0,Ot(A)},C=r.abortable(v,async function*({done:A,value:Y}){if(V===0&&this.lastRequestFirstBytes$.next(r.now()-y),v.aborted){S==null||S.unsubscribe();return}if(!A&&Y){const D=new Uint8Array(N.length+Y.length);D.set(N),D.set(Y,N.length),N=D,V+=Y.byteLength,l==null||l(new DataView(N.buffer),V),yield _==null?void 0:_.read().then(C,j)}}.bind(this));return yield _==null?void 0:_.read().then(C,j),S==null||S.unsubscribe(),F?null:N.buffer}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==ce.BYTE_RANGE)return null;const{from:c,to:u}=a.initRange;let d=c,h=u,f=!1,p,b;a.indexRange&&(p=a.indexRange.from,b=a.indexRange.to,f=u+1===p,f&&(d=Math.min(p,c),h=Math.max(b,u))),d=Math.min(d,0);const m=yield this.fetch(a.url,{range:{from:d,to:h},priority:o,measureThroughput:!1});if(!m)return null;const v=new DataView(m,c-d,u-d+1);if(!n.validateData(v))throw new Error("Invalid media file");const S=n.parseInit(v),y=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!y)throw new ReferenceError("No way to load representation index");let E;if(f)E=new DataView(m,y.from-d,y.to-y.from+1);else{const $=yield this.fetch(a.url,{range:y,priority:o,measureThroughput:!1});if(!$)return null;E=new DataView($)}const T=n.parseSegments(E,S,y);return{init:S,dataView:new DataView(m),segments:T}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==ce.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:a.segments.map(u=>({...u,status:L.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=gm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var a,n;const{type:o}=e;switch(o){case ce.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,s))!==null&&a!==void 0?a:null;case ce.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ot=i=>{if(!Ks(i))throw i},Xs=1e3,Ci=(i,e,t)=>t*e+(1-t)*i,so=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Tm=(i,e,t,s)=>{let a=0,n=t;const o=so(i,e),l=e<s?e:s;for(let c=0;c<l;c++)i[n]>o?a++:a--,n=(i.length+n-1)%i.length;return Math.abs(a)===l};class ga{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${s}`),this.smoothedSeries$=new ke(`smoothed_${s}`),this.reportedSeries$=new ke(`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 l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Em extends ga{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ci(this.slow,e,this.params.emaAlphaSlow),this.fast=Ci(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class $m extends ga{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=so(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ci(this.emaSmoothed,e,this.params.emaAlpha);const s=Tm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class km extends ga{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?Ci(this.smoothed,e,this.params.emaAlpha):e}}class Zs{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Em({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new $m({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 km({initial:e,label:"liveEdgeDelay",...t})}}const wm=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Je=()=>window.ManagedMediaSource||window.MediaSource,ao=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Am=()=>{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))},Pm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,Ur=["timeupdate","progress","play","seeked","stalled","waiting"];var ue;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(ue||(ue={}));let Cm=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.representationSubscription=new r.Subscription,this.state$=new K(ue.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.currentVideoRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.isLive$=new r.ValueSubject(!1),this.liveDuration$=new r.ValueSubject(0),this.liveAvailabilityStartTime$=new r.ValueSubject(void 0),this.bufferLength$=new r.ValueSubject(0),this.liveLoadBufferLength$=new r.ValueSubject(0),this.livePositionFromPlayer$=new r.ValueSubject(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new wt,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,s,a){var n;this.element=t,this.manifestUrlString=ve(s,a,Z.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ue.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(ue.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=r.abortable(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!s)return null;let a;try{a=pm(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return null;const n=({kind:o,mime:l,codecs:c})=>{var u,d,h,f;return!!(!((d=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||d===void 0)&&d.call(u,l)&&(!((f=(h=Je())===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${c}"`))||o===te.TEXT)};return a.dynamic&&this.isLive$.getValue()!==a.dynamic&&(this.isLive$.next(a.dynamic),this.liveDuration$.getValue()!==a.duration&&this.liveDuration$.next(-1*((t=a.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==a.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(a.liveAvailabilityStartTime)),{...a,representations:ki(Object.entries(a.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,s,a){var n;r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ue.REPRESENTATIOS_READY);const o=m=>{this.representationSubscription.add(r.fromEvent(m,"error").pipe(r.filter(v=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(v=>{this.error$.next({id:"VideoSource",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:v})}))};this.source=this.tuning.useManagedMediaSource?Pm():new MediaSource;const l=document.createElement("source");if(o(l),l.src=URL.createObjectURL(this.source),this.element.appendChild(l),this.tuning.useManagedMediaSource&&ao())if(a){const m=document.createElement("source");o(m),m.type="application/x-mpegurl",m.src=a.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const c={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 Fr(te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,c),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(s)&&(this.audioBufferManager=new Fr(te.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,c),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(r.interval(Xs).subscribe(m=>{var v;if(!((v=this.element)===null||v===void 0)&&v.paused){const S=kr(this.manifestUrlString,Z.DASH_CMAF_OFFSET_P);this.manifestUrlString=ve(this.manifestUrlString,S+Xs,Z.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Ur.map(m=>r.fromEvent(this.element,m))).pipe(r.map(m=>this.element?$t(this.element.buffered,this.element.currentTime*1e3):0),r.filterChanged(),r.filter(m=>!!m),r.tap(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(r.filter(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,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=v-S;let $=1+Math.sign(T)*E;Math.abs(T)<y?$=1:Math.abs(T)>y*2&&($=1+Math.sign(T)*E*2),wm(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(v=>{var S,y;let E=0;if(v){const T=((y=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&y!==void 0?y:0)*1e3;E=Math.min(...this.bufferManagers.map(x=>{var _,V;return(V=(_=x.getLiveSegmentsToLoadState(this.manifest))===null||_===void 0?void 0:_.to)!==null&&V!==void 0?V:0}))-T}E&&this.liveLoadBufferLength$.getValue()!==E&&this.liveLoadBufferLength$.next(E)}));let m=0;this.representationSubscription.add(r.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:v,bufferLength:S})=>{if(r.assertNonNullable(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,E=kr(this.manifestUrlString,Z.DASH_CMAF_OFFSET_P),T=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,$=Math.min(T,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),x=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,_=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,V=this.isActiveLowLatency?S:v;let N=$e.None;if(this.isActiveLowLatency?N=$e.ActiveLowLatency:V<$+_&&V>=$?N=$e.LiveWithTargetOffset:E!==0&&V<$&&(N=$e.LiveForwardBuffering),isFinite(v)&&(m=v>m?v:m),N===$e.LiveForwardBuffering||N===$e.LiveWithTargetOffset){const F=m-($+x),j=this.normolizeLiveOffset(Math.trunc(E+F/y)),C=Math.abs(j-E);let A;!v||C<=this.tuning.dashCmafLive.offsetCalculationError?A=E:j>0&&C>this.tuning.dashCmafLive.offsetCalculationError?A=j:A=0,this.manifestUrlString=ve(this.manifestUrlString,A,Z.DASH_CMAF_OFFSET_P)}N!==$e.None&&N!==$e.ActiveLowLatency&&(m=0,this.updateLive())}))}const u=r.merge(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),d=r.merge(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:u,someBufferEnded:d}).pipe(r.filter(({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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:v})}})),this.representationSubscription.add(r.merge(...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 h=(n=this.manifest.duration)!==null&&n!==void 0?n:0,f=(m,v)=>{var S;return Math.max(m,(S=v.duration)!==null&&S!==void 0?S:0)},p=this.manifest.representations.audio.reduce(f,h),b=this.manifest.representations.video.reduce(f,h);(p||b)&&(this.source.duration=Math.max(p,b)/1e3),this.audioBufferManager&&r.isNonNullable(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ue.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ym({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Zs.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,a,n;r.assertNonNullable(this.element);const o=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&o===0,this.liveLastSeekOffset=o,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=ve(this.manifestUrlString,o,Z.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((a=this.audioBufferManager)===null||a===void 0?void 0:a.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)))}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(ue.RUNNING),this.subscription.add(r.merge(...Ur.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ws(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={[te.VIDEO]:this.videoBufferManager,[te.AUDIO]:this.audioBufferManager,[te.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,a,n,o,l;r.assertNonNullable(this.element),r.assertNonNullable(this.videoBufferManager);let c;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?c=e:c=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Ws(this.element.buffered,c)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(c),(l=this.audioBufferManager)===null||l===void 0||l.maintain(c),this.element.currentTime=c/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(a=>a.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(ue.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:r.ErrorCategory.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 a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s);a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(a)&&(this.element.currentTime=a/1e3)}}};class Dm{constructor(e,t){this.fov=e,this.orientation=t}}class Rm{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 a=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:a,y:n,z:o},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 a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 Lm=`#define GLSLIFY 1
37
+ `}),D}return u==null||u.recordSwitch(A),A};var Pe=i=>new URL(i).hostname;const Pr=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 ut=async i=>{const e=i.muted;try{await i.play()}catch(t){if(!Pr(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{await i.play()}catch(s){return Pr(s)&&(i.muted=!1,console.warn(s)),!1}}return!0};function ae(){return r.now()}function qn(i){return ae()-i}function Cr(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,a=o=>s.test(o);return{resolve:(o,l,c=!1)=>{a(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return c&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function wf(i,e,t){const s=(...a)=>{t.apply(null,a),i.removeEventListener(e,s)};i.addEventListener(e,s)}function yi(i,e,t,s){const a=window.XMLHttpRequest;let n,o,l,c=!1,u=0,d,h,f=!1,p="arraybuffer",b=7e3,m=2e3,v=()=>{if(c)return;r.assertNonNullable(d);const C=qn(d);let A;if(C<m){A=m-C,setTimeout(v,A);return}m*=2,m>b&&(m=b),o&&o.abort(),o=new a,N()};const S=C=>(n=C,j),y=C=>(h=C,j),T=()=>(p="json",j),E=()=>{if(!c){if(--u>=0){v(),s&&s();return}c=!0,h&&h(),t&&t()}},$=C=>(f=C,j),N=()=>{d=ae(),o=new a,o.open("get",i);let C=0,A,Y=0;const D=()=>(r.assertNonNullable(d),Math.max(d,Math.max(A||0,Y||0)));if(n&&o.addEventListener("progress",w=>{const U=ae();n.updateChunk&&w.loaded>C&&(n.updateChunk(D(),w.loaded-C),C=w.loaded,A=U)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(c)return;r.assertNonNullable(o);const w=o.status;if(w>=200&&w<300){if(o.response.byteLength&&n){const U=o.response.byteLength-C;U&&n.updateChunk&&n.updateChunk(D(),U)}o.responseType==="json"&&!Object.values(o.response).length?E():(h&&h(),e(o.response))}else E()}),o.addEventListener("error",()=>{E()}),f){const w=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=ae(),o.removeEventListener("readystatechange",w))};o.addEventListener("readystatechange",w)}return o.responseType=p,o.send(),j},j={withBitrateReporting:S,withParallel:$,withJSONResponse:T,withRetryCount:C=>(u=C,j),withRetryInterval:(C,A)=>(r.isNonNullable(C)&&(m=C),r.isNonNullable(A)&&(b=A),j),withTimeout:C=>(l=C,j),withFinally:y,send:N,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return j}const Af=100,Pf=2e3,Cf=500;let Df=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-Cf;if(t-e>Pf){let s=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,a+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const c=n.bytes*o/l;a+=c,n.start=t,n.bytes-=c}}}if(a>0&&s>0){const n=a*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(a)}/${Math.round(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>Af&&(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 Lf{constructor(e,t,s,a,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=a,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=ae(),a=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=c=>{e._complete=1,e._responseData=c,e._downloadTime=ae()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=yi(t,n,()=>a("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ae()}_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=ae();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,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=a,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=a,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const ci=1e4,Ts=3,Rf=6e4,If=10,_f=1,xf=500;class Nf{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 Df(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Cr(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=Cr(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 a;s!==0&&(a=t.buffered.start(s-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let s,a,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!a||n.bitrate>a.bitrate)&&(a=n):(!s||s.bitrate>n.bitrate)&&(s=n));return a||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{wf(a,"progress",()=>{a.buffered.length?(a.currentTime=a.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Lf(Ts,ci,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:a}=this.params;let n=!1,o=null,l=null,c=null,u=null,d=!1;const h=()=>{const E=n&&(!d||d===this.rep);return E||t("Not running!"),E},f=(E,$,N)=>{c&&c.abort(),c=yi(this.urlResolver.resolve(E,!1),$,N,()=>this._retryCallback()).withTimeout(ci).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ts).withFinally(()=>{c=null}).send()},p=(E,$,N)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,N,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=E=>{const $=s.playbackRate;s.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),s.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const N=ae()-1e4;let O=0;for(let _=0;_<this.bufferStates.length;_++){const F=this.bufferStates[_];E=Math.min(E,F.buf),F.ts<N&&O++}this.bufferStates.splice(0,O),t(`update playback rate; minBuffer=${E} drop=${O} jitter=${this.sourceJitter}`);let V=E-_f;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?b(1.15):V>1?b(1.1):V>.3?b(1.05):b(1)}},S=E=>{let $;const N=()=>$&&$.start?$.start.length:0,O=w=>$.start[w]/1e3,V=w=>$.dur[w]/1e3,_=w=>$.fragIndex+w,F=(w,U)=>({chunkIdx:_(w),startTS:O(w),dur:V(w),discontinuity:U}),j=()=>{let w=0;if($&&$.dur){let U=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,W=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,J=U;this.sourceJitter>1&&(J+=this.sourceJitter-1);let ee=$.dur.length-1;for(;ee>=0&&(J-=$.dur[ee],!(J<=0));--ee);w=Math.min(ee,$.dur.length-1-W),w=Math.max(w,0)}return F(w,!0)},C=w=>{const U=N();if(!(U<=0)){if(r.isNonNullable(w)){for(let W=0;W<U;W++)if(O(W)>w)return F(W)}return j()}},A=w=>{const U=N(),W=w?w.chunkIdx+1:0,J=W-$.fragIndex;if(!(U<=0)){if(!w||J<0||J-U>If)return t(`Resync: offset=${J} bChunks=${U} chunk=`+JSON.stringify(w)),j();if(!(J>=U))return F(W-$.fragIndex,!1)}},Y=(w,U,W)=>{u&&u.abort(),u=yi(this.urlResolver.resolve(w,!0,this.lowLatency),U,W,()=>this._retryCallback()).withTimeout(ci).withRetryCount(Ts).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,U)=>{Y(E,W=>{if(!h())return;$=W;const J=!!$.lowLatency;J!==this.lowLatency&&m(J);let ee=0;for(let ge=0;ge<$.dur.length;++ge)ee+=$.dur[ge];ee>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/$.dur.length)),a({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,w(C(U))},()=>this._handleNetworkError())},nextChunk:A}},y=()=>{n=!1,l&&l.abort(),c&&c.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{const{videoElement:$,logger:N}=this.params;let O=S(e.jidxUrl),V,_,F,j,C=0,A,Y,D;const w=()=>{A&&(clearTimeout(A),A=void 0);const B=Math.max(xf,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=C+B,re=ae(),ne=Math.min(1e4,ie-re);C=re;const dt=()=>{u||h()&&O.seek(()=>{h()&&(C=ae(),U(),w())})};ne>0?A=window.setTimeout(()=>{this.paused?w():dt()},ne):dt()},U=()=>{let B;for(;B=O.nextChunk(j);)j=B,Rt(B);const ie=O.nextChunk(F);if(ie){if(F&&ie.discontinuity){N("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}ge(ie)}else w()},W=(B,ie)=>{if(!h()||!this.sourceBuffer)return;let re,ne,dt;const It=Ce=>{window.setTimeout(()=>{h()&&W(B,ie)},Ce)};if(this.sourceBuffer.updating)N("Source buffer is updating; delaying appendBuffer"),It(100);else{const Ce=ae(),oe=$.currentTime;!this.paused&&$.buffered.length>1&&Y===oe&&Ce-D>500&&(N("Stall suspected; trying to fix"),this._fixupStall()),Y!==oe&&(Y=oe,D=Ce);const ht=this._getBufferSizeSec();if(ht>30)N(`Buffered ${ht} seconds; delaying appendBuffer`),It(2e3);else try{this.sourceBuffer.appendBuffer(B),this.videoPlayStarted?(this.bufferStates.push({ts:Ce,buf:ht}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(_t){if(_t.name==="QuotaExceededError")N("QuotaExceededError; delaying appendBuffer"),dt=this.sourceBuffer.buffered.length,dt!==0&&(re=this.sourceBuffer.buffered.start(0),ne=oe,ne-re>4&&this.sourceBuffer.remove(re,ne-3)),It(1e3);else throw _t}}},J=()=>{_&&V&&(N([`Appending chunk, sz=${_.byteLength}:`,JSON.stringify(F)]),W(_,function(){_=null,U()}))},ee=B=>e.fragUrlTemplate.replace("%%id%%",B.chunkIdx),ge=B=>{h()&&p(ee(B),(ie,re)=>{if(h()){if(re/=1e3,_=ie,F=B,o=B.startTS,re){const ne=Math.min(10,B.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ne:ne}J()}},()=>this._handleNetworkError())},Rt=B=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(B),!1)))},ct=B=>{h()&&(e.cachedHeader=B,W(B,()=>{V=!0,J()}))};n=!0,O.seek(B=>{if(h()){if(C=ae(),!B){w();return}j=B,!r.isNullable(E)||B.startTS>E?ge(B):(F=B,U())}},E),e.cachedHeader?ct(e.cachedHeader):f(e.headerUrl,ct,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,p,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),b=h/this.bitrate,p>10&&b>.8||p>15&&b>.5||p>20&&b>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const b=ae();if(this.chunkRateEstimator.addInterval(f,b,p)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:b-f,speed:v}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,c=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(c&&h>l&&qn(o)<3e4)return;s(h)}c=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=ae();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=yi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(ci).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;ut(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((c,u)=>{c.video&&a.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,l.push(c))}),l.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.bitrate}),l):(s({name:"error",type:"empty_manifest"}),[])};this.manifest=n(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))},Rf))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class zn{constructor(){this.onDroopedVideoFramesLimit$=new r.Subject,this.subscription=new r.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new r.Subject,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&&!r.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),a=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(a-n)/a;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&r.isHigher(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(r.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=r.interval(this.droppedFramesChecker.checkTime).pipe(r.filter(()=>this.playing),r.filter(()=>{const a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(r.debounce(this.droppedFramesChecker.checkTime)),s=r.merge(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 a=(s=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>r.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:a}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 I;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(I||(I={}));const Of=[I.PAUSED,I.PLAYING,I.READY],Mf=[I.PAUSED,I.PLAYING,I.READY];class Bf{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(I.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Ge,this.droppedFramesManager=new zn,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new ma,this._dashCb=a=>{var n,o,l,c;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,d=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Mi(h.name))!==null&&o!==void 0?o:r.videoSizeToQuality(h.video),b=h.bitrate/1e3,m={...h.video};if(!p)continue;const v={id:f,quality:p,bitrate:b,size:m};d.push({track:v,representation:h})}this.representations$.next(d),this.params.output.availableVideoTracks$.next(d.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===I.MANIFEST_READY&&this.videoState.setState(I.MANIFEST_READY);break}case"qualitySwitch":{const u=a.quality,d=(c=this.representations$.getValue().find(({representation:h})=>h===u))===null||c===void 0?void 0:c.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),r.isNonNullable(d)&&this.params.output.currentVideoTrack$.next(d);break}case"bandwidth":{const{size:u,duration:d}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,d);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration||0),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{const a=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(c)};`}),o===exports.PlaybackState.STOPPED){a!==I.STOPPED&&(this.videoState.startTransitionTo(I.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(I.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Mf.includes(a)&&(u||d)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&c.state===x.Requested&&Of.includes(a)){this.seek(c.position-this.liveOffset.getTotalPausedTime());return}switch(a){case I.STOPPED:this.videoState.startTransitionTo(I.MANIFEST_READY),this.dash.attachSource(ve(this.params.source.url));return;case I.MANIFEST_READY:this.videoState.startTransitionTo(I.READY),this.prepare();break;case I.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(I.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(I.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(I.PAUSED)})}return;case I.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(I.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case I.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(I.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(I.PAUSED)}),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.dash.reinit(ve(this.params.source.url,h))}return;default:return r.assertNever(a)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=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(Pe(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=lt(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(r.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===I.READY&&this.videoState.setState(I.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(I.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===x.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(I.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(Wt(this.video,this.params.desiredState.isLooped,t)).add(ot(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Lt(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:a}})=>{const n=a&&r.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case I.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case I.MANIFEST_READY:case I.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case I.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case I.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.observableFrom(["init"])).pipe(r.debounce(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),nt(this.video)}createLiveDashPlayer(){const e=new Nf({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,a,n,o;const l=this.representations$.getValue(),c=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(a=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!u&&r.isNonNullable(c)?c:Bi(l.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}),h=d==null?void 0:d.id,f=this.params.desiredState.videoTrack.getTransition(),p=(n=this.params.desiredState.videoTrack.getState())===null||n===void 0?void 0:n.id,b=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(f||h!==p)&&this.setVideoTrack(d),b&&this.setAutoQuality(u),f||b||h!==p){const m=(o=l.find(({track:v})=>v.id===h))===null||o===void 0?void 0:o.representation;r.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:a})=>a.id===e.id))===null||t===void 0?void 0:t.representation;r.assertNonNullable(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(),a=t===exports.PlaybackState.PAUSED&&s===I.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ve(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var te;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(te||(te={}));var $e;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})($e||($e={}));var wi;(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"})(wi||(wi={}));var ce;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ce||(ce={}));var R;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(R||(R={}));var At;(function(i){i.MP4="mp4",i.WEBM="webm"})(At||(At={}));var Ai;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(Ai||(Ai={}));var z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(z||(z={}));var $t=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const a=i.start(s)*1e3,n=i.end(s)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Vf=300,Ff=(i,e=Vf)=>new r.Observable(t=>{const{width:s,height:a}=i.getBoundingClientRect();if(t.next({width:s,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(r.debounceFn(o=>{const l=o[0];if(!l)return;let c,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,c=l.contentBoxSize[0].inlineSize):l.contentRect&&(c=l.contentRect.width,u=l.contentRect.height),r.isNonNullable(c)&&r.isNonNullable(u)&&t.next({width:c,height:u})},e));return n.observe(i),()=>n.disconnect()});class Dr{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 a=0,n=s.length;a<n;a++)if(s[a].callback===t){s.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let a=0,n=s.length;a<n;a++){const o=s[a];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Wn extends Dr{constructor(){super(),this.listeners||Dr.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let Qn=class{constructor(){Object.defineProperty(this,"signal",{value:new Wn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let 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(a){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&&(Qn.prototype[Symbol.toStringTag]="AbortController",Wn.prototype[Symbol.toStringTag]="AbortSignal");function Kn(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 Uf(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=i;if(!Kn({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,d){let h;d&&d.signal&&(h=d.signal,delete d.signal);const f=new t(u,d);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(c,u)=>{const d=n&&n.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(d.aborted)return Promise.reject(h);const f=new Promise((p,b)=>{d.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(c,u)])}return o(c,u)},Request:n}}const Vi=Kn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Jn=Vi?Uf({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ht=Vi?Jn.fetch:window.fetch;Vi?Jn.Request:window.Request;const wt=Vi?Qn:window.AbortController;var Ws=(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 jf=(i,e={})=>{const s=e.timeout||1,a=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-a-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Hf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Lr=Hf?jf:window.requestIdleCallback;var Es,$s;const Gf=16;let Xn=!1;try{Xn=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt(($s=(Es=navigator.userAgent.match(/Version\/(\d+)/))===null||Es===void 0?void 0:Es[1])!==null&&$s!==void 0?$s:"",10)<=Gf}catch(i){console.error(i)}class Yf{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const 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:r.ErrorCategory.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 a={operation:"append",data:e,signal:t,callback:s};this.queue.push(a),this.pull()})}async remove(e,t,s){return s&&s.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:s,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let s;Xn&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!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(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:r.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:r.assertNever(t)}}}var Rr=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class he{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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 Zn extends he{}class qf extends he{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 zf extends he{parseChildrenBoxes(){return Ye(this.content)}}class Wf extends he{parseChildrenBoxes(){return Ye(this.content)}}class Qf extends he{constructor(e){super(e),this.data=this.content}}class Ve extends he{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class Kf extends Ve{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 a=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,c=s<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:c})}}}class Jf extends he{parseChildrenBoxes(){return Ye(this.content)}}class Xf extends he{parseChildrenBoxes(){return Ye(this.content)}}var tt;(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"})(tt||(tt={}));class Zf extends Ve{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=tt.MONOSCOPIC;break;case 1:this.stereoMode=tt.TOP_BOTTOM;break;case 2:this.stereoMode=tt.LEFT_RIGHT;break;case 3:this.stereoMode=tt.STEREO_CUSTOM;break;case 4:this.stereoMode=tt.RIGHT_LEFT;break}this.cursor+=1}}class ep extends Ve{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class tp extends Ve{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class ip extends he{parseChildrenBoxes(){return Ye(this.content)}}class sp extends Ve{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 ap extends he{parseChildrenBoxes(){return Ye(this.content)}}class rp extends he{parseChildrenBoxes(){return Ye(this.content)}}class np extends Ve{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class op extends he{parseChildrenBoxes(){return Ye(this.content)}}class lp extends Ve{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 up extends Ve{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 cp extends Ve{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 dp={ftyp:qf,moov:zf,moof:Wf,mdat:Qf,sidx:Kf,trak:Jf,mdia:ip,mfhd:np,tkhd:sp,traf:op,tfhd:lp,tfdt:up,trun:cp,minf:ap,sv3d:Xf,st3d:Zf,prhd:ep,proj:rp,equi:tp,unknown:Zn};class hp{createBox(e,t){const s=dp[e];return s?new s(t):new Zn(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Fi.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Fi=new hp;function Ft(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(o=>o.charCodeAt(0));let a=i.byteOffset,n=[];for(;a<t.byteLength;){if(t[a]===s[n.length]?n.push(t[a]):n.length&&(n=[],a--),n.length===4){const l=new DataView(i.buffer,a-7,4).getUint32(0);return a-7+l>i.buffer.byteLength?null:Fi.createBox(e,new DataView(i.buffer,a-7))}a++}return null}function Qs(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const a=Ft(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(a)t.push(a),s=a.source.byteOffset+a.size;else break}return t}function Ye(i){const e=[];let t=0;for(;t<i.byteLength;){const s=Fi.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const fp=new TextDecoder("ascii"),pp=i=>fp.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",mp=i=>{const e=Fi.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:R.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},vp=i=>{const e=Qs(i,"mdat"),t=Qs(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],a=e[e.length-1],n=s.source.byteOffset,l=a.source.byteOffset-s.source.byteOffset+a.size;return new DataView(i.buffer,n,l)},bp=(i,e)=>{const t=Qs(i,"traf"),s=t[t.length-1].children.find(c=>c.type==="tfhd"),a=t[t.length-1].children.find(c=>c.type==="tfdt"),n=t[t.length-1].children.find(c=>c.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((c,u)=>c+u,0):o=s.defaultSampleDuration*n.sampleCount,(Number(a.baseMediaDecodeTime)+o)/e*1e3},Sp=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Ai.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ft(i,"sv3d")){e.is3dVideo=!0;const s=Ft(i,"st3d");s&&(e.stereoMode=s.stereoMode);const a=Ft(i,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=Ft(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},gp={validateData:pp,parseInit:Sp,getIndexRange:()=>{},parseSegments:mp,parseFeedableSegmentChunk:vp,getSegmentEndTime:bp};var g;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.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"})(g||(g={}));var k;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(k||(k={}));const Ir={[g.EBML]:{type:k.Master},[g.EBMLVersion]:{type:k.UnsignedInteger},[g.EBMLReadVersion]:{type:k.UnsignedInteger},[g.EBMLMaxIDLength]:{type:k.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[g.DocType]:{type:k.String},[g.DocTypeVersion]:{type:k.UnsignedInteger},[g.DocTypeReadVersion]:{type:k.UnsignedInteger},[g.Void]:{type:k.Binary},[g.Segment]:{type:k.Master},[g.SeekHead]:{type:k.Master},[g.Seek]:{type:k.Master},[g.SeekID]:{type:k.Binary},[g.SeekPosition]:{type:k.UnsignedInteger},[g.Info]:{type:k.Master},[g.TimestampScale]:{type:k.UnsignedInteger},[g.Duration]:{type:k.Float},[g.Tracks]:{type:k.Master},[g.TrackEntry]:{type:k.Master},[g.Video]:{type:k.Master},[g.Projection]:{type:k.Master},[g.ProjectionType]:{type:k.UnsignedInteger},[g.ProjectionPrivate]:{type:k.Master},[g.Chapters]:{type:k.Master},[g.Cluster]:{type:k.Master},[g.Timestamp]:{type:k.UnsignedInteger},[g.SilentTracks]:{type:k.Master},[g.SilentTrackNumber]:{type:k.UnsignedInteger},[g.Position]:{type:k.UnsignedInteger},[g.PrevSize]:{type:k.UnsignedInteger},[g.SimpleBlock]:{type:k.Binary},[g.BlockGroup]:{type:k.Master},[g.EncryptedBlock]:{type:k.Binary},[g.Attachments]:{type:k.Master},[g.Tags]:{type:k.Master},[g.Cues]:{type:k.Master},[g.CuePoint]:{type:k.Master},[g.CueTime]:{type:k.UnsignedInteger},[g.CueTrackPositions]:{type:k.Master},[g.CueTrack]:{type:k.UnsignedInteger},[g.CueClusterPosition]:{type:k.UnsignedInteger},[g.CueRelativePosition]:{type:k.UnsignedInteger},[g.CueDuration]:{type:k.UnsignedInteger},[g.CueBlockNumber]:{type:k.UnsignedInteger},[g.CueCodecState]:{type:k.UnsignedInteger},[g.CueReference]:{type:k.Master},[g.CueRefTime]:{type:k.UnsignedInteger}},eo=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=Pi(i,t),a=s in Ir,n=a?Ir[s].type:k.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const c=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,d=Pi(c),h=u*2**((l-1)*8)+d,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:a?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},Pi=(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},we=(i,e)=>{switch(e){case k.SignedInteger:return i.getInt8(0);case k.UnsignedInteger:return Pi(i);case k.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(i);case k.UTF8:return new TextDecoder("utf-8").decode(i);case k.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case k.Master:return i;case k.Binary:return i;default:r.assertNever(e)}},Pt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),a=eo(s);if(!e(a))return;a.type===k.Master&&Pt(a.value,e),t=a.value.byteOffset-i.byteOffset+a.valueSize}},yp=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,s;const a=eo(i);return Pt(a.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=we(l,o):n===g.DocType?t=we(l,o):n===g.DocTypeReadVersion&&(s=we(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},to=[g.Info,g.SeekHead,g.Tracks,g.TrackEntry,g.Video,g.Projection,g.ProjectionType,g.ProjectionPrivate,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],Tp=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],Ep=i=>{let e,t,s,a,n=!1,o=!1,l=!1,c,u,d=!1;const h=0;return Pt(i,({tag:f,type:p,value:b,valueSize:m})=>{if(f===g.SeekID){const v=we(b,p);u=Pi(v)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=b.byteOffset,t=b.byteOffset+m):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?s=we(b,p):f===g.Duration?a=we(b,p):f===g.SeekPosition&&u===g.Cues?c=we(b,p):f===g.Tracks?Pt(b,({tag:v,type:S,value:y})=>v===g.ProjectionType?(d=we(y,S)===1,!1):!0):n&&o&&to.includes(f)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(a/1e9*s*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:h,projectionType:Ai.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},$p=i=>{if(r.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kp=(i,e)=>{let t=!1,s=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return Pt(i,({tag:l,type:c,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&a(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=we(u,c));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=we(u,c));break;default:t&&to.includes(l)&&(s=!0)}return!(t&&s)}),o&&a(o)&&n.push(o),n.map((l,c)=>{const{time:u,position:d}=l,h=n[c+1];return{status:R.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},wp=i=>{let e=0,t=!1;try{Pt(i,s=>s.tag===g.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):Tp.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},Ap={validateData:yp,parseInit:Ep,getIndexRange:$p,parseSegments:kp,parseFeedableSegmentChunk:wp};var Pp=it,Cp=Li,Dp=Se,Lp=Dp("match"),Rp=function(i){var e;return Pp(i)&&((e=i[Lp])!==void 0?!!e:Cp(i)=="RegExp")},Ip=Oi,_p=String,xp=function(i){if(Ip(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return _p(i)},Np=at,Op=function(){var i=Np(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},Mp=Me,Bp=Be,Vp=aa,Fp=Op,_r=RegExp.prototype,Up=function(i){var e=i.flags;return e===void 0&&!("flags"in _r)&&!Bp(i,"flags")&&Vp(_r,i)?Mp(Fp,i):e},ba=Oe,jp=_i,Hp=Math.floor,ks=ba("".charAt),Gp=ba("".replace),ws=ba("".slice),Yp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,qp=/\$([$&'`]|\d{1,2})/g,zp=function(i,e,t,s,a,n){var o=t+i.length,l=s.length,c=qp;return a!==void 0&&(a=jp(a),c=Yp),Gp(n,c,function(u,d){var h;switch(ks(d,0)){case"$":return"$";case"&":return i;case"`":return ws(e,0,t);case"'":return ws(e,o);case"<":h=a[ws(d,1,-1)];break;default:var f=+d;if(f===0)return u;if(f>l){var p=Hp(f/10);return p===0?u:p<=l?s[p-1]===void 0?ks(d,1):s[p-1]+ks(d,1):u}h=s[f-1]}return h===void 0?"":h})},Wp=Ni,Qp=Me,Sa=Oe,xr=ta,Kp=de,Jp=Ri,Xp=Rp,gt=xp,Zp=Ii,em=Up,tm=zp,im=Se,sm=im("replace"),am=TypeError,io=Sa("".indexOf),rm=Sa("".replace),Nr=Sa("".slice),nm=Math.max,Or=function(i,e,t){return t>i.length?-1:e===""?t:io(i,e,t)};Wp({target:"String",proto:!0},{replaceAll:function(e,t){var s=xr(this),a,n,o,l,c,u,d,h,f,p=0,b=0,m="";if(!Jp(e)){if(a=Xp(e),a&&(n=gt(xr(em(e))),!~io(n,"g")))throw am("`.replaceAll` does not allow non-global regexes");if(o=Zp(e,sm),o)return Qp(o,e,s,t);if(a)return rm(gt(s),e,t)}for(l=gt(s),c=gt(e),u=Kp(t),u||(t=gt(t)),d=c.length,h=nm(1,d),p=Or(l,c,0);p!==-1;)f=u?gt(t(c,p,l)):tm(c,l,p,[],void 0,t),m+=Nr(l,b,p)+f,b=p+d,p=Or(l,c,p+h);return b<l.length&&(m+=Nr(l,b)),m}});var om=Yn,lm=om("String","replaceAll"),um=lm,cm=um,dm=cm,hm=dm,Mr=ea(hm);const fm=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Br=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const c=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(c)?0:c)*l},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),a=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],a),hours:e(s==null?void 0:s[6],a),minutes:e(s==null?void 0:s[7],a),seconds:e(s==null?void 0:s[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Tt=(i,e)=>{let t=i;t=Mr(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(s)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=Mr(t,o,(l,c)=>r.isNullable(n)?l:r.isNullable(c)?n:n.padStart(parseInt(c,10),"0"))}return t},pm=(i,e)=>{var t,s,a,n,o,l,c,u,d,h,f,p,b,m,v,S,y,T,E,$,N,O,V,_,F,j,C,A,Y,D,w,U,W,J,ee,ge,Rt,ct,B,ie,re,ne;const It=new DOMParser().parseFromString(i,"application/xml"),Ce={video:[],audio:[],text:[]},oe=It.children[0],ht=oe.getElementsByTagName("Period")[0],_t=(a=(s=(t=oe.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||s===void 0?void 0:s.trim())!==null&&a!==void 0?a:"",uo=ht.children,co=oe.getAttribute("type")==="dynamic",Ta=oe.getAttribute("availabilityStartTime"),ho=Ta?new Date(Ta).getTime():void 0;let qe;const Ea=oe.getAttribute("mediaPresentationDuration"),$a=ht.getAttribute("duration"),Ui=oe.getElementsByTagName("vk:Attrs")[0],ka=Ui==null?void 0:Ui.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Ea)qe=Br(Ea);else if($a){const fe=Br($a);r.isNonNullable(fe)&&(qe=fe)}else ka&&(qe=parseInt(ka,10));let fo=0;const ji=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],po=ji.includes(wi.WEBM_AS_IN_FFMPEG)||ji.includes(wi.WEBM_AS_IN_SPEC)?At.WEBM:At.MP4;for(const fe of uo){const Qt=fe.getAttribute("mimeType"),mo=fe.getAttribute("codecs"),wa=(l=fe.getAttribute("contentType"))!==null&&l!==void 0?l:Qt==null?void 0:Qt.split("/")[0],vo=(u=(c=fe.getAttribute("profiles"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[],Aa=fe.querySelectorAll("Representation"),bo=fe.querySelector("SegmentTemplate");if(wa===te.TEXT){for(const X of Aa){const Fe=X.getAttribute("id")||"",Kt=fe.getAttribute("lang"),ft=(f=(h=(d=X.querySelector("BaseURL"))===null||d===void 0?void 0:d.textContent)===null||h===void 0?void 0:h.trim())!==null&&f!==void 0?f:"",Hi=new URL(ft||_t,e).toString(),Gi=Fe.includes("_auto");Ce[te.TEXT].push({id:Fe,lang:Kt,isAuto:Gi,kind:te.TEXT,url:Hi})}continue}for(const X of Aa){const Fe=(p=X.getAttribute("mimeType"))!==null&&p!==void 0?p:Qt,Kt=(m=(b=X.getAttribute("codecs"))!==null&&b!==void 0?b:mo)!==null&&m!==void 0?m:"",ft=(S=(v=X.getAttribute("contentType"))!==null&&v!==void 0?v:Fe==null?void 0:Fe.split("/")[0])!==null&&S!==void 0?S:wa,Hi=(T=(y=fe.getAttribute("profiles"))===null||y===void 0?void 0:y.split(","))!==null&&T!==void 0?T:[],Gi=parseInt((E=X.getAttribute("width"))!==null&&E!==void 0?E:"",10),Pa=parseInt(($=X.getAttribute("height"))!==null&&$!==void 0?$:"",10),Ca=parseInt((N=X.getAttribute("bandwidth"))!==null&&N!==void 0?N:"",10)/1e3,Da=(O=X.getAttribute("frameRate"))!==null&&O!==void 0?O:"",So=(V=X.getAttribute("quality"))!==null&&V!==void 0?V:void 0,go=Da?fm(Da):void 0,yo=(_=X.getAttribute("id"))!==null&&_!==void 0?_:(fo++).toString(10),To=ft==="video"?`${Pa}p`:ft==="audio"?`${Ca}Kbps`:Kt,Eo=`${yo}@${To}`,$o=(C=(j=(F=X.querySelector("BaseURL"))===null||F===void 0?void 0:F.textContent)===null||j===void 0?void 0:j.trim())!==null&&C!==void 0?C:"",La=new URL($o||_t,e).toString(),ko=[...ji,...vo,...Hi];let Yi;const wo=X.querySelector("SegmentBase"),ze=(A=X.querySelector("SegmentTemplate"))!==null&&A!==void 0?A:bo;if(wo){const We=(D=(Y=X.querySelector("SegmentBase Initialization"))===null||Y===void 0?void 0:Y.getAttribute("range"))!==null&&D!==void 0?D:"",[Qe,zi]=We.split("-").map(pt=>parseInt(pt,10)),Ue={from:Qe,to:zi},xt=(w=X.querySelector("SegmentBase"))===null||w===void 0?void 0:w.getAttribute("indexRange"),[Wi,Jt]=xt?xt.split("-").map(pt=>parseInt(pt,10)):[],Nt=xt?{from:Wi,to:Jt}:void 0;Yi={type:ce.BYTE_RANGE,url:La,initRange:Ue,indexRange:Nt}}else if(ze){const We={representationId:(U=X.getAttribute("id"))!==null&&U!==void 0?U:void 0,bandwidth:(W=X.getAttribute("bandwidth"))!==null&&W!==void 0?W:void 0},Qe=parseInt((J=ze.getAttribute("timescale"))!==null&&J!==void 0?J:"",10),zi=(ee=ze.getAttribute("initialization"))!==null&&ee!==void 0?ee:"",Ue=ze.getAttribute("media"),xt=(Rt=parseInt((ge=ze.getAttribute("startNumber"))!==null&&ge!==void 0?ge:"",10))!==null&&Rt!==void 0?Rt:1,Wi=Tt(zi,We);if(!Ue)throw new ReferenceError("No media attribute in SegmentTemplate");const Jt=(ct=ze.querySelectorAll("SegmentTimeline S"))!==null&&ct!==void 0?ct:[],Nt=[];let pt=0,Qi="",Ki=0;if(Jt.length){let Xt=xt,pe=0;for(const mt of Jt){const ye=parseInt((B=mt.getAttribute("d"))!==null&&B!==void 0?B:"",10),Ke=parseInt((ie=mt.getAttribute("r"))!==null&&ie!==void 0?ie:"",10)||0,Zt=parseInt((re=mt.getAttribute("t"))!==null&&re!==void 0?re:"",10);pe=Number.isFinite(Zt)?Zt:pe;const Ji=ye/Qe*1e3,Xi=pe/Qe*1e3;for(let ei=0;ei<Ke+1;ei++){const Po=Tt(Ue,{...We,segmentNumber:Xt.toString(10),segmentTime:(pe+ei*ye).toString(10)}),Ra=(Xi!=null?Xi:0)+ei*Ji,Co=Ra+Ji;Xt++,Nt.push({time:{from:Ra,to:Co},url:Po})}pe+=(Ke+1)*ye,pt+=(Ke+1)*Ji}Ki=pe/Qe*1e3,Qi=Tt(Ue,{...We,segmentNumber:Xt.toString(10),segmentTime:pe.toString(10)})}else if(r.isNonNullable(qe)){const pe=parseInt((ne=ze.getAttribute("duration"))!==null&&ne!==void 0?ne:"",10)/Qe*1e3,mt=Math.ceil(qe/pe);let ye=0;for(let Ke=1;Ke<mt;Ke++){const Zt=Tt(Ue,{...We,segmentNumber:Ke.toString(10),segmentTime:ye.toString(10)});Nt.push({time:{from:ye,to:ye+pe},url:Zt}),ye+=pe}Ki=ye,Qi=Tt(Ue,{...We,segmentNumber:mt.toString(10),segmentTime:ye.toString(10)})}const Ao={time:{from:Ki,to:1/0},url:Qi};Yi={type:ce.TEMPLATE,baseUrl:La,segmentTemplateUrl:Ue,initUrl:Wi,totalSegmentsDurationMs:pt,segments:Nt,nextSegmentBeyondManifest:Ao,timescale:Qe}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ft||!Fe)continue;const qi={video:te.VIDEO,audio:te.AUDIO,text:te.TEXT}[ft];qi&&Ce[qi].push({id:Eo,kind:qi,segmentReference:Yi,profiles:ko,duration:qe,bitrate:Ca,mime:Fe,codecs:Kt,width:Gi,height:Pa,fps:go,quality:So})}}return{dynamic:co,liveAvailabilityStartTime:ho,duration:qe,container:po,representations:Ce}},mm=({id:i,width:e,height:t,bitrate:s,fps:a,quality:n})=>{var o;const l=(o=n?Mi(n):void 0)!==null&&o!==void 0?o:r.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:s,size:{width:e,height:t},fps:a}},vm=({id:i,bitrate:e})=>({id:i,bitrate:e}),bm=(i,e,t)=>{var s;const a=e.indexOf(t);return(s=De(i,Math.round(i.length*a/e.length)))!==null&&s!==void 0?s:De(i,-1)},Sm=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Vr=i=>"url"in i,yt=i=>i.type===ce.TEMPLATE,Ks=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class Fr{constructor(e,t,s,a,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:c,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.playingRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new wt,this.destroyAbortController=new wt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(h){const f=this.representations.get(h);r.assertNonNullable(f,`Cannot find representation ${h}`),this.playingRepresentationId=h,this.downloadingRepresentationId=h,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${f.mime}; codecs="${f.codecs}"`),this.sourceBufferTaskQueue=new Yf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Rr(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(f,"high",!0);const p=this.initData.get(f.id),b=this.segments.get(f.id),m=this.parsedInitData.get(f.id);r.assertNonNullable(p,"No init buffer for starting representation"),r.assertNonNullable(b,"No segments for starting representation"),p instanceof ArrayBuffer&&(this.searchGaps(b,f),yield this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(h){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return;this.switchingToRepresentationId=h;const f=this.representations.get(h);r.assertNonNullable(f,`No such representation ${h}`);let p=this.segments.get(h),b=this.initData.get(h);if(r.isNullable(b)||r.isNullable(p)?yield this.loadInit(f,"high",!1):b instanceof Promise&&(yield b),p=this.segments.get(h),r.assertNonNullable(p,"No segments for starting representation"),b=this.initData.get(h),!b||!(b instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield this.sourceBufferTaskQueue.append(b,this.downloadAbortController.signal);const m=this.getCurrentPosition();r.isNonNullable(m)&&(this.isLive||(p.forEach(v=>v.status=R.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))}.bind(this)),this.seekLive=r.abortable(this.destroyAbortController.signal,async function*(h){var f;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return;for(const y of this.representations.keys()){const T=h.find(N=>N.id===y);T&&this.representations.set(y,T);const E=this.representations.get(y);if(!E||!yt(E.segmentReference))return;const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const p=(f=this.switchingToRepresentationId)!==null&&f!==void 0?f:this.downloadingRepresentationId,b=this.representations.get(p);r.assertNonNullable(b);const m=this.segments.get(p);r.assertNonNullable(m,"No segments for starting representation");const v=this.initData.get(p);if(r.assertNonNullable(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,b),yield this.sourceBufferTaskQueue.append(v,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isActiveLowLatency=c,this.isLive=!!(d!=null&&d.dynamic),this.container=s,s){case At.MP4:this.containerParser=gp;break;case At.WEBM:this.containerParser=Ap;break;default:r.assertNever(s)}this.initData=new Map(a.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(h=>[h.id,h])),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 wt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const a=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=$t(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&a.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Rr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=$t(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&a)if(l.includes(a))u="high";else{const d=De(l,0);d&&d.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===R.FED&&!l.length&&$t(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=De(s,-1);c&&c.status===R.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(a===c))}searchGaps(e,t){this.gaps=[];let s=0;const a=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:n.time.from+a}),s=n.time.to;r.isNonNullable(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,a=[];let n=0,o=t.length-1;do a.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<s&&o>=0);return this.liveInitialAdditionalOffset=n-s,this.isActiveLowLatency()?[a[0]]:a}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(a=>a.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,a,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!yt(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>({...h,status:R.NONE,size:void 0})),c=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(a=De(c,-1))===null||a===void 0?void 0:a.time.to)!==null&&n!==void 0?n:0,d=l==null?void 0:l.findIndex(h=>Math.floor(u)>=Math.floor(h.time.from)&&Math.floor(u)<=Math.floor(h.time.to));if(d===-1){this.liveUpdateSegmentIndex=0;const h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{const h=l.slice(d+1);this.segments.set(o.id,[...c,...h])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const a=s.segmentReference;if(!yt(a))return;const n=Math.round(e.segment.time.to*a.timescale/1e3).toString(10),o=Tt(a.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],c=l.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.from));c&&(c.time.to=e.segment.time.to),!!l.find(d=>Math.floor(d.time.from)===Math.floor(e.segment.time.to))||l.push({status:R.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,s,a;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(c=>c.time.from<=e&&c.time.to>=e);return(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const a=e.findIndex(({status:h,time:{from:f,to:p}},b)=>{const m=f<=s&&p>=s,v=f>s||m||b===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+S||p<=s+S;return(h===R.NONE||h===R.PARTIALLY_EJECTED&&v&&y&&this.sourceBuffer&&!Ws(this.sourceBuffer.buffered,s))&&v&&y});if(a===-1)return[];if(t!==ce.BYTE_RANGE)return e.slice(a,a+1);const n=e;let o=0,l=0;const c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let h=a;h<n.length&&(o<=u||l<=d);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===R.NONE||f.status===R.PARTIALLY_EJECTED)c.push(f);else break}return c}async loadSegments(e,t,s="auto"){t.segmentReference.type===ce.TEMPLATE?await this.loadTemplateSegment(e[0],t,s):await this.loadByteRangeSegments(e,t,s)}async loadTemplateSegment(e,t,s="auto"){e.status=R.DOWNLOADING;const a={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(a);const{range:n,url:o,signal:l,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(await r.abortable(l,async function*(){const d=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,d))}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const d=await this.fetcher.fetch(o,{range:n,signal:l,onProgress:c,priority:s,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;a.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}c&&a.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(h,l),a.segment.status=R.DOWNLOADED,this.onSegmentFullyAppended(a,t.id),this.failedDownloads=0}catch(d){if(!Ks(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}}async loadByteRangeSegments(e,t,s="auto"){if(!e.length)return;for(const c of e)c.status=R.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:a,url:n,signal:o,onProgress:l}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(await r.abortable(o,async function*(){const c=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,c))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:a,onProgress:l,signal:o,priority:s}),this.failedDownloads=0}catch(c){if(!Ks(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}}prepareByteRangeFetchSegmentParams(e,t){if(yt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,a={from:De(e,0).byte.from,to:De(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:s,range:a,signal:n,onProgress:(c,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:a?a.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}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 a=s.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},l=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:d,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});l.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:a,signal:n,onProgress:u,onProgressTasks:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(s=$t((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:a,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:c}=l;if(l.representationId===t){if(n.aborted){a();continue}if(l.loadedBytes=s,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),d=this.containerParser.parseFeedableSegmentChunk(u);d!=null&&d.byteLength&&(c.status=R.PARTIALLY_FED,l.feedingBytes+=d.byteLength,await this.sourceBufferTaskQueue.append(d),l.fedBytes+=d.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:a,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const c=l.segmentReference.type,u=e.byteLength;for(const d of this.activeSegments){const{segment:h}=d,f=c===ce.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(d.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const m=f?h.byte.from-s:0,v=f?h.byte.to-s:e.byteLength,S=m<a,y=v<=a;if(h.status===R.DOWNLOADING&&S&&y){h.status=R.DOWNLOADED;const T=new DataView(e.buffer,e.byteOffset+m,p);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?this.onSegmentFullyAppended(d,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(d.loadedBytes=Math.min(p,a-m),d.loadedBytes>d.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+m+d.feedingBytes,d.loadedBytes-d.feedingBytes),E=d.loadedBytes===p?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(h.status=R.PARTIALLY_FED,d.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then($=>{if(n.aborted)o();else if($)d.fedBytes+=E.byteLength,d.fedBytes===p&&this.onSegmentFullyAppended(d,t);else{if(d.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=R.FED,Vr(e.segment)&&(e.segment.size=e.fedBytes);for(const a of this.representations.values())if(a.id!==t)for(const n of(s=this.segments.get(a.id))!==null&&s!==void 0?s:[])n.status===R.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=R.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===R.PARTIALLY_FED||e.status===R.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=R.NONE),e.status=R.PARTIALLY_EJECTED):e.status=R.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[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=Lr(()=>this.loadInit(s,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",s=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(c=>setTimeout(c,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,a)).then(async l=>{if(!l)return;const{init:c,dataView:u,segments:d}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h);let f=d;this.isLive&&yt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),c&&this.parsedInitData.set(e.id,c)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:r.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,s=!1){if(!this.sourceBuffer||!this.playingRepresentationId||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=0,n=1/0,o=-1/0,l=!1;const c=u=>{var d;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h=Vr(u)?(d=u.size)!==null&&d!==void 0?d:0:u.byte.to-u.byte.from;a+=h};for(const u of this.segments.values())for(const d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;d.status===R.FED&&c(d)}if(l=isFinite(n)&&isFinite(o),!l){a=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||a>t)break;d.status===R.FED&&c(d)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const d=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===R.NONE&&Math.round(p.time.from)<=Math.round(d)&&Math.round(p.time.to)>=Math.round(h)){n=d,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const h of d)h.time.from>e+u&&h.status===R.FED&&c(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 a={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){a=void 0;break}l>s.time.from&&l<s.time.to&&(a.from=l),o<s.time.to&&o>s.time.from&&(a.to=o)}}a&&a.to-a.from>1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Lr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const a=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:a,to:n})}const t=1;for(const s of this.segments.values())for(const a of s){const{status:n}=a;if(n!==R.FED&&n!==R.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.time.to),c=e.some(d=>d.from-t<=o&&d.to+t>=l),u=e.filter(d=>o>=d.from-t&&o<=d.to+t||l>=d.from-t&&l<=d.to+t);c||(u.length===1?a.status=R.PARTIALLY_EJECTED:a.status=R.NONE)}}}var Js=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},gm=i=>{var e,t;const s=i.get("X-Delivery-Type"),a=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},kt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(kt||(kt={}));class ym{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new wt,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=Js(n));const o=yield Ht(n,{signal:this.abortAllController.signal}).catch(Ot);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?kt.HEADER:kt.PARAM,range:o,onProgress:l,priority:c="auto",signal:u,measureThroughput:d=!0,isLowLatency:h=!1}={}){var f,p;let b=a;const m=new Headers;if(o)switch(n){case kt.HEADER:{m.append("Range",`bytes=${o.from}-${o.to}`);break}case kt.PARAM:{const A=new URL(b,location.href);A.searchParams.append("bytes",`${o.from}-${o.to}`),b=A.toString();break}default:r.assertNever(n)}this.requestQuic&&(b=Js(b));let v=this.abortAllController.signal,S;if(u){const A=new wt;if(S=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{A.abort()}catch(Y){Ot(Y)}}),this.abortAllController.signal.aborted||u.aborted)try{A.abort()}catch(Y){Ot(Y)}v=A.signal}const y=r.now(),T=yield Ht(b,{priority:c,headers:m,signal:v}).catch(Ot),E=r.now();if(!T)return S==null||S.unsubscribe(),null;if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(E-y),!T.ok||!T.body)return S==null||S.unsubscribe(),Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`));if(this.onHeadersReceived(T.headers),!l&&!d)return S==null||S.unsubscribe(),T.arrayBuffer();const[$,N]=T.body.tee(),O=$.getReader();d&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(N,h));let V=0,_=new Uint8Array(0),F=!1;const j=A=>{S==null||S.unsubscribe(),F=!0,Ot(A)},C=r.abortable(v,async function*({done:A,value:Y}){if(V===0&&this.lastRequestFirstBytes$.next(r.now()-y),v.aborted){S==null||S.unsubscribe();return}if(!A&&Y){const D=new Uint8Array(_.length+Y.length);D.set(_),D.set(Y,_.length),_=D,V+=Y.byteLength,l==null||l(new DataView(_.buffer),V),yield O==null?void 0:O.read().then(C,j)}}.bind(this));return yield O==null?void 0:O.read().then(C,j),S==null||S.unsubscribe(),F?null:_.buffer}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==ce.BYTE_RANGE)return null;const{from:c,to:u}=a.initRange;let d=c,h=u,f=!1,p,b;a.indexRange&&(p=a.indexRange.from,b=a.indexRange.to,f=u+1===p,f&&(d=Math.min(p,c),h=Math.max(b,u))),d=Math.min(d,0);const m=yield this.fetch(a.url,{range:{from:d,to:h},priority:o,measureThroughput:!1});if(!m)return null;const v=new DataView(m,c-d,u-d+1);if(!n.validateData(v))throw new Error("Invalid media file");const S=n.parseInit(v),y=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!y)throw new ReferenceError("No way to load representation index");let T;if(f)T=new DataView(m,y.from-d,y.to-y.from+1);else{const $=yield this.fetch(a.url,{range:y,priority:o,measureThroughput:!1});if(!$)return null;T=new DataView($)}const E=n.parseSegments(T,S,y);return{init:S,dataView:new DataView(m),segments:E}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==ce.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:a.segments.map(u=>({...u,status:R.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=gm(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}async fetchRepresentation(e,t,s="auto"){var a,n;const{type:o}=e;switch(o){case ce.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,s))!==null&&a!==void 0?a:null;case ce.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Ot=i=>{if(!Ks(i))throw i},Xs=1e3,Ci=(i,e,t)=>t*e+(1-t)*i,so=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Tm=(i,e,t,s)=>{let a=0,n=t;const o=so(i,e),l=e<s?e:s;for(let c=0;c<l;c++)i[n]>o?a++:a--,n=(i.length+n-1)%i.length;return Math.abs(a)===l};class ga{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ke(`raw_${s}`),this.smoothedSeries$=new ke(`smoothed_${s}`),this.reportedSeries$=new ke(`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 l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,s++);this.takenMeasures=s,t/=s;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class Em extends ga{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ci(this.slow,e,this.params.emaAlphaSlow),this.fast=Ci(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class $m extends ga{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=so(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ci(this.emaSmoothed,e,this.params.emaAlpha);const s=Tm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class km extends ga{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?Ci(this.smoothed,e,this.params.emaAlpha):e}}class Zs{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new Em({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new $m({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 km({initial:e,label:"liveEdgeDelay",...t})}}const wm=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Je=()=>window.ManagedMediaSource||window.MediaSource,ao=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},Am=()=>{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))},Pm=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,Ur=["timeupdate","progress","play","seeked","stalled","waiting"];var ue;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(ue||(ue={}));let Cm=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.representationSubscription=new r.Subscription,this.state$=new K(ue.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.currentVideoRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.isLive$=new r.ValueSubject(!1),this.liveDuration$=new r.ValueSubject(0),this.liveAvailabilityStartTime$=new r.ValueSubject(void 0),this.bufferLength$=new r.ValueSubject(0),this.liveLoadBufferLength$=new r.ValueSubject(0),this.livePositionFromPlayer$=new r.ValueSubject(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new wt,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,s,a){var n;this.element=t,this.manifestUrlString=ve(s,a,Z.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ue.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(ue.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=r.abortable(this.destroyController.signal,async function*(){var t;const s=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!s)return null;let a;try{a=pm(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return null;const n=({kind:o,mime:l,codecs:c})=>{var u,d,h,f;return!!(!((d=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||d===void 0)&&d.call(u,l)&&(!((f=(h=Je())===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${c}"`))||o===te.TEXT)};return a.dynamic&&this.isLive$.getValue()!==a.dynamic&&(this.isLive$.next(a.dynamic),this.liveDuration$.getValue()!==a.duration&&this.liveDuration$.next(-1*((t=a.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==a.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(a.liveAvailabilityStartTime)),{...a,representations:ki(Object.entries(a.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,s,a){var n;r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ue.REPRESENTATIOS_READY);const o=m=>{this.representationSubscription.add(r.fromEvent(m,"error").pipe(r.filter(v=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(v=>{this.error$.next({id:"VideoSource",category:r.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:v})}))};this.source=this.tuning.useManagedMediaSource?Pm():new MediaSource;const l=document.createElement("source");if(o(l),l.src=URL.createObjectURL(this.source),this.element.appendChild(l),this.tuning.useManagedMediaSource&&ao())if(a){const m=document.createElement("source");o(m),m.type="application/x-mpegurl",m.src=a.url,this.element.appendChild(m)}else this.element.disableRemotePlayback=!0;this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const c={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 Fr(te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,c),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(s)&&(this.audioBufferManager=new Fr(te.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,c),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(r.interval(Xs).subscribe(m=>{var v;if(!((v=this.element)===null||v===void 0)&&v.paused){const S=kr(this.manifestUrlString,Z.DASH_CMAF_OFFSET_P);this.manifestUrlString=ve(this.manifestUrlString,S+Xs,Z.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Ur.map(m=>r.fromEvent(this.element,m))).pipe(r.map(m=>this.element?$t(this.element.buffered,this.element.currentTime*1e3):0),r.filterChanged(),r.filter(m=>!!m),r.tap(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(r.filter(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,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=v-S;let $=1+Math.sign(E)*T;Math.abs(E)<y?$=1:Math.abs(E)>y*2&&($=1+Math.sign(E)*T*2),wm(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(v=>{var S,y;let T=0;if(v){const E=((y=(S=this.element)===null||S===void 0?void 0:S.currentTime)!==null&&y!==void 0?y:0)*1e3;T=Math.min(...this.bufferManagers.map(N=>{var O,V;return(V=(O=N.getLiveSegmentsToLoadState(this.manifest))===null||O===void 0?void 0:O.to)!==null&&V!==void 0?V:0}))-E}T&&this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let m=0;this.representationSubscription.add(r.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(async({liveLoadBufferLength:v,bufferLength:S})=>{if(r.assertNonNullable(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,T=kr(this.manifestUrlString,Z.DASH_CMAF_OFFSET_P),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,$=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),N=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,O=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,V=this.isActiveLowLatency?S:v;let _=$e.None;if(this.isActiveLowLatency?_=$e.ActiveLowLatency:V<$+O&&V>=$?_=$e.LiveWithTargetOffset:T!==0&&V<$&&(_=$e.LiveForwardBuffering),isFinite(v)&&(m=v>m?v:m),_===$e.LiveForwardBuffering||_===$e.LiveWithTargetOffset){const F=m-($+N),j=this.normolizeLiveOffset(Math.trunc(T+F/y)),C=Math.abs(j-T);let A;!v||C<=this.tuning.dashCmafLive.offsetCalculationError?A=T:j>0&&C>this.tuning.dashCmafLive.offsetCalculationError?A=j:A=0,this.manifestUrlString=ve(this.manifestUrlString,A,Z.DASH_CMAF_OFFSET_P)}_!==$e.None&&_!==$e.ActiveLowLatency&&(m=0,this.updateLive())}))}const u=r.merge(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),d=r.merge(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:u,someBufferEnded:d}).pipe(r.filter(({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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:v})}})),this.representationSubscription.add(r.merge(...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 h=(n=this.manifest.duration)!==null&&n!==void 0?n:0,f=(m,v)=>{var S;return Math.max(m,(S=v.duration)!==null&&S!==void 0?S:0)},p=this.manifest.representations.audio.reduce(f,h),b=this.manifest.representations.video.reduce(f,h);(p||b)&&(this.source.duration=Math.max(p,b)/1e3),this.audioBufferManager&&r.isNonNullable(s)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)]):yield this.videoBufferManager.startWith(t),this.state$.setState(ue.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new ym({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=Zs.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,s,a,n;r.assertNonNullable(this.element);const o=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&o===0,this.liveLastSeekOffset=o,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=ve(this.manifestUrlString,o,Z.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((a=this.audioBufferManager)===null||a===void 0?void 0:a.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)))}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(ue.RUNNING),this.subscription.add(r.merge(...Ur.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Ws(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={[te.VIDEO]:this.videoBufferManager,[te.AUDIO]:this.audioBufferManager,[te.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)}seek(e,t){var s,a,n,o,l;r.assertNonNullable(this.element),r.assertNonNullable(this.videoBufferManager);let c;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?c=e:c=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Ws(this.element.buffered,c)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(c),(l=this.audioBufferManager)===null||l===void 0||l.maintain(c),this.element.currentTime=c/1e3}stop(){var e,t,s;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(a=>a.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(ue.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:r.ErrorCategory.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 a of this.bufferManagers)for(const n of a.gaps)a.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const a=Math.max(...s);a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(a)&&(this.element.currentTime=a/1e3)}}};class Dm{constructor(e,t){this.fov=e,this.orientation=t}}class Lm{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 a=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:a,y:n,z:o},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 a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 Rm=`#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;}`,Im=`#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 xm{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Dm(this.params.fov,this.params.orientation),this.cameraRotationManager=new Rm(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"),a=this.gl.getUniformLocation(this.program,"u_texture"),n=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(a,0),this.gl.uniform2f(n,-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(Lm,this.gl.VERTEX_SHADER),s=this.createShader(Im,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 a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:s=a/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,a=this.camera.fov.y/180/2,n=e-s,o=t-a,l=e+s,c=t-a,u=e+s,d=t+a,h=e-s,f=t+a;return[n,o,l,c,u,d,h,f]}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 _m=(i,e)=>new r.Observable(t=>{if(!window.IntersectionObserver)return;const s=()=>!!window.documentPictureInPicture.window||!!document.pictureInPictureElement,a={root:null},n=new IntersectionObserver((l,c)=>{l.forEach(u=>t.next(u.isIntersecting||s()))},{...a,...e});n.observe(i);const o=r.fromEvent(document,"visibilitychange").pipe(r.map(l=>!document.hidden||s())).subscribe(l=>t.next(l));return()=>{n.unobserve(i),o.unsubscribe}});class ro{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(z.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.elementVisible$=new r.ValueSubject(!0),this.textTracksManager=new Ge,this.droppedFramesManager=new zn,this.videoTracks$=new r.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new $f,this.textTracks=[],this.syncPlayback=()=>{var t,s,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(c.state===O.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==z.STOPPED&&o!==exports.PlaybackState.STOPPED){const d=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(c.position-d,c.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==z.STOPPED&&(this.videoState.startTransitionTo(z.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(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();return;case z.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),(a=this.liveOffset)===null||a===void 0||a.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.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()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}}},this.init3DScene=t=>{var s,a,n;if(this.scene3D)return;this.scene3D=new xm(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:((a=t.projectionData)===null||a===void 0?void 0:a.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.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 o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.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(Pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Cm({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=lt(this.video),a=this.constructor.name,n=l=>{e.error$.next({id:a,category:r.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:n,connect:(l,c)=>this.subscription.add(l.subscribe(c,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:n}=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(r.map(u=>u.map(({track:d})=>d)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Wt(this.video,t.isLooped,a)),this.subscription.add(ot(this.video,t.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Rt(this.video,t.playbackRate,s.playbackRateState$,a)),n(Ff(this.video),this.elementSize$),n(_m(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var d;if(u===ue.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();r.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((S,y)=>y.bitrate-S.bitrate),b=Array.from(f.video).sort((S,y)=>y.bitrate-S.bitrate),m=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const S of p){const y=vm(S);y&&this.audioTracks.push({track:y,representation:S})}for(const S of b){const y=mm(S);if(y){h.push({track:y,representation:S});const E=!this.params.tuning.isAudioDisabled&&bm(p,b,S);E&&this.audioRepresentations.set(S.id,E)}}this.videoTracks$.next(h);for(const S of m){const y=Sm(S);y&&this.textTracks.push({track:y,representation:S})}this.params.output.availableVideoTracks$.next(h.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();r.assertNonNullable(v),this.player.initRepresentations(v.id,(d=this.audioRepresentations.get(v.id))===null||d===void 0?void 0:d.id,this.params.sourceHls)}else u===ue.REPRESENTATIOS_READY&&(this.videoState.setState(z.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),d=this.player.state$.getTransition();if(u!==ue.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);const p=this.params.desiredState.autoVideoTrackSwitching.getState(),b=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(h){let m=h.id;!this.elementVisible$.getValue()&&p&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,y)=>y.bitrate-S.bitrate).filter(S=>{const{width:y,height:E}=S,{width:T,height:$}=h,x=Math.min(y,E)+"p",_=Math.min(T,$)+"p";return r.isLowerOrEqual(x,_)&&r.isLowerOrEqual(x,b)}).map(S=>S.id)[0]),this.player.switchRepresentation(te.VIDEO,m).catch(o);const v=this.audioRepresentations.get(h.id);v&&this.player.switchRepresentation(te.AUDIO,v.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var d;return u&&((d=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||d===void 0?void 0:d.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var d,h;if(u!=null&&u.is3dVideo&&(!((d=this.params.tuning.spherical)===null||d===void 0)&&d.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const c=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,s,a,n,o,l;const c=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,d=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=$t(this.video.buffered,this.video.currentTime*1e3),p=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!c&&(a=(s=this.audioRepresentations.get(d.id))===null||s===void 0?void 0:s.bitrate)!==null&&a!==void 0?a:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),v=Bi(this.videoTracks$.getValue().map(({track:y})=>y),{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:b,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=c?v!=null?v:d:d!=null?d:v;return S&&((l=this.videoTracks$.getValue().find(({track:y})=>y===S))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ut(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),nt(this.video)}}class Nm extends ro{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 Om extends ro{constructor(e){super(e),this.liveOffset=new ma}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(r.combine({interval:r.interval(Xs),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var n;if(this.videoState.getState()===z.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(a-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:a,liveAvailabilityStartTime:n})=>a&&n?a+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&s===z.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,a)})}}const Ee={};var M;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const Mt=(i,e)=>new r.Observable(t=>{const s=(a,n)=>t.next(n);return i.on(e,s),()=>i.off(e,s)});class Mm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(M.INITIALIZING),this.textTracksManager=new Ge,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==M.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===O.Requested&&this.seek(n.position),s){case exports.PlaybackState.STOPPED:switch(t){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(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(Pe(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),nt(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(a=>{e||(Ee.Hls=a.default,Ee.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){r.assertNonNullable(Ee.Hls,"hls.js not loaded"),this.hls=new Ee.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){r.assertNonNullable(Ee.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=lt(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,s));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Wt(this.video,e.isLooped,s)),this.subscription.add(ot(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Rt(this.video,e.playbackRate,a.playbackRateState$,s)),this.subscription.add(Mt(this.hls,Ee.Events.ERROR).subscribe(u=>{var d;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(d=u.err)===null||d===void 0?void 0:d.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},s)),n(Mt(this.hls,Ee.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((d,h)=>{var f,p;const b=h.name||h.height.toString(10),{width:m,height:v}=h,S=(p=Mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:r.videoSizeToQuality({width:m,height:v});if(!S)return d;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,E={id:b.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:m,height:v},fps:y};return this.trackLevels.set(b,{track:E,level:h}),d.push(E),d},[]))),t.availableVideoTracks$),n(Mt(this.hls,Ee.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const d=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI||"",b=h.lang,m="internal";d.push({id:f,url:p,language:b,type:m})}e.internalTextTracks.startTransitionTo(d)}}),n(Mt(this.hls,Ee.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>Pe(u))),t.hostname$),this.subscription.add(Re(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:s}));const o=u=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||d===void 0?void 0:d.track},l=Mt(this.hls,Ee.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Re(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var d;if(r.isNullable(u))return;const h=(d=this.trackLevels.get(u.id))===null||d===void 0?void 0:d.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,b=this.hls.levels[p];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:s})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await ut(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.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(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const jr="X-Playback-Duration";var Hr=async i=>{var e;const t=await Ht(i),s=await t.text(),a=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return a?parseInt(a,10):t.headers.has(jr)?parseInt(t.headers.get(jr),10):void 0};const Bm=i=>{let e=null;if(i.QUALITY&&(e=Mi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=r.videoSizeToQuality({width:t,height:s})}return e!=null?e:null},Vm=(i,e)=>{var t,s;const a=i.split(`
46
- `),n=[],o=[];for(let l=0;l<a.length;l++){const c=a[l],u=c.match(/^#EXT-X-STREAM-INF:(.+)/),d=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!d)){if(u){const h=ki(u[1].split(",").map(y=>y.split("="))),f=(t=h.QUALITY)!==null&&t!==void 0?t:`stream-${h.BANDWIDTH}`,p=Bm(h);let b;h.BANDWIDTH&&(b=parseInt(h.BANDWIDTH,10)/1e3||void 0),!b&&h["AVERAGE-BANDWIDTH"]&&(b=parseInt(h["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=h["FRAME-RATE"]?parseFloat(h["FRAME-RATE"]):void 0;let v;if(h.RESOLUTION){const[y,E]=h.RESOLUTION.split("x").map(T=>parseInt(T,10));y&&E&&(v={width:y,height:E})}const S=new URL(a[++l],e).toString();p&&n.push({id:f,quality:p,url:S,bandwidth:b,size:v,fps:m})}if(d){const h=ki(d[1].split(",").map(m=>m.split("=")).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),f=(s=h.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),p=h.LANGUAGE,b=h.NAME;f&&p&&o.push({type:"internal",id:p,label:b,language:p,url:f,isAuto:!1})}}}if(!n.length)throw new Error("Empty manifest");return{qualityManifests:n,textTracks:o}},Fm=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let As=0;const ya=async(i,e=i,t)=>{const a=await(await Ht(i)).text();As+=1;try{const{qualityManifests:n,textTracks:o}=Vm(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(As<=t.manifestRetryMaxCount)return await Fm(r.getExponentialDelay(As-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ya(i,e,t)}return{qualityManifests:[],textTracks:[]}};var H;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(H||(H={}));class Um{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new K(H.STOPPED),this.textTracksManager=new Ge,this.manifests$=new r.ValueSubject([]),this.liveOffset=new ma,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){a!==H.STOPPED&&(this.videoState.startTransitionTo(H.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(H.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(a===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(l||c||u){const f=this.videoState.getState();this.videoState.setState(H.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===O.Requested){this.videoState.startTransitionTo(H.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case H.READY:n===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(H.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 f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case H.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},ya(ve(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:r.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.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(Pe(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,a;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(a=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=o.getState())===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:"master",d=this.manifests$.getValue();if(!d.length)return;const h=l?"master":u;return l&&!c&&o.startTransitionTo(this.masterManifest),d.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=lt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,s));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(ot(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===H.READY&&this.videoState.setState(H.READY),this.videoState.getState()===H.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Pe(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from===H.CHANGING_MANIFEST&&this.videoState.setState(c.to),l&&l.state===O.Requested&&this.seek(l.position)},s)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,c,u;const d=(u=(c=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||c===void 0?void 0:c.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(d||void 0)},s)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:c})=>this.params.output.liveTime$.next(l+c*1e3),s)),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:c,quality:u,size:d,bandwidth:h,fps:f})=>({id:c,quality:u,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(r.isNullable(s))return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(s.url);if((a||n)&&s.id===this.masterManifest.id){const{max:u,min:d}=(t=(e=a==null?void 0:a.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[h,f]of[[u,"mq"],[d,"lq"]]){const p=String(parseFloat(h||""));f&&h&&o.searchParams.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?Z.DASH_CMAF_OFFSET_P:Z.OFFSET_P,c=ve(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",c),this.video.load(),Hr(c).then(u=>{var d;if(!r.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(d=this.params.source.maxSeekBackTime)!==null&&d!==void 0?d:this.maxSeekBackTime$.getValue();if(r.isNullable(h)||!isFinite(h))try{Ht(c).then(f=>f.text()).then(f=>{var p;const b=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(b){const m=new URL(b,c).toString();Hr(m).then(v=>{r.isNullable(v)||this.maxSeekBackTime$.next(v)})}})}catch(f){}}})}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(q||(q={}));class jm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(q.STOPPED),this.textTracksManager=new Ge,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=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(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===exports.PlaybackState.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o||l||c){const h=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),d.state===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&d.state===O.Requested&&this.seek(d.position),s){case q.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case q.CHANGING_MANIFEST:break;default:return r.assertNever(s)}},this.params=e,this.video=rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ya(ve(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:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,a;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(a=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=o.getState())===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:"master",d=this.manifests$.getValue();if(!d.length)return;const h=l?"master":u;return l&&!c&&o.startTransitionTo(this.masterManifest),d.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=lt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c));if(n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Wt(this.video,t.isLooped,s)),this.subscription.add(ot(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},s).add(a.loadedMetadata$.subscribe(()=>{var l;const c=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&r.isNonNullable(d.to)){const f=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const p=this.manifests$.getValue().find(b=>b.id===f);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Pe(p.url));const b=this.params.desiredState.playbackRate.getState(),m=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(b!==m){const v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(b),v.playbackRate=b)}}}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),u&&u.from===q.CHANGING_MANIFEST&&this.videoState.setState(u.to),c.state===O.Requested&&this.seek(c.position)},s))),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:c,quality:u,size:d,bandwidth:h,fps:f})=>({id:c,quality:u,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s)),!r.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(r.merge(r.fromEvent(l,"addtrack"),r.fromEvent(l,"removetrack"),r.fromEvent(l,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let c=0;c<l.length;c++)l[c].mode="hidden"},s))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(r.isNullable(s))return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(s.url);if((a||n)&&s.id===this.masterManifest.id){const{max:l,min:c}=(t=(e=a==null?void 0:a.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,d]of[[l,"mq"],[c,"lq"]]){const h=String(parseFloat(u||""));d&&u&&o.searchParams.set(d,h)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));class Hm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(Q.STOPPED),this.trackUrls={},this.textTracksManager=new Ge,this.syncPlayback=()=>{var t,s,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.seekState.getState();if(u&&n!==Q.READY&&!d){this.handleQualityLimitTransition(u.to.max);return}if(n===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(d){const{currentTime:f}=this.video;this.prepare(),h.state===O.None&&this.params.desiredState.seekState.setState({state:O.Requested,position:f*1e3,forcePrecise:!0}),d.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((a=(s=this.trackUrls[d.to.id])===null||s===void 0?void 0:s.track)===null||a===void 0?void 0:a.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===O.Requested&&this.seek(h.position),n){case Q.READY:o===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}},this.params=e,this.video=rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},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=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=lt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Wt(this.video,t.isLooped,s)),this.subscription.add(ot(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Rt(this.video,t.playbackRate,a.playbackRateState$,s)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l,c;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Q.READY&&this.videoState.setState(Q.READY);const u=this.params.desiredState.videoTrack.getTransition();if(u&&r.isNonNullable(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);const d=this.params.desiredState.playbackRate.getState(),h=(c=this.params.output.element$.getValue())===null||c===void 0?void 0:c.playbackRate;if(d!==h){const f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}}this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),nt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;r.assertNonNullable(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];r.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Js(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Pe(s))}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,a,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const c=(s=Object.values(this.trackUrls).find(h=>!r.isInvariantQuality(h.track.quality)&&r.isLowerOrEqual(h.track.quality,e)))===null||s===void 0?void 0:s.track,u=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,d=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(c&&d&&r.isHigherOrEqual(d.quality,c.quality)&&(o=c),!o){const h=Object.values(this.trackUrls).filter(p=>!r.isInvariantQuality(p.track.quality)&&r.isHigher(p.track.quality,e)),f=h.length;f&&(o=h[f-1].track)}o&&(l=o.quality)}else if(!e){const c=Object.values(this.trackUrls).map(u=>u.track);o=Bi(c,{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})}o&&(this.params.output.currentVideoTrack$.next(o),this.params.desiredState.videoTrack.startTransitionTo(o)),this.params.output.autoVideoTrackLimits$.next({max:l})}}const Gr=["stun:videostun.mycdn.me:80"],Gm=1e3,Ym=3,Ps=()=>null;class qm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ps,this.externalStopCallback=Ps,this.externalErrorCallback=Ps,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:Gr}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),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),Gm)}normalizeOptions(e={}){const t={stunServerList:Gr,maxRetryNumber:Ym,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var G;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(G||(G={}));class zm{constructor(e){this.videoState=new K(G.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED){t!==G.STOPPED&&(this.videoState.startTransitionTo(G.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(G.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case G.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=rt(e.container),this.liveStreamClient=new qm(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),nt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=lt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,s));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===G.READY&&this.videoState.setState(G.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},s)).add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING)},s)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ot(this.video,t.volume,a.volumeState$,s)).add(a.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case G.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case G.READY:break;case G.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case G.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},s)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:r.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(G.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Yr{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 Cs,Ds,Rs,Ls,di,Is,hi,xs,fi,_s,pi,Ns,mi,Os,vi,Ms;const no=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,He=document.createElement("video"),Wm='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Qm='video/mp4; codecs="hev1.1.6.L93.B0"',oo='video/webm; codecs="vp09.00.10.08"',lo='video/webm; codecs="av01.0.00M.08"',Km='audio/mp4; codecs="mp4a.40.2"',Jm='audio/webm; codecs="opus"',Xe={mms:ao(),mse:Am(),hls:!!(!((Cs=He.canPlayType)===null||Cs===void 0)&&Cs.call(He,"application/x-mpegurl")||!((Ds=He.canPlayType)===null||Ds===void 0)&&Ds.call(He,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},le={mp4:!!(!((Rs=He.canPlayType)===null||Rs===void 0)&&Rs.call(He,"video/mp4")),webm:!!(!((Ls=He.canPlayType)===null||Ls===void 0)&&Ls.call(He,"video/webm")),cmaf:!0},Ae={h264:!!(!((Is=(di=Je())===null||di===void 0?void 0:di.isTypeSupported)===null||Is===void 0)&&Is.call(di,Wm)),h265:!!(!((xs=(hi=Je())===null||hi===void 0?void 0:hi.isTypeSupported)===null||xs===void 0)&&xs.call(hi,Qm)),vp9:!!(!((_s=(fi=Je())===null||fi===void 0?void 0:fi.isTypeSupported)===null||_s===void 0)&&_s.call(fi,oo)),av1:!!(!((Ns=(pi=Je())===null||pi===void 0?void 0:pi.isTypeSupported)===null||Ns===void 0)&&Ns.call(pi,lo)),aac:!!(!((Os=(mi=Je())===null||mi===void 0?void 0:mi.isTypeSupported)===null||Os===void 0)&&Os.call(mi,Km)),opus:!!(!((Ms=(vi=Je())===null||vi===void 0?void 0:vi.isTypeSupported)===null||Ms===void 0)&&Ms.call(vi,Jm))},Bt=(Ae.h264||Ae.h265)&&Ae.aac;var je;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(je||(je={}));var xe;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(xe||(xe={}));let Ze;const Xm=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:lo}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:oo}})]);Ze={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Xm()}catch(i){console.error(i)}const Gt=Xe.hls&&le.mp4,Zm=()=>Object.keys(Ae).filter(i=>Ae[i]),ev=(i,e=!1,t=!1)=>{const s=Xe.mse||Xe.mms&&t;return i.filter(a=>{switch(a){case exports.VideoFormat.DASH_SEP:return s&&le.mp4&&Bt;case exports.VideoFormat.DASH_WEBM:return s&&le.webm&&Ae.vp9&&Ae.opus;case exports.VideoFormat.DASH_WEBM_AV1:return s&&le.webm&&Ae.av1&&Ae.opus;case exports.VideoFormat.DASH_LIVE:return Xe.mse&&le.mp4&&Bt;case exports.VideoFormat.DASH_LIVE_CMAF:return s&&le.mp4&&Bt&&le.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return s&&le.mp4&&Bt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return Gt||e&&Xe.mse&&le.mp4&&Bt;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return Gt;case exports.VideoFormat.MPEG:return le.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Xe.webrtc&&Xe.ws&&Ae.h264&&(le.mp4||le.webm);default:return r.assertNever(a)}})},Vt=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case je.VP9:return[e,t];case je.AV1:return[t,e];case je.NONE:return[];case je.SMOOTH:return Ze?Ze[t].smooth?[t,e]:Ze[e].smooth?[e,t]:[t,e]:[e,t];case je.POWER_EFFICIENT:return Ze?Ze[t].powerEfficient?[t,e]:Ze[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(i)}return[e,t]},tv=({webmCodec:i,androidPreferredFormat:e})=>{if(no)switch(e){case xe.MPEG:return[exports.VideoFormat.MPEG,...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case xe.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case xe.DASH:return[...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return Gt?[...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},iv=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],a=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...s,...a],o=[...a,...s];let l;if(no)switch(i){case xe.DASH:{l=n;break}case xe.HLS:case xe.MPEG:{l=o;break}}else Gt?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},qr=i=>i?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var sv=i=>new r.Observable(e=>{const t=new r.Subscription,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(r.map(({type:u})=>u!==void 0)),o=new r.Subject;let l=0,c="unknown";return t.add(s.subscribe(u=>{l&&window.clearTimeout(l),c=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),c="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(c),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const av={chunkDuration:5e3,maxParallelRequests:5};class rv{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=ev([...iv(this.params.tuning),...tv(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>r.isNonNullable(e.sources[l])),{forceFormat:s,formatsToAvoid:a}=this.params.tuning;let n=[];s?n=[s]:a.length?n=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Yr(n);const o=[...qr(!0),...qr(!1)];this.chromecastFormatsIterator=new Yr(o.filter(l=>r.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}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(),a=s.state!==O.None;if(this.params.desiredState.seekState.setState({state:O.Requested,position:a?s.position:t,forcePrecise:a?s.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case se.SCREEN:return this.createScreenProvider(t);case se.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:a}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t[exports.VideoFormat.HLS_ONDEMAND]||t[exports.VideoFormat.HLS]);return r.assertNonNullable(l),new Nm({...o,source:l,sourceHls:c})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Om({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Gt||!this.params.tuning.useHlsJs?new jm({...o,source:l}):new Mm({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Um({...o,source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Hm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Bf({...o,source:l,config:{...av,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new zm({container:s,source:l,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new Xh({connection:l,meta:n,container:s,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?se.CHROMECAST:se.SCREEN}chooseFormat(e){switch(e){case se.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case se.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case se.SCREEN:return this.screenFormatsIterator.next();case se.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case se.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case se.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return ki(Object.entries(e).map(([a,n])=>[a,s(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,s=0;return e.add(r.merge(this.providerOutput.error$,sv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===se.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(se.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===r.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=s<this.params.tuning.providerErrorLimit;l&&(o&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(s++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:se.SCREEN)}})),e}}const nv=5e3,zr="one_video_throughput",Wr="one_video_rtt",_e=window.navigator.connection,Qr=()=>{const i=_e==null?void 0:_e.downlink;if(r.isNonNullable(i)&&i!==10)return i*1e3},Kr=()=>{const i=_e==null?void 0:_e.rtt;if(r.isNonNullable(i)&&i!==3e3)return i},Jr=(i,e,t)=>{const s=t*8,a=s/i;return s/(a+e)};class Ut{constructor(e){var t,s;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Ut.load(zr)||(e.useBrowserEstimation?Qr():void 0)||nv,n=(s=(t=Ut.load(Wr))!==null&&t!==void 0?t:e.useBrowserEstimation?Kr():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Jr(a,n,e.rttPenaltyRequestSize)),this.throughput=Zs.getSmoothedValue(a,-1,e),this.rtt=Zs.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const c=Qr();c&&this.throughput.next(c);const u=Kr();r.isNonNullable(u)&&this.rtt.next(u)};_e&&"onchange"in _e&&this.subscription.add(r.fromEvent(_e,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{r.safeStorage.set(zr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{r.safeStorage.set(Wr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Jr(o,l,e.rttPenaltyRequestSize)),r.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,s=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),c=o-t,u=l-s;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let a=0,n=r.now(),o=0,l=r.now();const c=d=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:h})=>{if(d)!t&&this.addRawSpeed(a,r.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(r.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=h.byteLength;else{const p=l-n;p&&this.addRawSpeed(o,p,1,t),o=h.byteLength,n=r.now()}l=r.now()}else a+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&r.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,r.now()-l,this.concurrentDownloads.size),o=0,l=r.now());await(s==null?void 0:s.read().then(u,c))}};this.concurrentDownloads.add(e),s==null||s.read().then(u,c)}addRawSpeed(e,t,s=1,a=!1){if(Ut.sanityCheck(e,t,a)){const n=e*8/t;this.throughput.next(n*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=r.safeStorage.get(e);if(r.isNonNullable(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Xr={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:r.VideoQuality.Q_480P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.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:je.VP9,androidPreferredFormat:xe.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}},ov=i=>{var e;return{...r.fillWithDefault(i,Xr),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Xr.configName]}};var Zr=({seekState:i,position$:e})=>r.merge(i.stateChangeEnded$.pipe(r.map(({to:t})=>{var s;return t.state===O.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>i.getState().state===O.None))),lv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return r.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const uv=(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(r.filter(a=>a.length>0),r.once()).subscribe(a=>{a.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class cv{constructor(e={configName:[]}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:O.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),internalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({}),cameraOrientation:new K({x:0,y:0})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:yf},this.initLogs(),this.tuning=ov(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Mo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ut(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,a)=>{const n=Reflect.get(t,s,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const c=o.map(h=>JSON.stringify(h,(f,p)=>{const b=typeof p;return["number","string","boolean"].includes(b)?p:p===null?null:`<${b}>`})),u=`Player.${String(s)}`,d=`Exception calling ${u} (${c.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:d,thrown:l}),l}}}})}initVideo(e){var t,s,a;return this.config=e,this.domContainer=lv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new rv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=s&&!a&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:O.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(r.filter(s=>s.length>0),r.once()).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;r.assertNonNullable(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 uv(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 a=s.getCameraRotation(),n=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+n.x,y:a.y+n.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(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===O.None?void 0:t.position;return r.isNonNullable(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:a})=>s||a||0,0),height:e.reduce((s,{height:a})=>s||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===O.Requested?this.desiredState.seekState.setState({...o,state:O.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===O.Applying&&(this.desiredState.seekState.setState({state:O.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:l})=>l).sort((l,c)=>r.isInvariantQuality(l)?1:r.isInvariantQuality(c)?-1:r.isHigher(c,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const c of o)c.fps&&(l[c.quality]=c.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(r.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:l,isLowLatency:c})=>{const u=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(l)<u/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:l,duration:c})=>o&&(Math.abs(c)-Math.abs(l))*1e3<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(Zr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o!=null?o:r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>s.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,s).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||s.getValue();return o&&!l}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,c;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(c=o==null?void 0:o.size)===null||c===void 0?void 0:c.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let d;u===exports.ChromecastState.CONNECTED?d=exports.Surface.SECOND_SCREEN:c?o?d=exports.Surface.PIP:l?d=exports.Surface.FULLSCREEN:d=exports.Surface.INLINE:d=exports.Surface.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((s,a)=>s.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(s=>s.length>0),r.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const a=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;a&&(s=e.find(({quality:n})=>n===a),s||this.setAutoQuality(!0)),s||(s=Bi(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(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),gf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Sf(s)),this.providerContainer.current$.subscribe(({type:s})=>ui("provider",s)),t.duration$.subscribe(s=>ui("duration",s)),t.availableVideoTracks$.pipe(r.filter(s=>!!s.length),r.once()).subscribe(s=>ui("tracks",s)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),t.position$.subscribe(new ke("position")),t.currentVideoTrack$.pipe(r.map(s=>s==null?void 0:s.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),t.isBuffering$.subscribe(new ke("isBuffering"))].forEach(s=>this.subscription.add(s)),ui("codecs",Zm())}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(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);a&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(a=>a.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const dv=`@vkontakte/videoplayer-core@${en}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=cv;exports.SDK_VERSION=dv;exports.VERSION=en;
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 _m{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Dm(this.params.fov,this.params.orientation),this.cameraRotationManager=new Lm(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"),a=this.gl.getUniformLocation(this.program,"u_texture"),n=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(a,0),this.gl.uniform2f(n,-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(Rm,this.gl.VERTEX_SHADER),s=this.createShader(Im,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 a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:s=a/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,a=this.camera.fov.y/180/2,n=e-s,o=t-a,l=e+s,c=t-a,u=e+s,d=t+a,h=e-s,f=t+a;return[n,o,l,c,u,d,h,f]}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 xm=(i,e)=>new r.Observable(t=>{if(!window.IntersectionObserver)return;const s=()=>{var l;return!!(!((l=window.documentPictureInPicture)===null||l===void 0)&&l.window)||!!document.pictureInPictureElement},a={root:null},n=new IntersectionObserver((l,c)=>{l.forEach(u=>t.next(u.isIntersecting||s()))},{...a,...e});n.observe(i);const o=r.fromEvent(document,"visibilitychange").pipe(r.map(l=>!document.hidden||s())).subscribe(l=>t.next(l));return()=>{n.unobserve(i),o.unsubscribe}});class ro{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(z.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.elementVisible$=new r.ValueSubject(!0),this.textTracksManager=new Ge,this.droppedFramesManager=new zn,this.videoTracks$=new r.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new $f,this.textTracks=[],this.syncPlayback=()=>{var t,s,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(c.state===x.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==z.STOPPED&&o!==exports.PlaybackState.STOPPED){const d=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(c.position-d,c.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==z.STOPPED&&(this.videoState.startTransitionTo(z.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(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case z.STOPPED:this.videoState.startTransitionTo(z.READY),this.prepare();return;case z.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),(a=this.liveOffset)===null||a===void 0||a.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.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()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}}},this.init3DScene=t=>{var s,a,n;if(this.scene3D)return;this.scene3D=new _m(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:((a=t.projectionData)===null||a===void 0?void 0:a.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.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 o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.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(Pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Cm({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=lt(this.video),a=this.constructor.name,n=l=>{e.error$.next({id:a,category:r.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:n,connect:(l,c)=>this.subscription.add(l.subscribe(c,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:a,connect:n}=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(r.map(u=>u.map(({track:d})=>d)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(Wt(this.video,t.isLooped,a)),this.subscription.add(ot(this.video,t.volume,s.volumeState$,a)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,a)),n(Ff(this.video),this.elementSize$),n(xm(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(s.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var d;if(u===ue.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();r.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((S,y)=>y.bitrate-S.bitrate),b=Array.from(f.video).sort((S,y)=>y.bitrate-S.bitrate),m=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const S of p){const y=vm(S);y&&this.audioTracks.push({track:y,representation:S})}for(const S of b){const y=mm(S);if(y){h.push({track:y,representation:S});const T=!this.params.tuning.isAudioDisabled&&bm(p,b,S);T&&this.audioRepresentations.set(S.id,T)}}this.videoTracks$.next(h);for(const S of m){const y=Sm(S);y&&this.textTracks.push({track:y,representation:S})}this.params.output.availableVideoTracks$.next(h.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();r.assertNonNullable(v),this.player.initRepresentations(v.id,(d=this.audioRepresentations.get(v.id))===null||d===void 0?void 0:d.id,this.params.sourceHls)}else u===ue.REPRESENTATIOS_READY&&(this.videoState.setState(z.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),d=this.player.state$.getTransition();if(u!==ue.RUNNING||d||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();f&&this.params.output.autoVideoTrackLimits$.next(f.to);const p=this.params.desiredState.autoVideoTrackSwitching.getState(),b=this.params.tuning.autoTrackSelection.backgroundVideoQualityLimit;if(h){let m=h.id;!this.elementVisible$.getValue()&&p&&(m=this.videoTracks$.getValue().map(S=>S.representation).sort((S,y)=>y.bitrate-S.bitrate).filter(S=>{const y=r.videoSizeToQuality(S),T=r.videoSizeToQuality(h);if(y&&T)return r.isLowerOrEqual(y,T)&&r.isLowerOrEqual(y,b)}).map(S=>S.id)[0]),this.player.switchRepresentation(te.VIDEO,m).catch(o);const v=this.audioRepresentations.get(h.id);v&&this.player.switchRepresentation(te.AUDIO,v.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var d;return u&&((d=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||d===void 0?void 0:d.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var d,h;if(u!=null&&u.is3dVideo&&(!((d=this.params.tuning.spherical)===null||d===void 0)&&d.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashProvider",message:`DashProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const c=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,s,a,n,o,l;const c=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,d=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=$t(this.video.buffered,this.video.currentTime*1e3),p=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!c&&(a=(s=this.audioRepresentations.get(d.id))===null||s===void 0?void 0:s.bitrate)!==null&&a!==void 0?a:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),v=Bi(this.videoTracks$.getValue().map(({track:y})=>y),{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:b,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=c?v!=null?v:d:d!=null?d:v;return S&&((l=this.videoTracks$.getValue().find(({track:y})=>y===S))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ut(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),nt(this.video)}}class Nm extends ro{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 Om extends ro{constructor(e){super(e),this.liveOffset=new ma}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(r.combine({interval:r.interval(Xs),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var n;if(this.videoState.getState()===z.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(a-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:a,liveAvailabilityStartTime:n})=>a&&n?a+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&s===z.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,a)})}}const Ee={};var M;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const Mt=(i,e)=>new r.Observable(t=>{const s=(a,n)=>t.next(n);return i.on(e,s),()=>i.off(e,s)});class Mm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(M.INITIALIZING),this.textTracksManager=new Ge,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==M.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===x.Requested&&this.seek(n.position),s){case exports.PlaybackState.STOPPED:switch(t){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(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(Pe(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),nt(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(a=>{e||(Ee.Hls=a.default,Ee.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(s),e=!0})}init(){r.assertNonNullable(Ee.Hls,"hls.js not loaded"),this.hls=new Ee.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){r.assertNonNullable(Ee.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=lt(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,s));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(Wt(this.video,e.isLooped,s)),this.subscription.add(ot(this.video,e.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Lt(this.video,e.playbackRate,a.playbackRateState$,s)),this.subscription.add(Mt(this.hls,Ee.Events.ERROR).subscribe(u=>{var d;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(d=u.err)===null||d===void 0?void 0:d.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},s)),n(Mt(this.hls,Ee.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((d,h)=>{var f,p;const b=h.name||h.height.toString(10),{width:m,height:v}=h,S=(p=Mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:r.videoSizeToQuality({width:m,height:v});if(!S)return d;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,T={id:b.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:m,height:v},fps:y};return this.trackLevels.set(b,{track:T,level:h}),d.push(T),d},[]))),t.availableVideoTracks$),n(Mt(this.hls,Ee.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const d=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI||"",b=h.lang,m="internal";d.push({id:f,url:p,language:b,type:m})}e.internalTextTracks.startTransitionTo(d)}}),n(Mt(this.hls,Ee.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>Pe(u))),t.hostname$),this.subscription.add(Le(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:s}));const o=u=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||d===void 0?void 0:d.track},l=Mt(this.hls,Ee.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,s),this.subscription.add(Le(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var d;if(r.isNullable(u))return;const h=(d=this.trackLevels.get(u.id))===null||d===void 0?void 0:d.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,b=this.hls.levels[p];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:s})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await ut(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.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(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const jr="X-Playback-Duration";var Hr=async i=>{var e;const t=await Ht(i),s=await t.text(),a=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return a?parseInt(a,10):t.headers.has(jr)?parseInt(t.headers.get(jr),10):void 0};const Bm=i=>{let e=null;if(i.QUALITY&&(e=Mi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(a=>parseInt(a,10));e=r.videoSizeToQuality({width:t,height:s})}return e!=null?e:null},Vm=(i,e)=>{var t,s;const a=i.split(`
46
+ `),n=[],o=[];for(let l=0;l<a.length;l++){const c=a[l],u=c.match(/^#EXT-X-STREAM-INF:(.+)/),d=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!d)){if(u){const h=ki(u[1].split(",").map(y=>y.split("="))),f=(t=h.QUALITY)!==null&&t!==void 0?t:`stream-${h.BANDWIDTH}`,p=Bm(h);let b;h.BANDWIDTH&&(b=parseInt(h.BANDWIDTH,10)/1e3||void 0),!b&&h["AVERAGE-BANDWIDTH"]&&(b=parseInt(h["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=h["FRAME-RATE"]?parseFloat(h["FRAME-RATE"]):void 0;let v;if(h.RESOLUTION){const[y,T]=h.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&T&&(v={width:y,height:T})}const S=new URL(a[++l],e).toString();p&&n.push({id:f,quality:p,url:S,bandwidth:b,size:v,fps:m})}if(d){const h=ki(d[1].split(",").map(m=>m.split("=")).map(([m,v])=>[m,v.replace(/^"|"$/g,"")])),f=(s=h.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),p=h.LANGUAGE,b=h.NAME;f&&p&&o.push({type:"internal",id:p,label:b,language:p,url:f,isAuto:!1})}}}if(!n.length)throw new Error("Empty manifest");return{qualityManifests:n,textTracks:o}},Fm=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let As=0;const ya=async(i,e=i,t)=>{const a=await(await Ht(i)).text();As+=1;try{const{qualityManifests:n,textTracks:o}=Vm(a,e);return{qualityManifests:n,textTracks:o}}catch(n){if(As<=t.manifestRetryMaxCount)return await Fm(r.getExponentialDelay(As-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),ya(i,e,t)}return{qualityManifests:[],textTracks:[]}};var H;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(H||(H={}));class Um{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new K(H.STOPPED),this.textTracksManager=new Ge,this.manifests$=new r.ValueSubject([]),this.liveOffset=new ma,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){a!==H.STOPPED&&(this.videoState.startTransitionTo(H.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(H.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(a===H.STOPPED){this.videoState.startTransitionTo(H.READY),this.prepare();return}if(l||c||u){const f=this.videoState.getState();this.videoState.setState(H.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===x.Requested){this.videoState.startTransitionTo(H.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case H.READY:n===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(H.PLAYING),this.playIfAllowed());return;case H.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(H.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case H.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(H.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 f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case H.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url},ya(ve(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:r.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.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(Pe(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,s,a;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(a=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=o.getState())===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:"master",d=this.manifests$.getValue();if(!d.length)return;const h=l?"master":u;return l&&!c&&o.startTransitionTo(this.masterManifest),d.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=lt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,s));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(ot(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(H.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(H.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===H.READY&&this.videoState.setState(H.READY),this.videoState.getState()===H.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(Pe(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from===H.CHANGING_MANIFEST&&this.videoState.setState(c.to),l&&l.state===x.Requested&&this.seek(l.position)},s)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,c,u;const d=(u=(c=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||c===void 0?void 0:c.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(d||void 0)},s)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:c})=>this.params.output.liveTime$.next(l+c*1e3),s)),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:c,quality:u,size:d,bandwidth:h,fps:f})=>({id:c,quality:u,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(r.isNullable(s))return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(s.url);if((a||n)&&s.id===this.masterManifest.id){const{max:u,min:d}=(t=(e=a==null?void 0:a.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[h,f]of[[u,"mq"],[d,"lq"]]){const p=String(parseFloat(h||""));f&&h&&o.searchParams.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?Z.DASH_CMAF_OFFSET_P:Z.OFFSET_P,c=ve(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",c),this.video.load(),Hr(c).then(u=>{var d;if(!r.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(d=this.params.source.maxSeekBackTime)!==null&&d!==void 0?d:this.maxSeekBackTime$.getValue();if(r.isNullable(h)||!isFinite(h))try{Ht(c).then(f=>f.text()).then(f=>{var p;const b=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(b){const m=new URL(b,c).toString();Hr(m).then(v=>{r.isNullable(v)||this.maxSeekBackTime$.next(v)})}})}catch(f){}}})}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(H.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(q||(q={}));class jm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(q.STOPPED),this.textTracksManager=new Ge,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=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(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(a===exports.PlaybackState.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(s===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o||l||c){const h=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),d.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&d.state===x.Requested&&this.seek(d.position),s){case q.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case q.CHANGING_MANIFEST:break;default:return r.assertNever(s)}},this.params=e,this.video=rt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:r.VideoQuality.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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),ya(ve(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:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,s,a;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(a=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(s=o.getState())===null||s===void 0?void 0:s.id)!==null&&a!==void 0?a:"master",d=this.manifests$.getValue();if(!d.length)return;const h=l?"master":u;return l&&!c&&o.startTransitionTo(this.masterManifest),d.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=lt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c));if(n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Wt(this.video,t.isLooped,s)),this.subscription.add(ot(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,a.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},s).add(a.loadedMetadata$.subscribe(()=>{var l;const c=this.params.desiredState.seekState.getState(),u=this.videoState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&r.isNonNullable(d.to)){const f=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const p=this.manifests$.getValue().find(b=>b.id===f);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Pe(p.url));const b=this.params.desiredState.playbackRate.getState(),m=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(b!==m){const v=this.params.output.element$.getValue();v&&(this.params.desiredState.playbackRate.setState(b),v.playbackRate=b)}}}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),u&&u.from===q.CHANGING_MANIFEST&&this.videoState.setState(u.to),c.state===x.Requested&&this.seek(c.position)},s))),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:c,quality:u,size:d,bandwidth:h,fps:f})=>({id:c,quality:u,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s)),!r.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(r.merge(r.fromEvent(l,"addtrack"),r.fromEvent(l,"removetrack"),r.fromEvent(l,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let c=0;c<l.length;c++)l[c].mode="hidden"},s))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),nt(this.video)}prepare(){var e,t;const s=this.selectManifest();if(r.isNullable(s))return;const a=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(s.url);if((a||n)&&s.id===this.masterManifest.id){const{max:l,min:c}=(t=(e=a==null?void 0:a.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,d]of[[l,"mq"],[c,"lq"]]){const h=String(parseFloat(u||""));d&&u&&o.searchParams.set(d,h)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));class Hm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(Q.STOPPED),this.trackUrls={},this.textTracksManager=new Ge,this.syncPlayback=()=>{var t,s,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.seekState.getState();if(u&&n!==Q.READY&&!d){this.handleQualityLimitTransition(u.to.max);return}if(n===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(d){const{currentTime:f}=this.video;this.prepare(),h.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:f*1e3,forcePrecise:!0}),d.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((a=(s=this.trackUrls[d.to.id])===null||s===void 0?void 0:s.track)===null||a===void 0?void 0:a.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===x.Requested&&this.seek(h.position),n){case Q.READY:o===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}},this.params=e,this.video=rt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},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=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=lt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,s));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(Wt(this.video,t.isLooped,s)),this.subscription.add(ot(this.video,t.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,a.playbackRateState$,s)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(a.canplay$.subscribe(()=>{var l,c;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Q.READY&&this.videoState.setState(Q.READY);const u=this.params.desiredState.videoTrack.getTransition();if(u&&r.isNonNullable(u.to)){this.params.desiredState.videoTrack.setState(u.to),this.params.output.currentVideoTrack$.next(this.trackUrls[u.to.id].track);const d=this.params.desiredState.playbackRate.getState(),h=(c=this.params.output.element$.getValue())===null||c===void 0?void 0:c.playbackRate;if(d!==h){const f=this.params.output.element$.getValue();f&&(this.params.desiredState.playbackRate.setState(d),f.playbackRate=d)}}this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),nt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;r.assertNonNullable(t,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[t];r.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Js(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(Pe(s))}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,a,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const c=(s=Object.values(this.trackUrls).find(h=>!r.isInvariantQuality(h.track.quality)&&r.isLowerOrEqual(h.track.quality,e)))===null||s===void 0?void 0:s.track,u=(a=this.params.desiredState.videoTrack.getState())===null||a===void 0?void 0:a.id,d=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(c&&d&&r.isHigherOrEqual(d.quality,c.quality)&&(o=c),!o){const h=Object.values(this.trackUrls).filter(p=>!r.isInvariantQuality(p.track.quality)&&r.isHigher(p.track.quality,e)),f=h.length;f&&(o=h[f-1].track)}o&&(l=o.quality)}else if(!e){const c=Object.values(this.trackUrls).map(u=>u.track);o=Bi(c,{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})}o&&(this.params.output.currentVideoTrack$.next(o),this.params.desiredState.videoTrack.startTransitionTo(o)),this.params.output.autoVideoTrackLimits$.next({max:l})}}const Gr=["stun:videostun.mycdn.me:80"],Gm=1e3,Ym=3,Ps=()=>null;class qm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ps,this.externalStopCallback=Ps,this.externalErrorCallback=Ps,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:Gr}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),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),Gm)}normalizeOptions(e={}){const t={stunServerList:Gr,maxRetryNumber:Ym,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var G;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(G||(G={}));class zm{constructor(e){this.videoState=new K(G.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED){t!==G.STOPPED&&(this.videoState.startTransitionTo(G.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(G.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case G.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=rt(e.container),this.liveStreamClient=new qm(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),nt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=lt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,s));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===G.READY&&this.videoState.setState(G.READY)},s)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED)},s)).add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING)},s)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ot(this.video,t.volume,a.volumeState$,s)).add(a.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case G.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case G.READY:break;case G.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case G.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},s)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(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(Pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:r.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(G.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Yr{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 Cs,Ds,Ls,Rs,di,Is,hi,_s,fi,xs,pi,Ns,mi,Os,vi,Ms;const no=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,He=document.createElement("video"),Wm='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Qm='video/mp4; codecs="hev1.1.6.L93.B0"',oo='video/webm; codecs="vp09.00.10.08"',lo='video/webm; codecs="av01.0.00M.08"',Km='audio/mp4; codecs="mp4a.40.2"',Jm='audio/webm; codecs="opus"',Xe={mms:ao(),mse:Am(),hls:!!(!((Cs=He.canPlayType)===null||Cs===void 0)&&Cs.call(He,"application/x-mpegurl")||!((Ds=He.canPlayType)===null||Ds===void 0)&&Ds.call(He,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},le={mp4:!!(!((Ls=He.canPlayType)===null||Ls===void 0)&&Ls.call(He,"video/mp4")),webm:!!(!((Rs=He.canPlayType)===null||Rs===void 0)&&Rs.call(He,"video/webm")),cmaf:!0},Ae={h264:!!(!((Is=(di=Je())===null||di===void 0?void 0:di.isTypeSupported)===null||Is===void 0)&&Is.call(di,Wm)),h265:!!(!((_s=(hi=Je())===null||hi===void 0?void 0:hi.isTypeSupported)===null||_s===void 0)&&_s.call(hi,Qm)),vp9:!!(!((xs=(fi=Je())===null||fi===void 0?void 0:fi.isTypeSupported)===null||xs===void 0)&&xs.call(fi,oo)),av1:!!(!((Ns=(pi=Je())===null||pi===void 0?void 0:pi.isTypeSupported)===null||Ns===void 0)&&Ns.call(pi,lo)),aac:!!(!((Os=(mi=Je())===null||mi===void 0?void 0:mi.isTypeSupported)===null||Os===void 0)&&Os.call(mi,Km)),opus:!!(!((Ms=(vi=Je())===null||vi===void 0?void 0:vi.isTypeSupported)===null||Ms===void 0)&&Ms.call(vi,Jm))},Bt=(Ae.h264||Ae.h265)&&Ae.aac;var je;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(je||(je={}));var _e;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(_e||(_e={}));let Ze;const Xm=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:lo}}),window.navigator.mediaCapabilities.decodingInfo({...i,video:{...i.video,contentType:oo}})]);Ze={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Xm()}catch(i){console.error(i)}const Gt=Xe.hls&&le.mp4,Zm=()=>Object.keys(Ae).filter(i=>Ae[i]),ev=(i,e=!1,t=!1)=>{const s=Xe.mse||Xe.mms&&t;return i.filter(a=>{switch(a){case exports.VideoFormat.DASH_SEP:return s&&le.mp4&&Bt;case exports.VideoFormat.DASH_WEBM:return s&&le.webm&&Ae.vp9&&Ae.opus;case exports.VideoFormat.DASH_WEBM_AV1:return s&&le.webm&&Ae.av1&&Ae.opus;case exports.VideoFormat.DASH_LIVE:return Xe.mse&&le.mp4&&Bt;case exports.VideoFormat.DASH_LIVE_CMAF:return s&&le.mp4&&Bt&&le.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return s&&le.mp4&&Bt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return Gt||e&&Xe.mse&&le.mp4&&Bt;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return Gt;case exports.VideoFormat.MPEG:return le.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Xe.webrtc&&Xe.ws&&Ae.h264&&(le.mp4||le.webm);default:return r.assertNever(a)}})},Vt=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case je.VP9:return[e,t];case je.AV1:return[t,e];case je.NONE:return[];case je.SMOOTH:return Ze?Ze[t].smooth?[t,e]:Ze[e].smooth?[e,t]:[t,e]:[e,t];case je.POWER_EFFICIENT:return Ze?Ze[t].powerEfficient?[t,e]:Ze[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(i)}return[e,t]},tv=({webmCodec:i,androidPreferredFormat:e})=>{if(no)switch(e){case _e.MPEG:return[exports.VideoFormat.MPEG,...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case _e.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case _e.DASH:return[...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return Gt?[...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...Vt(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},iv=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],a=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...s,...a],o=[...a,...s];let l;if(no)switch(i){case _e.DASH:{l=n;break}case _e.HLS:case _e.MPEG:{l=o;break}}else Gt?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},qr=i=>i?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var sv=i=>new r.Observable(e=>{const t=new r.Subscription,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:d})=>`${u}-${d}`)),a=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(r.map(({type:u})=>u!==void 0)),o=new r.Subject;let l=0,c="unknown";return t.add(s.subscribe(u=>{l&&window.clearTimeout(l),c=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),c="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(c),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const av={chunkDuration:5e3,maxParallelRequests:5};class rv{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=ev([...iv(this.params.tuning),...tv(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>r.isNonNullable(e.sources[l])),{forceFormat:s,formatsToAvoid:a}=this.params.tuning;let n=[];s?n=[s]:a.length?n=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Yr(n);const o=[...qr(!0),...qr(!1)];this.chromecastFormatsIterator=new Yr(o.filter(l=>r.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}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(),a=s.state!==x.None;if(this.params.desiredState.seekState.setState({state:x.Requested,position:a?s.position:t,forcePrecise:a?s.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case se.SCREEN:return this.createScreenProvider(t);case se.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:a}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]),c=this.applyFailoverHost(t[exports.VideoFormat.HLS_ONDEMAND]||t[exports.VideoFormat.HLS]);return r.assertNonNullable(l),new Nm({...o,source:l,sourceHls:c})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Om({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Gt||!this.params.tuning.useHlsJs?new jm({...o,source:l}):new Mm({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Um({...o,source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Hm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Bf({...o,source:l,config:{...av,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new zm({container:s,source:l,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new Xh({connection:l,meta:n,container:s,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?se.CHROMECAST:se.SCREEN}chooseFormat(e){switch(e){case se.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case se.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case se.SCREEN:return this.screenFormatsIterator.next();case se.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case se.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case se.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const s=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:s(e.url)}}return ki(Object.entries(e).map(([a,n])=>[a,s(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,s=0;return e.add(r.merge(this.providerOutput.error$,sv({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===se.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(se.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===r.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=s<this.params.tuning.providerErrorLimit;l&&(o&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(s++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:se.SCREEN)}})),e}}const nv=5e3,zr="one_video_throughput",Wr="one_video_rtt",xe=window.navigator.connection,Qr=()=>{const i=xe==null?void 0:xe.downlink;if(r.isNonNullable(i)&&i!==10)return i*1e3},Kr=()=>{const i=xe==null?void 0:xe.rtt;if(r.isNonNullable(i)&&i!==3e3)return i},Jr=(i,e,t)=>{const s=t*8,a=s/i;return s/(a+e)};class Ut{constructor(e){var t,s;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Ut.load(zr)||(e.useBrowserEstimation?Qr():void 0)||nv,n=(s=(t=Ut.load(Wr))!==null&&t!==void 0?t:e.useBrowserEstimation?Kr():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Jr(a,n,e.rttPenaltyRequestSize)),this.throughput=Zs.getSmoothedValue(a,-1,e),this.rtt=Zs.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const c=Qr();c&&this.throughput.next(c);const u=Kr();r.isNonNullable(u)&&this.rtt.next(u)};xe&&"onchange"in xe&&this.subscription.add(r.fromEvent(xe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{r.safeStorage.set(zr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{r.safeStorage.set(Wr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Jr(o,l,e.rttPenaltyRequestSize)),r.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,s=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),c=o-t,u=l-s;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let a=0,n=r.now(),o=0,l=r.now();const c=d=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=async({done:d,value:h})=>{if(d)!t&&this.addRawSpeed(a,r.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(r.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=h.byteLength;else{const p=l-n;p&&this.addRawSpeed(o,p,1,t),o=h.byteLength,n=r.now()}l=r.now()}else a+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&r.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,r.now()-l,this.concurrentDownloads.size),o=0,l=r.now());await(s==null?void 0:s.read().then(u,c))}};this.concurrentDownloads.add(e),s==null||s.read().then(u,c)}addRawSpeed(e,t,s=1,a=!1){if(Ut.sanityCheck(e,t,a)){const n=e*8/t;this.throughput.next(n*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const a=e*8/t;return!(!a||!isFinite(a)||a>1e6||a<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=r.safeStorage.get(e);if(r.isNonNullable(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Xr={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:r.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.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:je.VP9,androidPreferredFormat:_e.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}},ov=i=>{var e;return{...r.fillWithDefault(i,Xr),configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Xr.configName]}};var Zr=({seekState:i,position$:e})=>r.merge(i.stateChangeEnded$.pipe(r.map(({to:t})=>{var s;return t.state===x.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>i.getState().state===x.None))),lv=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return r.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const uv=(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(r.filter(a=>a.length>0),r.once()).subscribe(a=>{a.find(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class cv{constructor(e={configName:[]}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:x.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),internalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({}),cameraOrientation:new K({x:0,y:0})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:yf},this.initLogs(),this.tuning=ov(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Mo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ut(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,a)=>{const n=Reflect.get(t,s,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const c=o.map(h=>JSON.stringify(h,(f,p)=>{const b=typeof p;return["number","string","boolean"].includes(b)?p:p===null?null:`<${b}>`})),u=`Player.${String(s)}`,d=`Exception calling ${u} (${c.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:d,thrown:l}),l}}}})}initVideo(e){var t,s,a;return this.config=e,this.domContainer=lv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new rv({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=s&&!a&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:x.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(r.filter(s=>s.length>0),r.once()).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;r.assertNonNullable(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 uv(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 a=s.getCameraRotation(),n=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+n.x,y:a.y+n.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(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===x.None?void 0:t.position;return r.isNonNullable(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:a})=>s||a||0,0),height:e.reduce((s,{height:a})=>s||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===x.Requested?this.desiredState.seekState.setState({...o,state:x.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===x.Applying&&(this.desiredState.seekState.setState({state:x.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:l})=>l).sort((l,c)=>r.isInvariantQuality(l)?1:r.isInvariantQuality(c)?-1:r.isHigher(c,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const c of o)c.fps&&(l[c.quality]=c.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(r.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Zr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:l,isLowLatency:c})=>{const u=c?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(l)<u/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:l,duration:c})=>o&&(Math.abs(c)-Math.abs(l))*1e3<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(Zr({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o!=null?o:r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>s.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,s).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||s.getValue();return o&&!l}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,c;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(c=o==null?void 0:o.size)===null||c===void 0?void 0:c.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let d;u===exports.ChromecastState.CONNECTED?d=exports.Surface.SECOND_SCREEN:c?o?d=exports.Surface.PIP:l?d=exports.Surface.FULLSCREEN:d=exports.Surface.INLINE:d=exports.Surface.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((s,a)=>s.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(s=>s.length>0),r.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const a=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;a&&(s=e.find(({quality:n})=>n===a),s||this.setAutoQuality(!0)),s||(s=Bi(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(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),gf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Sf(s)),this.providerContainer.current$.subscribe(({type:s})=>ui("provider",s)),t.duration$.subscribe(s=>ui("duration",s)),t.availableVideoTracks$.pipe(r.filter(s=>!!s.length),r.once()).subscribe(s=>ui("tracks",s)),this.events.fatalError$.subscribe(new ke("fatalError")),this.events.managedError$.subscribe(new ke("managedError")),t.position$.subscribe(new ke("position")),t.currentVideoTrack$.pipe(r.map(s=>s==null?void 0:s.quality)).subscribe(new ke("quality")),this.info.currentBuffer$.subscribe(new ke("buffer")),t.isBuffering$.subscribe(new ke("isBuffering"))].forEach(s=>this.subscription.add(s)),ui("codecs",Zm())}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(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);a&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(a=>a.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const dv=`@vkontakte/videoplayer-core@${en}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=cv;exports.SDK_VERSION=dv;exports.VERSION=en;