@vkontakte/videoplayer-core 2.0.99 → 2.0.100
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +10 -10
- package/es2015.esm.js +10 -10
- package/es2018.cjs.js +10 -10
- package/es2018.esm.js +10 -10
- package/esnext.cjs.js +10 -10
- package/esnext.esm.js +11 -11
- package/evergreen.esm.js +11 -11
- package/package.json +1 -1
package/es2015.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.100
|
|
3
|
+
* Fri, 12 Apr 2024 14:49:51 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-100/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Bu=Object.create;var Ya=Object.defineProperty;var Vu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var Uu=Object.getPrototypeOf,ju=Object.prototype.hasOwnProperty;var Hu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fu(e))!ju.call(i,s)&&s!==t&&Ya(i,s,{get:()=>e[s],enumerable:!(r=Vu(e,s))||r.enumerable});return i};var Gu=(i,e,t)=>(t=i!=null?Bu(Uu(i)):{},Hu(e||!i||!i.__esModule?Ya(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js");const Bo="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 oe;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(oe||(oe={}));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 M;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(M||(M={}));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={}));function H(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(d){try{u(r.next(d))}catch(h){o(h)}}function c(d){try{u(r.throw(d))}catch(h){o(h)}}function u(d){d.done?n(d.value):s(d.value).then(l,c)}u((r=r.apply(i,e||[])).next())})}function C(i){return this instanceof C?(this.v=i,this):new C(i)}function de(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{c(r[f](p))}catch(v){h(n[0][3],v)}}function c(f){f.value instanceof C?Promise.resolve(f.value.v).then(u,d):h(n[0][2],f)}function u(f){l("next",f)}function d(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var Yu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class qu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Yu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(zu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const c=r.getCurrentSession();a.assertNonNullable(c);const u=c.getCastDevice(),d=(n=c.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.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(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const zu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var Lr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function nr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ge=function(i){try{return!!i()}catch(e){return!0}},Wu=ge,or=!Wu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Vo=or,Fo=Function.prototype,Rs=Fo.call,Qu=Vo&&Fo.bind.bind(Rs,Rs),ye=Vo?Qu:function(i){return function(){return Rs.apply(i,arguments)}},Uo=ye,Ku=Uo({}.toString),Ju=Uo("".slice),di=function(i){return Ju(Ku(i),8,-1)},Xu=ye,Zu=ge,ec=di,xr=Object,tc=Xu("".split),ic=Zu(function(){return!xr("z").propertyIsEnumerable(0)})?function(i){return ec(i)=="String"?tc(i,""):xr(i)}:xr,hi=function(i){return i==null},rc=hi,sc=TypeError,ra=function(i){if(rc(i))throw sc("Can't call method on "+i);return i},ac=ic,nc=ra,fi=function(i){return ac(nc(i))},Ht={},Pi=function(i){return i&&i.Math==Math&&i},ae=Pi(typeof globalThis=="object"&&globalThis)||Pi(typeof window=="object"&&window)||Pi(typeof self=="object"&&self)||Pi(typeof Lr=="object"&&Lr)||function(){return this}()||Lr||Function("return this")(),_s=typeof document=="object"&&document.all,oc=typeof _s=="undefined"&&_s!==void 0,jo={all:_s,IS_HTMLDDA:oc},Ho=jo,lc=Ho.all,te=Ho.IS_HTMLDDA?function(i){return typeof i=="function"||i===lc}:function(i){return typeof i=="function"},uc=ae,cc=te,qa=uc.WeakMap,dc=cc(qa)&&/native code/.test(String(qa)),za=te,Go=jo,hc=Go.all,Ge=Go.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:za(i)||i===hc}:function(i){return typeof i=="object"?i!==null:za(i)},fc=ge,Xe=!fc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ft={},pc=ae,Wa=Ge,Ds=pc.document,mc=Wa(Ds)&&Wa(Ds.createElement),sa=function(i){return mc?Ds.createElement(i):{}},vc=Xe,bc=ge,Sc=sa,Yo=!vc&&!bc(function(){return Object.defineProperty(Sc("div"),"a",{get:function(){return 7}}).a!=7}),gc=Xe,yc=ge,qo=gc&&yc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Tc=Ge,Ec=String,$c=TypeError,Ye=function(i){if(Tc(i))return i;throw $c(Ec(i)+" is not an object")},kc=or,Ai=Function.prototype.call,pe=kc?Ai.bind(Ai):function(){return Ai.apply(Ai,arguments)},aa={},Nr=aa,Or=ae,wc=te,Qa=function(i){return wc(i)?i:void 0},pt=function(i,e){return arguments.length<2?Qa(Nr[i])||Qa(Or[i]):Nr[i]&&Nr[i][e]||Or[i]&&Or[i][e]},Pc=ye,lr=Pc({}.isPrototypeOf),ur=typeof navigator!="undefined"&&String(navigator.userAgent)||"",zo=ae,Mr=ur,Ka=zo.process,Ja=zo.Deno,Xa=Ka&&Ka.versions||Ja&&Ja.version,Za=Xa&&Xa.v8,ke,Ji;Za&&(ke=Za.split("."),Ji=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Ji&&Mr&&(ke=Mr.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Mr.match(/Chrome\/(\d+)/),ke&&(Ji=+ke[1])));var Wo=Ji,en=Wo,Ac=ge,Cc=ae,Ic=Cc.String,Qo=!!Object.getOwnPropertySymbols&&!Ac(function(){var i=Symbol();return!Ic(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&en&&en<41}),Rc=Qo,Ko=Rc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",_c=pt,Dc=te,Lc=lr,xc=Ko,Nc=Object,Jo=xc?function(i){return typeof i=="symbol"}:function(i){var e=_c("Symbol");return Dc(e)&&Lc(e.prototype,Nc(i))},Oc=String,cr=function(i){try{return Oc(i)}catch(e){return"Object"}},Mc=te,Bc=cr,Vc=TypeError,mt=function(i){if(Mc(i))return i;throw Vc(Bc(i)+" is not a function")},Fc=mt,Uc=hi,dr=function(i,e){var t=i[e];return Uc(t)?void 0:Fc(t)},Br=pe,Vr=te,Fr=Ge,jc=TypeError,Hc=function(i,e){var t,r;if(e==="string"&&Vr(t=i.toString)&&!Fr(r=Br(t,i))||Vr(t=i.valueOf)&&!Fr(r=Br(t,i))||e!=="string"&&Vr(t=i.toString)&&!Fr(r=Br(t,i)))return r;throw jc("Can't convert object to primitive value")},Xo={exports:{}},Gc=!0,tn=ae,Yc=Object.defineProperty,qc=function(i,e){try{Yc(tn,i,{value:e,configurable:!0,writable:!0})}catch(t){tn[i]=e}return e},zc=ae,Wc=qc,rn="__core-js_shared__",Qc=zc[rn]||Wc(rn,{}),na=Qc,sn=na;(Xo.exports=function(i,e){return sn[i]||(sn[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 Zo=Xo.exports,Kc=ra,Jc=Object,hr=function(i){return Jc(Kc(i))},Xc=ye,Zc=hr,ed=Xc({}.hasOwnProperty),Oe=Object.hasOwn||function(e,t){return ed(Zc(e),t)},td=ye,id=0,rd=Math.random(),sd=td(1 .toString),el=function(i){return"Symbol("+(i===void 0?"":i)+")_"+sd(++id+rd,36)},ad=ae,nd=Zo,an=Oe,od=el,ld=Qo,ud=Ko,xt=ad.Symbol,Ur=nd("wks"),cd=ud?xt.for||xt:xt&&xt.withoutSetter||od,ue=function(i){return an(Ur,i)||(Ur[i]=ld&&an(xt,i)?xt[i]:cd("Symbol."+i)),Ur[i]},dd=pe,nn=Ge,on=Jo,hd=dr,fd=Hc,pd=ue,md=TypeError,vd=pd("toPrimitive"),bd=function(i,e){if(!nn(i)||on(i))return i;var t=hd(i,vd),r;if(t){if(e===void 0&&(e="default"),r=dd(t,i,e),!nn(r)||on(r))return r;throw md("Can't convert object to primitive value")}return e===void 0&&(e="number"),fd(i,e)},Sd=bd,gd=Jo,oa=function(i){var e=Sd(i,"string");return gd(e)?e:e+""},yd=Xe,Td=Yo,Ed=qo,Ci=Ye,ln=oa,$d=TypeError,jr=Object.defineProperty,kd=Object.getOwnPropertyDescriptor,Hr="enumerable",Gr="configurable",Yr="writable";ft.f=yd?Ed?function(e,t,r){if(Ci(e),t=ln(t),Ci(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Yr in r&&!r[Yr]){var s=kd(e,t);s&&s[Yr]&&(e[t]=r.value,r={configurable:Gr in r?r[Gr]:s[Gr],enumerable:Hr in r?r[Hr]:s[Hr],writable:!1})}return jr(e,t,r)}:jr:function(e,t,r){if(Ci(e),t=ln(t),Ci(r),Td)try{return jr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw $d("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var fr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},wd=Xe,Pd=ft,Ad=fr,pi=wd?function(i,e,t){return Pd.f(i,e,Ad(1,t))}:function(i,e,t){return i[e]=t,i},Cd=Zo,Id=el,un=Cd("keys"),la=function(i){return un[i]||(un[i]=Id(i))},ua={},Rd=dc,tl=ae,_d=Ge,Dd=pi,qr=Oe,zr=na,Ld=la,xd=ua,cn="Object already initialized",Ls=tl.TypeError,Nd=tl.WeakMap,Xi,oi,Zi,Od=function(i){return Zi(i)?oi(i):Xi(i,{})},Md=function(i){return function(e){var t;if(!_d(e)||(t=oi(e)).type!==i)throw Ls("Incompatible receiver, "+i+" required");return t}};if(Rd||zr.state){var Ie=zr.state||(zr.state=new Nd);Ie.get=Ie.get,Ie.has=Ie.has,Ie.set=Ie.set,Xi=function(i,e){if(Ie.has(i))throw Ls(cn);return e.facade=i,Ie.set(i,e),e},oi=function(i){return Ie.get(i)||{}},Zi=function(i){return Ie.has(i)}}else{var At=Ld("state");xd[At]=!0,Xi=function(i,e){if(qr(i,At))throw Ls(cn);return e.facade=i,Dd(i,At,e),e},oi=function(i){return qr(i,At)?i[At]:{}},Zi=function(i){return qr(i,At)}}var il={set:Xi,get:oi,has:Zi,enforce:Od,getterFor:Md},Bd=or,rl=Function.prototype,dn=rl.apply,hn=rl.call,sl=typeof Reflect=="object"&&Reflect.apply||(Bd?hn.bind(dn):function(){return hn.apply(dn,arguments)}),Vd=di,Fd=ye,al=function(i){if(Vd(i)==="Function")return Fd(i)},ca={},nl={},ol={}.propertyIsEnumerable,ll=Object.getOwnPropertyDescriptor,Ud=ll&&!ol.call({1:2},1);nl.f=Ud?function(e){var t=ll(this,e);return!!t&&t.enumerable}:ol;var jd=Xe,Hd=pe,Gd=nl,Yd=fr,qd=fi,zd=oa,Wd=Oe,Qd=Yo,fn=Object.getOwnPropertyDescriptor;ca.f=jd?fn:function(e,t){if(e=qd(e),t=zd(t),Qd)try{return fn(e,t)}catch(r){}if(Wd(e,t))return Yd(!Hd(Gd.f,e,t),e[t])};var Kd=ge,Jd=te,Xd=/#|\.prototype\./,mi=function(i,e){var t=eh[Zd(i)];return t==ih?!0:t==th?!1:Jd(e)?Kd(e):!!e},Zd=mi.normalize=function(i){return String(i).replace(Xd,".").toLowerCase()},eh=mi.data={},th=mi.NATIVE="N",ih=mi.POLYFILL="P",ul=mi,pn=al,rh=mt,sh=or,ah=pn(pn.bind),pr=function(i,e){return rh(i),e===void 0?i:sh?ah(i,e):function(){return i.apply(e,arguments)}},Ii=ae,nh=sl,oh=al,lh=te,uh=ca.f,ch=ul,Ct=aa,dh=pr,It=pi,mn=Oe,hh=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return nh(i,this,arguments)};return e.prototype=i.prototype,e},Pe=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?Ii:s?Ii[t]:(Ii[t]||{}).prototype,l=r?Ct:Ct[t]||It(Ct,t,{})[t],c=l.prototype,u,d,h,f,p,v,m,b,S;for(f in e)u=ch(r?f:t+(s?".":"#")+f,i.forced),d=!u&&o&&mn(o,f),v=l[f],d&&(i.dontCallGetSet?(S=uh(o,f),m=S&&S.value):m=o[f]),p=d&&m?m:e[f],!(d&&typeof v==typeof p)&&(i.bind&&d?b=dh(p,Ii):i.wrap&&d?b=hh(p):n&&lh(p)?b=oh(p):b=p,(i.sham||p&&p.sham||v&&v.sham)&&It(b,"sham",!0),It(l,f,b),n&&(h=t+"Prototype",mn(Ct,h)||It(Ct,h,{}),It(Ct[h],f,p),i.real&&c&&(u||!c[f])&&It(c,f,p)))},xs=Xe,fh=Oe,cl=Function.prototype,ph=xs&&Object.getOwnPropertyDescriptor,da=fh(cl,"name"),mh=da&&function(){}.name==="something",vh=da&&(!xs||xs&&ph(cl,"name").configurable),bh={EXISTS:da,PROPER:mh,CONFIGURABLE:vh},dl={},Sh=Math.ceil,gh=Math.floor,yh=Math.trunc||function(e){var t=+e;return(t>0?gh:Sh)(t)},Th=yh,ha=function(i){var e=+i;return e!==e||e===0?0:Th(e)},Eh=ha,$h=Math.max,kh=Math.min,wh=function(i,e){var t=Eh(i);return t<0?$h(t+e,0):kh(t,e)},Ph=ha,Ah=Math.min,Ch=function(i){return i>0?Ah(Ph(i),9007199254740991):0},Ih=Ch,fa=function(i){return Ih(i.length)},Rh=fi,_h=wh,Dh=fa,vn=function(i){return function(e,t,r){var s=Rh(e),n=Dh(s),o=_h(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Lh={includes:vn(!0),indexOf:vn(!1)},xh=ye,Wr=Oe,Nh=fi,Oh=Lh.indexOf,Mh=ua,bn=xh([].push),Bh=function(i,e){var t=Nh(i),r=0,s=[],n;for(n in t)!Wr(Mh,n)&&Wr(t,n)&&bn(s,n);for(;e.length>r;)Wr(t,n=e[r++])&&(~Oh(s,n)||bn(s,n));return s},hl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Vh=Bh,Fh=hl,Uh=Object.keys||function(e){return Vh(e,Fh)},jh=Xe,Hh=qo,Gh=ft,Yh=Ye,qh=fi,zh=Uh;dl.f=jh&&!Hh?Object.defineProperties:function(e,t){Yh(e);for(var r=qh(t),s=zh(t),n=s.length,o=0,l;n>o;)Gh.f(e,l=s[o++],r[l]);return e};var Wh=pt,fl=Wh("document","documentElement"),Qh=Ye,Kh=dl,Sn=hl,Jh=ua,Xh=fl,Zh=sa,ef=la,gn=">",yn="<",Ns="prototype",Os="script",pl=ef("IE_PROTO"),Qr=function(){},ml=function(i){return yn+Os+gn+i+yn+"/"+Os+gn},Tn=function(i){i.write(ml("")),i.close();var e=i.parentWindow.Object;return i=null,e},tf=function(){var i=Zh("iframe"),e="java"+Os+":",t;return i.style.display="none",Xh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(ml("document.F=Object")),t.close(),t.F},Ri,zi=function(){try{Ri=new ActiveXObject("htmlfile")}catch(e){}zi=typeof document!="undefined"?document.domain&&Ri?Tn(Ri):tf():Tn(Ri);for(var i=Sn.length;i--;)delete zi[Ns][Sn[i]];return zi()};Jh[pl]=!0;var vl=Object.create||function(e,t){var r;return e!==null?(Qr[Ns]=Qh(e),r=new Qr,Qr[Ns]=null,r[pl]=e):r=zi(),t===void 0?r:Kh.f(r,t)},rf=ge,sf=!rf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),af=Oe,nf=te,of=hr,lf=la,uf=sf,En=lf("IE_PROTO"),Ms=Object,cf=Ms.prototype,bl=uf?Ms.getPrototypeOf:function(i){var e=of(i);if(af(e,En))return e[En];var t=e.constructor;return nf(t)&&e instanceof t?t.prototype:e instanceof Ms?cf:null},df=pi,pa=function(i,e,t,r){return r&&r.enumerable?i[e]=t:df(i,e,t),i},hf=ge,ff=te,pf=Ge,mf=vl,$n=bl,vf=pa,bf=ue,Bs=bf("iterator"),Sl=!1,Ue,Kr,Jr;[].keys&&(Jr=[].keys(),"next"in Jr?(Kr=$n($n(Jr)),Kr!==Object.prototype&&(Ue=Kr)):Sl=!0);var Sf=!pf(Ue)||hf(function(){var i={};return Ue[Bs].call(i)!==i});Sf?Ue={}:Ue=mf(Ue);ff(Ue[Bs])||vf(Ue,Bs,function(){return this});var gl={IteratorPrototype:Ue,BUGGY_SAFARI_ITERATORS:Sl},gf=ue,yf=gf("toStringTag"),yl={};yl[yf]="z";var ma=String(yl)==="[object z]",Tf=ma,Ef=te,Wi=di,$f=ue,kf=$f("toStringTag"),wf=Object,Pf=Wi(function(){return arguments}())=="Arguments",Af=function(i,e){try{return i[e]}catch(t){}},vi=Tf?Wi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Af(e=wf(i),kf))=="string"?t:Pf?Wi(e):(r=Wi(e))=="Object"&&Ef(e.callee)?"Arguments":r},Cf=ma,If=vi,Rf=Cf?{}.toString:function(){return"[object "+If(this)+"]"},_f=ma,Df=ft.f,Lf=pi,xf=Oe,Nf=Rf,Of=ue,kn=Of("toStringTag"),va=function(i,e,t,r){if(i){var s=t?i:i.prototype;xf(s,kn)||Df(s,kn,{configurable:!0,value:e}),r&&!_f&&Lf(s,"toString",Nf)}},Mf=gl.IteratorPrototype,Bf=vl,Vf=fr,Ff=va,Uf=Ht,jf=function(){return this},Hf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=Bf(Mf,{next:Vf(+!r,t)}),Ff(i,s,!1,!0),Uf[s]=jf,i},Gf=Pe,Yf=pe,Tl=bh,qf=Hf,zf=bl,Wf=va,wn=pa,Qf=ue,Pn=Ht,El=gl,Kf=Tl.PROPER;Tl.CONFIGURABLE;El.IteratorPrototype;var _i=El.BUGGY_SAFARI_ITERATORS,Xr=Qf("iterator"),An="keys",Di="values",Cn="entries",Jf=function(){return this},Xf=function(i,e,t,r,s,n,o){qf(t,e,r);var l=function(S){if(S===s&&f)return f;if(!_i&&S in d)return d[S];switch(S){case An:return function(){return new t(this,S)};case Di:return function(){return new t(this,S)};case Cn:return function(){return new t(this,S)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,h=d[Xr]||d["@@iterator"]||s&&d[s],f=!_i&&h||l(s),p=e=="Array"&&d.entries||h,v,m,b;if(p&&(v=zf(p.call(new i)),v!==Object.prototype&&v.next&&(Wf(v,c,!0,!0),Pn[c]=Jf)),Kf&&s==Di&&h&&h.name!==Di&&(u=!0,f=function(){return Yf(h,this)}),s)if(m={values:l(Di),keys:n?f:l(An),entries:l(Cn)},o)for(b in m)(_i||u||!(b in d))&&wn(d,b,m[b]);else Gf({target:e,proto:!0,forced:_i||u},m);return o&&d[Xr]!==f&&wn(d,Xr,f,{name:s}),Pn[e]=f,m},Zf=function(i,e){return{value:i,done:e}},ep=fi,In=Ht,$l=il;ft.f;var tp=Xf,Li=Zf,kl="Array Iterator",ip=$l.set,rp=$l.getterFor(kl);tp(Array,"Array",function(i,e){ip(this,{type:kl,target:ep(i),index:0,kind:e})},function(){var i=rp(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Li(void 0,!0)):t=="keys"?Li(r,!1):t=="values"?Li(e[r],!1):Li([r,e[r]],!1)},"values");In.Arguments=In.Array;var sp=ue,ap=Ht,np=sp("iterator"),op=Array.prototype,lp=function(i){return i!==void 0&&(ap.Array===i||op[np]===i)},up=vi,Rn=dr,cp=hi,dp=Ht,hp=ue,fp=hp("iterator"),wl=function(i){if(!cp(i))return Rn(i,fp)||Rn(i,"@@iterator")||dp[up(i)]},pp=pe,mp=mt,vp=Ye,bp=cr,Sp=wl,gp=TypeError,yp=function(i,e){var t=arguments.length<2?Sp(i):e;if(mp(t))return vp(pp(t,i));throw gp(bp(i)+" is not iterable")},Tp=pe,_n=Ye,Ep=dr,$p=function(i,e,t){var r,s;_n(i);try{if(r=Ep(i,"return"),!r){if(e==="throw")throw t;return t}r=Tp(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return _n(r),t},kp=pr,wp=pe,Pp=Ye,Ap=cr,Cp=lp,Ip=fa,Dn=lr,Rp=yp,_p=wl,Ln=$p,Dp=TypeError,Qi=function(i,e){this.stopped=i,this.result=e},xn=Qi.prototype,ba=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),c=kp(e,r),u,d,h,f,p,v,m,b=function(y){return u&&Ln(u,"normal",y),new Qi(!0,y)},S=function(y){return s?(Pp(y),l?c(y[0],y[1],b):c(y[0],y[1])):l?c(y,b):c(y)};if(n)u=i.iterator;else if(o)u=i;else{if(d=_p(i),!d)throw Dp(Ap(i)+" is not iterable");if(Cp(d)){for(h=0,f=Ip(i);f>h;h++)if(p=S(i[h]),p&&Dn(xn,p))return p;return new Qi(!1)}u=Rp(i,d)}for(v=n?i.next:u.next;!(m=wp(v,u)).done;){try{p=S(m.value)}catch(y){Ln(u,"throw",y)}if(typeof p=="object"&&p&&Dn(xn,p))return p}return new Qi(!1)},Lp=oa,xp=ft,Np=fr,Op=function(i,e,t){var r=Lp(e);r in i?xp.f(i,r,Np(0,t)):i[r]=t},Mp=Pe,Bp=ba,Vp=Op;Mp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Bp(e,function(r,s){Vp(t,r,s)},{AS_ENTRIES:!0}),t}});var Fp=aa,Up=Fp.Object.fromEntries,jp={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},Hp=jp,Gp=ae,Yp=vi,qp=pi,Nn=Ht,zp=ue,On=zp("toStringTag");for(var Zr in Hp){var Mn=Gp[Zr],es=Mn&&Mn.prototype;es&&Yp(es)!==On&&qp(es,On,Zr),Nn[Zr]=Nn.Array}var Wp=Up,Qp=Wp,Kp=Qp,Jp=Kp,er=nr(Jp),Xp=di,mr=typeof process!="undefined"&&Xp(process)=="process",Zp=ft,em=function(i,e,t){return Zp.f(i,e,t)},tm=pt,im=em,rm=ue,sm=Xe,Bn=rm("species"),am=function(i){var e=tm(i);sm&&e&&!e[Bn]&&im(e,Bn,{configurable:!0,get:function(){return this}})},nm=lr,om=TypeError,lm=function(i,e){if(nm(e,i))return i;throw om("Incorrect invocation")},um=ye,cm=te,Vs=na,dm=um(Function.toString);cm(Vs.inspectSource)||(Vs.inspectSource=function(i){return dm(i)});var Pl=Vs.inspectSource,hm=ye,fm=ge,Al=te,pm=vi,mm=pt,vm=Pl,Cl=function(){},bm=[],Il=mm("Reflect","construct"),Sa=/^\s*(?:class|function)\b/,Sm=hm(Sa.exec),gm=!Sa.exec(Cl),Xt=function(e){if(!Al(e))return!1;try{return Il(Cl,bm,e),!0}catch(t){return!1}},Rl=function(e){if(!Al(e))return!1;switch(pm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gm||!!Sm(Sa,vm(e))}catch(t){return!0}};Rl.sham=!0;var ym=!Il||fm(function(){var i;return Xt(Xt.call)||!Xt(Object)||!Xt(function(){i=!0})||i})?Rl:Xt,Tm=ym,Em=cr,$m=TypeError,km=function(i){if(Tm(i))return i;throw $m(Em(i)+" is not a constructor")},Vn=Ye,wm=km,Pm=hi,Am=ue,Cm=Am("species"),_l=function(i,e){var t=Vn(i).constructor,r;return t===void 0||Pm(r=Vn(t)[Cm])?e:wm(r)},Im=ye,Rm=Im([].slice),_m=TypeError,Dm=function(i,e){if(i<e)throw _m("Not enough arguments");return i},Lm=ur,Dl=/(?:ipad|iphone|ipod).*applewebkit/i.test(Lm),fe=ae,xm=sl,Nm=pr,Fn=te,Om=Oe,Ll=ge,Un=fl,Mm=Rm,jn=sa,Bm=Dm,Vm=Dl,Fm=mr,Fs=fe.setImmediate,Us=fe.clearImmediate,Um=fe.process,ts=fe.Dispatch,jm=fe.Function,Hn=fe.MessageChannel,Hm=fe.String,is=0,si={},Gn="onreadystatechange",li,nt,rs,ss;Ll(function(){li=fe.location});var ga=function(i){if(Om(si,i)){var e=si[i];delete si[i],e()}},as=function(i){return function(){ga(i)}},Yn=function(i){ga(i.data)},qn=function(i){fe.postMessage(Hm(i),li.protocol+"//"+li.host)};(!Fs||!Us)&&(Fs=function(e){Bm(arguments.length,1);var t=Fn(e)?e:jm(e),r=Mm(arguments,1);return si[++is]=function(){xm(t,void 0,r)},nt(is),is},Us=function(e){delete si[e]},Fm?nt=function(i){Um.nextTick(as(i))}:ts&&ts.now?nt=function(i){ts.now(as(i))}:Hn&&!Vm?(rs=new Hn,ss=rs.port2,rs.port1.onmessage=Yn,nt=Nm(ss.postMessage,ss)):fe.addEventListener&&Fn(fe.postMessage)&&!fe.importScripts&&li&&li.protocol!=="file:"&&!Ll(qn)?(nt=qn,fe.addEventListener("message",Yn,!1)):Gn in jn("script")?nt=function(i){Un.appendChild(jn("script"))[Gn]=function(){Un.removeChild(this),ga(i)}}:nt=function(i){setTimeout(as(i),0)});var xl={set:Fs,clear:Us},Nl=function(){this.head=null,this.tail=null};Nl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Ol=Nl,Gm=ur,Ym=/ipad|iphone|ipod/i.test(Gm)&&typeof Pebble!="undefined",qm=ur,zm=/web0s(?!.*chrome)/i.test(qm),ht=ae,zn=pr,Wm=ca.f,ns=xl.set,Qm=Ol,Km=Dl,Jm=Ym,Xm=zm,os=mr,Wn=ht.MutationObserver||ht.WebKitMutationObserver,Qn=ht.document,Kn=ht.process,xi=ht.Promise,Jn=Wm(ht,"queueMicrotask"),js=Jn&&Jn.value,Rt,ls,us,Ni,Xn;if(!js){var Oi=new Qm,Mi=function(){var i,e;for(os&&(i=Kn.domain)&&i.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&Rt(),t}i&&i.enter()};!Km&&!os&&!Xm&&Wn&&Qn?(ls=!0,us=Qn.createTextNode(""),new Wn(Mi).observe(us,{characterData:!0}),Rt=function(){us.data=ls=!ls}):!Jm&&xi&&xi.resolve?(Ni=xi.resolve(void 0),Ni.constructor=xi,Xn=zn(Ni.then,Ni),Rt=function(){Xn(Mi)}):os?Rt=function(){Kn.nextTick(Mi)}:(ns=zn(ns,ht),Rt=function(){ns(Mi)}),js=function(i){Oi.head||Rt(),Oi.add(i)}}var Zm=js,ev=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},ya=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},tv=ae,Gt=tv.Promise,Ml=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",iv=Ml,rv=mr,sv=!iv&&!rv&&typeof window=="object"&&typeof document=="object",av=ae,ai=Gt,nv=te,ov=ul,lv=Pl,uv=ue,cv=sv,dv=Ml,cs=Wo,Zn=ai&&ai.prototype,hv=uv("species"),Hs=!1,Bl=nv(av.PromiseRejectionEvent),fv=ov("Promise",function(){var i=lv(ai),e=i!==String(ai);if(!e&&cs===66||!(Zn.catch&&Zn.finally))return!0;if(!cs||cs<51||!/native code/.test(i)){var t=new ai(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[hv]=r,Hs=t.then(function(){})instanceof r,!Hs)return!0}return!e&&(cv||dv)&&!Bl}),bi={CONSTRUCTOR:fv,REJECTION_EVENT:Bl,SUBCLASSING:Hs},Yt={},eo=mt,pv=TypeError,mv=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw pv("Bad Promise constructor");e=r,t=s}),this.resolve=eo(e),this.reject=eo(t)};Yt.f=function(i){return new mv(i)};var vv=Pe,tr=mr,Je=ae,Si=pe,bv=pa,Sv=va,gv=am,yv=mt,Gs=te,Tv=Ge,Ev=lm,$v=_l,Vl=xl.set,Ta=Zm,kv=ev,wv=ya,Pv=Ol,Fl=il,Ys=Gt,Ea=bi,Ul=Yt,vr="Promise",jl=Ea.CONSTRUCTOR,Av=Ea.REJECTION_EVENT;Ea.SUBCLASSING;var ds=Fl.getterFor(vr),Cv=Fl.set,Iv=Ys&&Ys.prototype,Nt=Ys,hs=Iv,Hl=Je.TypeError,qs=Je.document,$a=Je.process,zs=Ul.f,Rv=zs,_v=!!(qs&&qs.createEvent&&Je.dispatchEvent),Gl="unhandledrejection",Dv="rejectionhandled",to=0,Yl=1,Lv=2,ka=1,ql=2,Bi,io,xv,zl=function(i){var e;return Tv(i)&&Gs(e=i.then)?e:!1},Wl=function(i,e){var t=e.value,r=e.state==Yl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,c,u,d;try{s?(r||(e.rejection===ql&&Ov(e),e.rejection=ka),s===!0?c=t:(l&&l.enter(),c=s(t),l&&(l.exit(),d=!0)),c===i.promise?o(Hl("Promise-chain cycle")):(u=zl(c))?Si(u,c,n,o):n(c)):o(t)}catch(h){l&&!d&&l.exit(),o(h)}},Ql=function(i,e){i.notified||(i.notified=!0,Ta(function(){for(var t=i.reactions,r;r=t.get();)Wl(r,i);i.notified=!1,e&&!i.rejection&&Nv(i)}))},Kl=function(i,e,t){var r,s;_v?(r=qs.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Je.dispatchEvent(r)):r={promise:e,reason:t},!Av&&(s=Je["on"+i])?s(r):i===Gl&&kv("Unhandled promise rejection",t)},Nv=function(i){Si(Vl,Je,function(){var e=i.facade,t=i.value,r=ro(i),s;if(r&&(s=wv(function(){tr?$a.emit("unhandledRejection",t,e):Kl(Gl,e,t)}),i.rejection=tr||ro(i)?ql:ka,s.error))throw s.value})},ro=function(i){return i.rejection!==ka&&!i.parent},Ov=function(i){Si(Vl,Je,function(){var e=i.facade;tr?$a.emit("rejectionHandled",e):Kl(Dv,e,i.value)})},Ot=function(i,e,t){return function(r){i(e,r,t)}},Vt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Lv,Ql(i,!0))},Ws=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Hl("Promise can't be resolved itself");var r=zl(e);r?Ta(function(){var s={done:!1};try{Si(r,e,Ot(Ws,s,i),Ot(Vt,s,i))}catch(n){Vt(s,n,i)}}):(i.value=e,i.state=Yl,Ql(i,!1))}catch(s){Vt({done:!1},s,i)}}};jl&&(Nt=function(e){Ev(this,hs),yv(e),Si(Bi,this);var t=ds(this);try{e(Ot(Ws,t),Ot(Vt,t))}catch(r){Vt(t,r)}},hs=Nt.prototype,Bi=function(e){Cv(this,{type:vr,done:!1,notified:!1,parent:!1,reactions:new Pv,rejection:!1,state:to,value:void 0})},Bi.prototype=bv(hs,"then",function(e,t){var r=ds(this),s=zs($v(this,Nt));return r.parent=!0,s.ok=Gs(e)?e:!0,s.fail=Gs(t)&&t,s.domain=tr?$a.domain:void 0,r.state==to?r.reactions.add(s):Ta(function(){Wl(s,r)}),s.promise}),io=function(){var i=new Bi,e=ds(i);this.promise=i,this.resolve=Ot(Ws,e),this.reject=Ot(Vt,e)},Ul.f=zs=function(i){return i===Nt||i===xv?new io(i):Rv(i)});vv({global:!0,constructor:!0,wrap:!0,forced:jl},{Promise:Nt});Sv(Nt,vr,!1,!0);gv(vr);var Mv=ue,Jl=Mv("iterator"),Xl=!1;try{var Bv=0,so={next:function(){return{done:!!Bv++}},return:function(){Xl=!0}};so[Jl]=function(){return this},Array.from(so,function(){throw 2})}catch(i){}var Vv=function(i,e){if(!e&&!Xl)return!1;var t=!1;try{var r={};r[Jl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},Fv=Gt,Uv=Vv,jv=bi.CONSTRUCTOR,Zl=jv||!Uv(function(i){Fv.all(i).then(void 0,function(){})}),Hv=Pe,Gv=pe,Yv=mt,qv=Yt,zv=ya,Wv=ba,Qv=Zl;Hv({target:"Promise",stat:!0,forced:Qv},{all:function(e){var t=this,r=qv.f(t),s=r.resolve,n=r.reject,o=zv(function(){var l=Yv(t.resolve),c=[],u=0,d=1;Wv(e,function(h){var f=u++,p=!1;d++,Gv(l,t,h).then(function(v){p||(p=!0,c[f]=v,--d||s(c))},n)}),--d||s(c)});return o.error&&n(o.value),r.promise}});var Kv=Pe,Jv=bi.CONSTRUCTOR,ao=Gt;ao&&ao.prototype;Kv({target:"Promise",proto:!0,forced:Jv,real:!0},{catch:function(i){return this.then(void 0,i)}});var Xv=Pe,Zv=pe,eb=mt,tb=Yt,ib=ya,rb=ba,sb=Zl;Xv({target:"Promise",stat:!0,forced:sb},{race:function(e){var t=this,r=tb.f(t),s=r.reject,n=ib(function(){var o=eb(t.resolve);rb(e,function(l){Zv(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var ab=Pe,nb=pe,ob=Yt,lb=bi.CONSTRUCTOR;ab({target:"Promise",stat:!0,forced:lb},{reject:function(e){var t=ob.f(this);return nb(t.reject,void 0,e),t.promise}});var ub=Ye,cb=Ge,db=Yt,eu=function(i,e){if(ub(i),cb(e)&&e.constructor===i)return e;var t=db.f(i),r=t.resolve;return r(e),t.promise},hb=Pe,fb=pt,pb=Gc,mb=Gt,vb=bi.CONSTRUCTOR,bb=eu,Sb=fb("Promise"),gb=!vb;hb({target:"Promise",stat:!0,forced:pb},{resolve:function(e){return bb(gb&&this===Sb?mb:this,e)}});var yb=Pe,Qs=Gt,Tb=ge,Eb=pt,$b=te,kb=_l,no=eu,wb=Qs&&Qs.prototype,Pb=!!Qs&&Tb(function(){wb.finally.call({then:function(){}},function(){})});yb({target:"Promise",proto:!0,real:!0,forced:Pb},{finally:function(i){var e=kb(this,Eb("Promise")),t=$b(i);return this.then(t?function(r){return no(e,i()).then(function(){return r})}:i,t?function(r){return no(e,i()).then(function(){throw r})}:i)}});var Ab=pt,wa=Ab,Cb=wa,Ib=Cb("Promise","finally"),Rb=Ib,_b=Rb,Db=_b,Lb=Db,Pa=nr(Lb),ie;(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"})(ie||(ie={}));var we=(i,e=0,t=ie.OFFSET_P)=>{switch(t){case ie.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ie.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case ie.DASH_CMAF_OFFSET_P:{const r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:a.assertNever(t)}return i};const oo=(i,e)=>{var t;switch(e){case ie.OFFSET_P:return NaN;case ie.PLAYBACK_SHIFT:{const r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case ie.DASH_CMAF_OFFSET_P:{const r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var A=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};class X{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const xb=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 a.assertNever(i)}};var _;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(_||(_={}));const Nb=5,Ob=5,Mb=500,lo=7e3;class Bb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new X(_.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==_.STOPPED&&(this.videoState.startTransitionTo(_.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===M.Requested&&r!==_.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case _.PLAYING:case _.PAUSED:case _.READY:break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case _.PLAYING:break;case _.PAUSED:this.videoState.startTransitionTo(_.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case _.READY:this.videoState.startTransitionTo(_.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case _.PLAYING:this.videoState.startTransitionTo(_.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case _.PAUSED:break;case _.READY:this.videoState.startTransitionTo(_.PAUSED),this.videoState.setState(_.PAUSED);break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(xb(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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(Mb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===M.Applying||Math.abs(l-n)>Nb)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),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<Ob&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(_.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(_.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:M.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===_.PAUSED||e===_.PLAYING)&&(this.videoState.setState(_.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===_.PLAYING||e===_.PAUSED)&&(this.videoState.setState(_.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===_.READY&&this.videoState.setState(_.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==_.STOPPED&&this.videoState.setState(_.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const d=r[e];a.assertNonNullable(d);const h=a.getHighestQuality(Object.keys(d));a.assertNonNullable(h);const f=d[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const d=r[e];a.assertNonNullable(d),s=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=r[e];a.assertNonNullable(d),s=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const d=r[e];a.assertNonNullable(d),s=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=r[e];a.assertNonNullable(d),s=we(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:a.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 a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:u}=this.params.meta;return a.isNonNullable(c)&&(l.metadata.title=c),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===M.Applying||r.state===M.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(lo).subscribe(()=>n(`timeout(${lo})`)))});Pa(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===M.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Aa=i=>{i.removeAttribute("src"),i.load()},Vb=i=>{try{i.pause(),i.playbackRate=0,Aa(i),i.remove()}catch(e){console.error(e)}};class Fb{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 Ks=window.WeakMap?new WeakMap:new Fb,vt=i=>{let e=i.querySelector("video");const t=!!e;return e?Aa(e):(e=document.createElement("video"),i.appendChild(e)),Ks.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=i=>{const e=Ks.get(i);Ks.delete(i),e?Aa(i):Vb(i)},Ve=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),c=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(d=>{const h=i.getState();r(d,h)&&i.setState(d)},n)),r(l,o)||(t(o),c&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},n)),u},gi=(i,e,t)=>Ve(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),St=(i,e,t,r)=>Ve(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),qt=(i,e,t,r)=>Ve(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Ub=i=>["__",i.language,i.label].join("|"),jb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Ze{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ve(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{a.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Ve(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ve(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ve(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var 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=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ze.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,r;const{language:s,label:n}=e,o=e.id?e.id:Ub(e),l=this.externalTracks.has(o),c=o.includes("auto");return l?{id:o,type:"external",isAuto:c,language:s,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:c,language:s,label:n,url:(r=this.internalTracks.get(o))===null||r===void 0?void 0:r.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:r,language:s,isAuto:n})=>!this.internalTracks.has(r)&&!t.some(([,o])=>o.language===s&&o.isAuto===n)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(s=>s.id===r)).forEach(([,r])=>this.detach(r))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!jb(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){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class Ca{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 tu=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},uo=i=>{const e=tu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Hb=i=>{const e=tu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Gb=3;var Yb=(i,e,t=Gb)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let c=n-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=n+1;c<i.length;c++)i.start(c)-t<=s&&(s=i.end(c))}}return{from:r,to:s}};const gt=i=>{const e=E=>a.fromEvent(i,E).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(E=>a.fromEvent(i,E))).pipe(a.map(E=>E.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Yb(i.buffered,i.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),c=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>!!(i.error||i.played.length)),a.map(()=>{var E;const T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.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=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;d.subscribe(E=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(E)&&p>=i.duration-f&&E<=f&&h.next(p),p=E});const v=a.fromEvent(i,"enterpictureinpicture"),m=a.fromEvent(i,"leavepictureinpicture"),b=new a.ValueSubject(Hb(i));v.subscribe(()=>b.next(!0)),m.subscribe(()=>b.next(!1));const S=new a.ValueSubject(uo(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>uo(i))).subscribe(S),{playing$:o,pause$:e("pause").pipe(a.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$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,playbackRateState$:c,inPiP$:b,inFullscreen$:S}};var br=i=>{switch(i){case"mobile":return a.VideoQuality.Q_144P;case"lowest":return a.VideoQuality.Q_240P;case"low":return a.VideoQuality.Q_360P;case"sd":case"medium":return a.VideoQuality.Q_480P;case"hd":case"high":return a.VideoQuality.Q_720P;case"fullhd":case"full":return a.VideoQuality.Q_1080P;case"quadhd":case"quad":return a.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return a.VideoQuality.Q_2160P}},qb=Pe,zb=hr,Wb=fa,Qb=ha;qb({target:"Array",proto:!0},{at:function(e){var t=zb(this),r=Wb(t),s=Qb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Kb=wa,Jb=Kb("Array","at"),Xb=Jb,Zb=Xb,eS=Zb,tS=eS,Be=nr(tS);let Ia=!1,Fe={};const iS=i=>{Ia=i},rS=()=>{Fe={}},sS=i=>{i(Fe)},Vi=(i,e)=>{var t;Ia&&(Fe.meta=(t=Fe.meta)!==null&&t!==void 0?t:{},Fe.meta[i]=e)};class De{constructor(e){this.name=e}next(e){var t,r;if(!Ia)return;Fe.series=(t=Fe.series)!==null&&t!==void 0?t:{};const s=(r=Fe.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Fe.series[this.name]=s}}var ct;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(ct||(ct={}));const aS=new De("best_bitrate"),nS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class oS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const lS='Assertion "ABR Tracks is empty array" failed',Sr=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:c,history:u,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var f,p,v,m,b;a.assertNotEmptyArray(i,lS);const S=r.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*r.containerSizeFactor,height:e.height*S*r.containerSizeFactor},E=y&&a.videoSizeToQuality(y),T=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,$=i.filter(R=>!a.isInvariantQuality(R.quality)).sort((R,w)=>a.isHigher(R.quality,w.quality)?-1:1),x=(p=Be($,-1))===null||p===void 0?void 0:p.quality,N=(v=Be($,0))===null||v===void 0?void 0:v.quality,F=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&a.isLower(s.max,s.min)||a.isNonNullable(s.min)&&N&&a.isHigher(s.min,N)||a.isNonNullable(s.max)&&x&&a.isLower(s.max,x),O=T*nS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),U={},I=$.filter(R=>(E?a.isLower(R.quality,E):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(R.bitrate)?t-n>=R.bitrate*O:!0)?r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&c&&!a.isInvariantQuality(c.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&a.isHigher(R.quality,c.quality)?(U[R.quality]=ct.Buffer,!1):!!d&&a.isHigherOrEqual(R.quality,d)?(U[R.quality]=ct.DroppedFramesLimit,!1):F||(a.isNullable(s.max)||a.isLowerOrEqual(R.quality,s.max))&&(a.isNullable(s.min)||a.isHigherOrEqual(R.quality,s.min))?!0:(U[R.quality]=ct.FitsQualityLimits,!1):(U[R.quality]=ct.FitsThroughput,!1):(U[R.quality]=ct.FitsContainer,!1))[0];I&&I.bitrate&&aS.next(I.bitrate);const P=(m=I!=null?I:$[Math.ceil(($.length-1)/2)])!==null&&m!==void 0?m:i[0];P.quality!==((b=u==null?void 0:u.last)===null||b===void 0?void 0:b.quality)&&h({message:`
|
|
6
|
+
"use strict";var Bu=Object.create;var Ya=Object.defineProperty;var Vu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var Uu=Object.getPrototypeOf,ju=Object.prototype.hasOwnProperty;var Hu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fu(e))!ju.call(i,s)&&s!==t&&Ya(i,s,{get:()=>e[s],enumerable:!(r=Vu(e,s))||r.enumerable});return i};var Gu=(i,e,t)=>(t=i!=null?Bu(Uu(i)):{},Hu(e||!i||!i.__esModule?Ya(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js");const Bo="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 oe;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(oe||(oe={}));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 N;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(N||(N={}));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={}));function H(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(d){try{u(r.next(d))}catch(h){o(h)}}function c(d){try{u(r.throw(d))}catch(h){o(h)}}function u(d){d.done?n(d.value):s(d.value).then(l,c)}u((r=r.apply(i,e||[])).next())})}function C(i){return this instanceof C?(this.v=i,this):new C(i)}function de(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(v,m){n.push([f,p,v,m])>1||l(f,p)})})}function l(f,p){try{c(r[f](p))}catch(v){h(n[0][3],v)}}function c(f){f.value instanceof C?Promise.resolve(f.value.v).then(u,d):h(n[0][2],f)}function u(f){l("next",f)}function d(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var Yu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class qu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Yu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(zu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const c=r.getCurrentSession();a.assertNonNullable(c);const u=c.getCastDevice(),d=(n=c.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.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(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const zu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var Lr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function nr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ge=function(i){try{return!!i()}catch(e){return!0}},Wu=ge,or=!Wu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Vo=or,Fo=Function.prototype,Rs=Fo.call,Qu=Vo&&Fo.bind.bind(Rs,Rs),ye=Vo?Qu:function(i){return function(){return Rs.apply(i,arguments)}},Uo=ye,Ku=Uo({}.toString),Ju=Uo("".slice),di=function(i){return Ju(Ku(i),8,-1)},Xu=ye,Zu=ge,ec=di,xr=Object,tc=Xu("".split),ic=Zu(function(){return!xr("z").propertyIsEnumerable(0)})?function(i){return ec(i)=="String"?tc(i,""):xr(i)}:xr,hi=function(i){return i==null},rc=hi,sc=TypeError,ra=function(i){if(rc(i))throw sc("Can't call method on "+i);return i},ac=ic,nc=ra,fi=function(i){return ac(nc(i))},Ht={},Pi=function(i){return i&&i.Math==Math&&i},ae=Pi(typeof globalThis=="object"&&globalThis)||Pi(typeof window=="object"&&window)||Pi(typeof self=="object"&&self)||Pi(typeof Lr=="object"&&Lr)||function(){return this}()||Lr||Function("return this")(),_s=typeof document=="object"&&document.all,oc=typeof _s=="undefined"&&_s!==void 0,jo={all:_s,IS_HTMLDDA:oc},Ho=jo,lc=Ho.all,te=Ho.IS_HTMLDDA?function(i){return typeof i=="function"||i===lc}:function(i){return typeof i=="function"},uc=ae,cc=te,qa=uc.WeakMap,dc=cc(qa)&&/native code/.test(String(qa)),za=te,Go=jo,hc=Go.all,Ge=Go.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:za(i)||i===hc}:function(i){return typeof i=="object"?i!==null:za(i)},fc=ge,Xe=!fc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ft={},pc=ae,Wa=Ge,Ds=pc.document,mc=Wa(Ds)&&Wa(Ds.createElement),sa=function(i){return mc?Ds.createElement(i):{}},vc=Xe,bc=ge,Sc=sa,Yo=!vc&&!bc(function(){return Object.defineProperty(Sc("div"),"a",{get:function(){return 7}}).a!=7}),gc=Xe,yc=ge,qo=gc&&yc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Tc=Ge,Ec=String,$c=TypeError,Ye=function(i){if(Tc(i))return i;throw $c(Ec(i)+" is not an object")},kc=or,Ai=Function.prototype.call,pe=kc?Ai.bind(Ai):function(){return Ai.apply(Ai,arguments)},aa={},Nr=aa,Or=ae,wc=te,Qa=function(i){return wc(i)?i:void 0},pt=function(i,e){return arguments.length<2?Qa(Nr[i])||Qa(Or[i]):Nr[i]&&Nr[i][e]||Or[i]&&Or[i][e]},Pc=ye,lr=Pc({}.isPrototypeOf),ur=typeof navigator!="undefined"&&String(navigator.userAgent)||"",zo=ae,Mr=ur,Ka=zo.process,Ja=zo.Deno,Xa=Ka&&Ka.versions||Ja&&Ja.version,Za=Xa&&Xa.v8,ke,Ji;Za&&(ke=Za.split("."),Ji=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Ji&&Mr&&(ke=Mr.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Mr.match(/Chrome\/(\d+)/),ke&&(Ji=+ke[1])));var Wo=Ji,en=Wo,Ac=ge,Cc=ae,Ic=Cc.String,Qo=!!Object.getOwnPropertySymbols&&!Ac(function(){var i=Symbol();return!Ic(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&en&&en<41}),Rc=Qo,Ko=Rc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",_c=pt,Dc=te,Lc=lr,xc=Ko,Nc=Object,Jo=xc?function(i){return typeof i=="symbol"}:function(i){var e=_c("Symbol");return Dc(e)&&Lc(e.prototype,Nc(i))},Oc=String,cr=function(i){try{return Oc(i)}catch(e){return"Object"}},Mc=te,Bc=cr,Vc=TypeError,mt=function(i){if(Mc(i))return i;throw Vc(Bc(i)+" is not a function")},Fc=mt,Uc=hi,dr=function(i,e){var t=i[e];return Uc(t)?void 0:Fc(t)},Br=pe,Vr=te,Fr=Ge,jc=TypeError,Hc=function(i,e){var t,r;if(e==="string"&&Vr(t=i.toString)&&!Fr(r=Br(t,i))||Vr(t=i.valueOf)&&!Fr(r=Br(t,i))||e!=="string"&&Vr(t=i.toString)&&!Fr(r=Br(t,i)))return r;throw jc("Can't convert object to primitive value")},Xo={exports:{}},Gc=!0,tn=ae,Yc=Object.defineProperty,qc=function(i,e){try{Yc(tn,i,{value:e,configurable:!0,writable:!0})}catch(t){tn[i]=e}return e},zc=ae,Wc=qc,rn="__core-js_shared__",Qc=zc[rn]||Wc(rn,{}),na=Qc,sn=na;(Xo.exports=function(i,e){return sn[i]||(sn[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 Zo=Xo.exports,Kc=ra,Jc=Object,hr=function(i){return Jc(Kc(i))},Xc=ye,Zc=hr,ed=Xc({}.hasOwnProperty),Oe=Object.hasOwn||function(e,t){return ed(Zc(e),t)},td=ye,id=0,rd=Math.random(),sd=td(1 .toString),el=function(i){return"Symbol("+(i===void 0?"":i)+")_"+sd(++id+rd,36)},ad=ae,nd=Zo,an=Oe,od=el,ld=Qo,ud=Ko,xt=ad.Symbol,Ur=nd("wks"),cd=ud?xt.for||xt:xt&&xt.withoutSetter||od,ue=function(i){return an(Ur,i)||(Ur[i]=ld&&an(xt,i)?xt[i]:cd("Symbol."+i)),Ur[i]},dd=pe,nn=Ge,on=Jo,hd=dr,fd=Hc,pd=ue,md=TypeError,vd=pd("toPrimitive"),bd=function(i,e){if(!nn(i)||on(i))return i;var t=hd(i,vd),r;if(t){if(e===void 0&&(e="default"),r=dd(t,i,e),!nn(r)||on(r))return r;throw md("Can't convert object to primitive value")}return e===void 0&&(e="number"),fd(i,e)},Sd=bd,gd=Jo,oa=function(i){var e=Sd(i,"string");return gd(e)?e:e+""},yd=Xe,Td=Yo,Ed=qo,Ci=Ye,ln=oa,$d=TypeError,jr=Object.defineProperty,kd=Object.getOwnPropertyDescriptor,Hr="enumerable",Gr="configurable",Yr="writable";ft.f=yd?Ed?function(e,t,r){if(Ci(e),t=ln(t),Ci(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Yr in r&&!r[Yr]){var s=kd(e,t);s&&s[Yr]&&(e[t]=r.value,r={configurable:Gr in r?r[Gr]:s[Gr],enumerable:Hr in r?r[Hr]:s[Hr],writable:!1})}return jr(e,t,r)}:jr:function(e,t,r){if(Ci(e),t=ln(t),Ci(r),Td)try{return jr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw $d("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var fr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},wd=Xe,Pd=ft,Ad=fr,pi=wd?function(i,e,t){return Pd.f(i,e,Ad(1,t))}:function(i,e,t){return i[e]=t,i},Cd=Zo,Id=el,un=Cd("keys"),la=function(i){return un[i]||(un[i]=Id(i))},ua={},Rd=dc,tl=ae,_d=Ge,Dd=pi,qr=Oe,zr=na,Ld=la,xd=ua,cn="Object already initialized",Ls=tl.TypeError,Nd=tl.WeakMap,Xi,oi,Zi,Od=function(i){return Zi(i)?oi(i):Xi(i,{})},Md=function(i){return function(e){var t;if(!_d(e)||(t=oi(e)).type!==i)throw Ls("Incompatible receiver, "+i+" required");return t}};if(Rd||zr.state){var Ie=zr.state||(zr.state=new Nd);Ie.get=Ie.get,Ie.has=Ie.has,Ie.set=Ie.set,Xi=function(i,e){if(Ie.has(i))throw Ls(cn);return e.facade=i,Ie.set(i,e),e},oi=function(i){return Ie.get(i)||{}},Zi=function(i){return Ie.has(i)}}else{var At=Ld("state");xd[At]=!0,Xi=function(i,e){if(qr(i,At))throw Ls(cn);return e.facade=i,Dd(i,At,e),e},oi=function(i){return qr(i,At)?i[At]:{}},Zi=function(i){return qr(i,At)}}var il={set:Xi,get:oi,has:Zi,enforce:Od,getterFor:Md},Bd=or,rl=Function.prototype,dn=rl.apply,hn=rl.call,sl=typeof Reflect=="object"&&Reflect.apply||(Bd?hn.bind(dn):function(){return hn.apply(dn,arguments)}),Vd=di,Fd=ye,al=function(i){if(Vd(i)==="Function")return Fd(i)},ca={},nl={},ol={}.propertyIsEnumerable,ll=Object.getOwnPropertyDescriptor,Ud=ll&&!ol.call({1:2},1);nl.f=Ud?function(e){var t=ll(this,e);return!!t&&t.enumerable}:ol;var jd=Xe,Hd=pe,Gd=nl,Yd=fr,qd=fi,zd=oa,Wd=Oe,Qd=Yo,fn=Object.getOwnPropertyDescriptor;ca.f=jd?fn:function(e,t){if(e=qd(e),t=zd(t),Qd)try{return fn(e,t)}catch(r){}if(Wd(e,t))return Yd(!Hd(Gd.f,e,t),e[t])};var Kd=ge,Jd=te,Xd=/#|\.prototype\./,mi=function(i,e){var t=eh[Zd(i)];return t==ih?!0:t==th?!1:Jd(e)?Kd(e):!!e},Zd=mi.normalize=function(i){return String(i).replace(Xd,".").toLowerCase()},eh=mi.data={},th=mi.NATIVE="N",ih=mi.POLYFILL="P",ul=mi,pn=al,rh=mt,sh=or,ah=pn(pn.bind),pr=function(i,e){return rh(i),e===void 0?i:sh?ah(i,e):function(){return i.apply(e,arguments)}},Ii=ae,nh=sl,oh=al,lh=te,uh=ca.f,ch=ul,Ct=aa,dh=pr,It=pi,mn=Oe,hh=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return nh(i,this,arguments)};return e.prototype=i.prototype,e},Pe=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?Ii:s?Ii[t]:(Ii[t]||{}).prototype,l=r?Ct:Ct[t]||It(Ct,t,{})[t],c=l.prototype,u,d,h,f,p,v,m,b,S;for(f in e)u=ch(r?f:t+(s?".":"#")+f,i.forced),d=!u&&o&&mn(o,f),v=l[f],d&&(i.dontCallGetSet?(S=uh(o,f),m=S&&S.value):m=o[f]),p=d&&m?m:e[f],!(d&&typeof v==typeof p)&&(i.bind&&d?b=dh(p,Ii):i.wrap&&d?b=hh(p):n&&lh(p)?b=oh(p):b=p,(i.sham||p&&p.sham||v&&v.sham)&&It(b,"sham",!0),It(l,f,b),n&&(h=t+"Prototype",mn(Ct,h)||It(Ct,h,{}),It(Ct[h],f,p),i.real&&c&&(u||!c[f])&&It(c,f,p)))},xs=Xe,fh=Oe,cl=Function.prototype,ph=xs&&Object.getOwnPropertyDescriptor,da=fh(cl,"name"),mh=da&&function(){}.name==="something",vh=da&&(!xs||xs&&ph(cl,"name").configurable),bh={EXISTS:da,PROPER:mh,CONFIGURABLE:vh},dl={},Sh=Math.ceil,gh=Math.floor,yh=Math.trunc||function(e){var t=+e;return(t>0?gh:Sh)(t)},Th=yh,ha=function(i){var e=+i;return e!==e||e===0?0:Th(e)},Eh=ha,$h=Math.max,kh=Math.min,wh=function(i,e){var t=Eh(i);return t<0?$h(t+e,0):kh(t,e)},Ph=ha,Ah=Math.min,Ch=function(i){return i>0?Ah(Ph(i),9007199254740991):0},Ih=Ch,fa=function(i){return Ih(i.length)},Rh=fi,_h=wh,Dh=fa,vn=function(i){return function(e,t,r){var s=Rh(e),n=Dh(s),o=_h(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Lh={includes:vn(!0),indexOf:vn(!1)},xh=ye,Wr=Oe,Nh=fi,Oh=Lh.indexOf,Mh=ua,bn=xh([].push),Bh=function(i,e){var t=Nh(i),r=0,s=[],n;for(n in t)!Wr(Mh,n)&&Wr(t,n)&&bn(s,n);for(;e.length>r;)Wr(t,n=e[r++])&&(~Oh(s,n)||bn(s,n));return s},hl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Vh=Bh,Fh=hl,Uh=Object.keys||function(e){return Vh(e,Fh)},jh=Xe,Hh=qo,Gh=ft,Yh=Ye,qh=fi,zh=Uh;dl.f=jh&&!Hh?Object.defineProperties:function(e,t){Yh(e);for(var r=qh(t),s=zh(t),n=s.length,o=0,l;n>o;)Gh.f(e,l=s[o++],r[l]);return e};var Wh=pt,fl=Wh("document","documentElement"),Qh=Ye,Kh=dl,Sn=hl,Jh=ua,Xh=fl,Zh=sa,ef=la,gn=">",yn="<",Ns="prototype",Os="script",pl=ef("IE_PROTO"),Qr=function(){},ml=function(i){return yn+Os+gn+i+yn+"/"+Os+gn},Tn=function(i){i.write(ml("")),i.close();var e=i.parentWindow.Object;return i=null,e},tf=function(){var i=Zh("iframe"),e="java"+Os+":",t;return i.style.display="none",Xh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(ml("document.F=Object")),t.close(),t.F},Ri,zi=function(){try{Ri=new ActiveXObject("htmlfile")}catch(e){}zi=typeof document!="undefined"?document.domain&&Ri?Tn(Ri):tf():Tn(Ri);for(var i=Sn.length;i--;)delete zi[Ns][Sn[i]];return zi()};Jh[pl]=!0;var vl=Object.create||function(e,t){var r;return e!==null?(Qr[Ns]=Qh(e),r=new Qr,Qr[Ns]=null,r[pl]=e):r=zi(),t===void 0?r:Kh.f(r,t)},rf=ge,sf=!rf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),af=Oe,nf=te,of=hr,lf=la,uf=sf,En=lf("IE_PROTO"),Ms=Object,cf=Ms.prototype,bl=uf?Ms.getPrototypeOf:function(i){var e=of(i);if(af(e,En))return e[En];var t=e.constructor;return nf(t)&&e instanceof t?t.prototype:e instanceof Ms?cf:null},df=pi,pa=function(i,e,t,r){return r&&r.enumerable?i[e]=t:df(i,e,t),i},hf=ge,ff=te,pf=Ge,mf=vl,$n=bl,vf=pa,bf=ue,Bs=bf("iterator"),Sl=!1,Ue,Kr,Jr;[].keys&&(Jr=[].keys(),"next"in Jr?(Kr=$n($n(Jr)),Kr!==Object.prototype&&(Ue=Kr)):Sl=!0);var Sf=!pf(Ue)||hf(function(){var i={};return Ue[Bs].call(i)!==i});Sf?Ue={}:Ue=mf(Ue);ff(Ue[Bs])||vf(Ue,Bs,function(){return this});var gl={IteratorPrototype:Ue,BUGGY_SAFARI_ITERATORS:Sl},gf=ue,yf=gf("toStringTag"),yl={};yl[yf]="z";var ma=String(yl)==="[object z]",Tf=ma,Ef=te,Wi=di,$f=ue,kf=$f("toStringTag"),wf=Object,Pf=Wi(function(){return arguments}())=="Arguments",Af=function(i,e){try{return i[e]}catch(t){}},vi=Tf?Wi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Af(e=wf(i),kf))=="string"?t:Pf?Wi(e):(r=Wi(e))=="Object"&&Ef(e.callee)?"Arguments":r},Cf=ma,If=vi,Rf=Cf?{}.toString:function(){return"[object "+If(this)+"]"},_f=ma,Df=ft.f,Lf=pi,xf=Oe,Nf=Rf,Of=ue,kn=Of("toStringTag"),va=function(i,e,t,r){if(i){var s=t?i:i.prototype;xf(s,kn)||Df(s,kn,{configurable:!0,value:e}),r&&!_f&&Lf(s,"toString",Nf)}},Mf=gl.IteratorPrototype,Bf=vl,Vf=fr,Ff=va,Uf=Ht,jf=function(){return this},Hf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=Bf(Mf,{next:Vf(+!r,t)}),Ff(i,s,!1,!0),Uf[s]=jf,i},Gf=Pe,Yf=pe,Tl=bh,qf=Hf,zf=bl,Wf=va,wn=pa,Qf=ue,Pn=Ht,El=gl,Kf=Tl.PROPER;Tl.CONFIGURABLE;El.IteratorPrototype;var _i=El.BUGGY_SAFARI_ITERATORS,Xr=Qf("iterator"),An="keys",Di="values",Cn="entries",Jf=function(){return this},Xf=function(i,e,t,r,s,n,o){qf(t,e,r);var l=function(S){if(S===s&&f)return f;if(!_i&&S in d)return d[S];switch(S){case An:return function(){return new t(this,S)};case Di:return function(){return new t(this,S)};case Cn:return function(){return new t(this,S)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,h=d[Xr]||d["@@iterator"]||s&&d[s],f=!_i&&h||l(s),p=e=="Array"&&d.entries||h,v,m,b;if(p&&(v=zf(p.call(new i)),v!==Object.prototype&&v.next&&(Wf(v,c,!0,!0),Pn[c]=Jf)),Kf&&s==Di&&h&&h.name!==Di&&(u=!0,f=function(){return Yf(h,this)}),s)if(m={values:l(Di),keys:n?f:l(An),entries:l(Cn)},o)for(b in m)(_i||u||!(b in d))&&wn(d,b,m[b]);else Gf({target:e,proto:!0,forced:_i||u},m);return o&&d[Xr]!==f&&wn(d,Xr,f,{name:s}),Pn[e]=f,m},Zf=function(i,e){return{value:i,done:e}},ep=fi,In=Ht,$l=il;ft.f;var tp=Xf,Li=Zf,kl="Array Iterator",ip=$l.set,rp=$l.getterFor(kl);tp(Array,"Array",function(i,e){ip(this,{type:kl,target:ep(i),index:0,kind:e})},function(){var i=rp(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Li(void 0,!0)):t=="keys"?Li(r,!1):t=="values"?Li(e[r],!1):Li([r,e[r]],!1)},"values");In.Arguments=In.Array;var sp=ue,ap=Ht,np=sp("iterator"),op=Array.prototype,lp=function(i){return i!==void 0&&(ap.Array===i||op[np]===i)},up=vi,Rn=dr,cp=hi,dp=Ht,hp=ue,fp=hp("iterator"),wl=function(i){if(!cp(i))return Rn(i,fp)||Rn(i,"@@iterator")||dp[up(i)]},pp=pe,mp=mt,vp=Ye,bp=cr,Sp=wl,gp=TypeError,yp=function(i,e){var t=arguments.length<2?Sp(i):e;if(mp(t))return vp(pp(t,i));throw gp(bp(i)+" is not iterable")},Tp=pe,_n=Ye,Ep=dr,$p=function(i,e,t){var r,s;_n(i);try{if(r=Ep(i,"return"),!r){if(e==="throw")throw t;return t}r=Tp(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return _n(r),t},kp=pr,wp=pe,Pp=Ye,Ap=cr,Cp=lp,Ip=fa,Dn=lr,Rp=yp,_p=wl,Ln=$p,Dp=TypeError,Qi=function(i,e){this.stopped=i,this.result=e},xn=Qi.prototype,ba=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),c=kp(e,r),u,d,h,f,p,v,m,b=function(y){return u&&Ln(u,"normal",y),new Qi(!0,y)},S=function(y){return s?(Pp(y),l?c(y[0],y[1],b):c(y[0],y[1])):l?c(y,b):c(y)};if(n)u=i.iterator;else if(o)u=i;else{if(d=_p(i),!d)throw Dp(Ap(i)+" is not iterable");if(Cp(d)){for(h=0,f=Ip(i);f>h;h++)if(p=S(i[h]),p&&Dn(xn,p))return p;return new Qi(!1)}u=Rp(i,d)}for(v=n?i.next:u.next;!(m=wp(v,u)).done;){try{p=S(m.value)}catch(y){Ln(u,"throw",y)}if(typeof p=="object"&&p&&Dn(xn,p))return p}return new Qi(!1)},Lp=oa,xp=ft,Np=fr,Op=function(i,e,t){var r=Lp(e);r in i?xp.f(i,r,Np(0,t)):i[r]=t},Mp=Pe,Bp=ba,Vp=Op;Mp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Bp(e,function(r,s){Vp(t,r,s)},{AS_ENTRIES:!0}),t}});var Fp=aa,Up=Fp.Object.fromEntries,jp={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},Hp=jp,Gp=ae,Yp=vi,qp=pi,Nn=Ht,zp=ue,On=zp("toStringTag");for(var Zr in Hp){var Mn=Gp[Zr],es=Mn&&Mn.prototype;es&&Yp(es)!==On&&qp(es,On,Zr),Nn[Zr]=Nn.Array}var Wp=Up,Qp=Wp,Kp=Qp,Jp=Kp,er=nr(Jp),Xp=di,mr=typeof process!="undefined"&&Xp(process)=="process",Zp=ft,em=function(i,e,t){return Zp.f(i,e,t)},tm=pt,im=em,rm=ue,sm=Xe,Bn=rm("species"),am=function(i){var e=tm(i);sm&&e&&!e[Bn]&&im(e,Bn,{configurable:!0,get:function(){return this}})},nm=lr,om=TypeError,lm=function(i,e){if(nm(e,i))return i;throw om("Incorrect invocation")},um=ye,cm=te,Vs=na,dm=um(Function.toString);cm(Vs.inspectSource)||(Vs.inspectSource=function(i){return dm(i)});var Pl=Vs.inspectSource,hm=ye,fm=ge,Al=te,pm=vi,mm=pt,vm=Pl,Cl=function(){},bm=[],Il=mm("Reflect","construct"),Sa=/^\s*(?:class|function)\b/,Sm=hm(Sa.exec),gm=!Sa.exec(Cl),Xt=function(e){if(!Al(e))return!1;try{return Il(Cl,bm,e),!0}catch(t){return!1}},Rl=function(e){if(!Al(e))return!1;switch(pm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gm||!!Sm(Sa,vm(e))}catch(t){return!0}};Rl.sham=!0;var ym=!Il||fm(function(){var i;return Xt(Xt.call)||!Xt(Object)||!Xt(function(){i=!0})||i})?Rl:Xt,Tm=ym,Em=cr,$m=TypeError,km=function(i){if(Tm(i))return i;throw $m(Em(i)+" is not a constructor")},Vn=Ye,wm=km,Pm=hi,Am=ue,Cm=Am("species"),_l=function(i,e){var t=Vn(i).constructor,r;return t===void 0||Pm(r=Vn(t)[Cm])?e:wm(r)},Im=ye,Rm=Im([].slice),_m=TypeError,Dm=function(i,e){if(i<e)throw _m("Not enough arguments");return i},Lm=ur,Dl=/(?:ipad|iphone|ipod).*applewebkit/i.test(Lm),fe=ae,xm=sl,Nm=pr,Fn=te,Om=Oe,Ll=ge,Un=fl,Mm=Rm,jn=sa,Bm=Dm,Vm=Dl,Fm=mr,Fs=fe.setImmediate,Us=fe.clearImmediate,Um=fe.process,ts=fe.Dispatch,jm=fe.Function,Hn=fe.MessageChannel,Hm=fe.String,is=0,si={},Gn="onreadystatechange",li,nt,rs,ss;Ll(function(){li=fe.location});var ga=function(i){if(Om(si,i)){var e=si[i];delete si[i],e()}},as=function(i){return function(){ga(i)}},Yn=function(i){ga(i.data)},qn=function(i){fe.postMessage(Hm(i),li.protocol+"//"+li.host)};(!Fs||!Us)&&(Fs=function(e){Bm(arguments.length,1);var t=Fn(e)?e:jm(e),r=Mm(arguments,1);return si[++is]=function(){xm(t,void 0,r)},nt(is),is},Us=function(e){delete si[e]},Fm?nt=function(i){Um.nextTick(as(i))}:ts&&ts.now?nt=function(i){ts.now(as(i))}:Hn&&!Vm?(rs=new Hn,ss=rs.port2,rs.port1.onmessage=Yn,nt=Nm(ss.postMessage,ss)):fe.addEventListener&&Fn(fe.postMessage)&&!fe.importScripts&&li&&li.protocol!=="file:"&&!Ll(qn)?(nt=qn,fe.addEventListener("message",Yn,!1)):Gn in jn("script")?nt=function(i){Un.appendChild(jn("script"))[Gn]=function(){Un.removeChild(this),ga(i)}}:nt=function(i){setTimeout(as(i),0)});var xl={set:Fs,clear:Us},Nl=function(){this.head=null,this.tail=null};Nl.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Ol=Nl,Gm=ur,Ym=/ipad|iphone|ipod/i.test(Gm)&&typeof Pebble!="undefined",qm=ur,zm=/web0s(?!.*chrome)/i.test(qm),ht=ae,zn=pr,Wm=ca.f,ns=xl.set,Qm=Ol,Km=Dl,Jm=Ym,Xm=zm,os=mr,Wn=ht.MutationObserver||ht.WebKitMutationObserver,Qn=ht.document,Kn=ht.process,xi=ht.Promise,Jn=Wm(ht,"queueMicrotask"),js=Jn&&Jn.value,Rt,ls,us,Ni,Xn;if(!js){var Oi=new Qm,Mi=function(){var i,e;for(os&&(i=Kn.domain)&&i.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&Rt(),t}i&&i.enter()};!Km&&!os&&!Xm&&Wn&&Qn?(ls=!0,us=Qn.createTextNode(""),new Wn(Mi).observe(us,{characterData:!0}),Rt=function(){us.data=ls=!ls}):!Jm&&xi&&xi.resolve?(Ni=xi.resolve(void 0),Ni.constructor=xi,Xn=zn(Ni.then,Ni),Rt=function(){Xn(Mi)}):os?Rt=function(){Kn.nextTick(Mi)}:(ns=zn(ns,ht),Rt=function(){ns(Mi)}),js=function(i){Oi.head||Rt(),Oi.add(i)}}var Zm=js,ev=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},ya=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},tv=ae,Gt=tv.Promise,Ml=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",iv=Ml,rv=mr,sv=!iv&&!rv&&typeof window=="object"&&typeof document=="object",av=ae,ai=Gt,nv=te,ov=ul,lv=Pl,uv=ue,cv=sv,dv=Ml,cs=Wo,Zn=ai&&ai.prototype,hv=uv("species"),Hs=!1,Bl=nv(av.PromiseRejectionEvent),fv=ov("Promise",function(){var i=lv(ai),e=i!==String(ai);if(!e&&cs===66||!(Zn.catch&&Zn.finally))return!0;if(!cs||cs<51||!/native code/.test(i)){var t=new ai(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[hv]=r,Hs=t.then(function(){})instanceof r,!Hs)return!0}return!e&&(cv||dv)&&!Bl}),bi={CONSTRUCTOR:fv,REJECTION_EVENT:Bl,SUBCLASSING:Hs},Yt={},eo=mt,pv=TypeError,mv=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw pv("Bad Promise constructor");e=r,t=s}),this.resolve=eo(e),this.reject=eo(t)};Yt.f=function(i){return new mv(i)};var vv=Pe,tr=mr,Je=ae,Si=pe,bv=pa,Sv=va,gv=am,yv=mt,Gs=te,Tv=Ge,Ev=lm,$v=_l,Vl=xl.set,Ta=Zm,kv=ev,wv=ya,Pv=Ol,Fl=il,Ys=Gt,Ea=bi,Ul=Yt,vr="Promise",jl=Ea.CONSTRUCTOR,Av=Ea.REJECTION_EVENT;Ea.SUBCLASSING;var ds=Fl.getterFor(vr),Cv=Fl.set,Iv=Ys&&Ys.prototype,Nt=Ys,hs=Iv,Hl=Je.TypeError,qs=Je.document,$a=Je.process,zs=Ul.f,Rv=zs,_v=!!(qs&&qs.createEvent&&Je.dispatchEvent),Gl="unhandledrejection",Dv="rejectionhandled",to=0,Yl=1,Lv=2,ka=1,ql=2,Bi,io,xv,zl=function(i){var e;return Tv(i)&&Gs(e=i.then)?e:!1},Wl=function(i,e){var t=e.value,r=e.state==Yl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,c,u,d;try{s?(r||(e.rejection===ql&&Ov(e),e.rejection=ka),s===!0?c=t:(l&&l.enter(),c=s(t),l&&(l.exit(),d=!0)),c===i.promise?o(Hl("Promise-chain cycle")):(u=zl(c))?Si(u,c,n,o):n(c)):o(t)}catch(h){l&&!d&&l.exit(),o(h)}},Ql=function(i,e){i.notified||(i.notified=!0,Ta(function(){for(var t=i.reactions,r;r=t.get();)Wl(r,i);i.notified=!1,e&&!i.rejection&&Nv(i)}))},Kl=function(i,e,t){var r,s;_v?(r=qs.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Je.dispatchEvent(r)):r={promise:e,reason:t},!Av&&(s=Je["on"+i])?s(r):i===Gl&&kv("Unhandled promise rejection",t)},Nv=function(i){Si(Vl,Je,function(){var e=i.facade,t=i.value,r=ro(i),s;if(r&&(s=wv(function(){tr?$a.emit("unhandledRejection",t,e):Kl(Gl,e,t)}),i.rejection=tr||ro(i)?ql:ka,s.error))throw s.value})},ro=function(i){return i.rejection!==ka&&!i.parent},Ov=function(i){Si(Vl,Je,function(){var e=i.facade;tr?$a.emit("rejectionHandled",e):Kl(Dv,e,i.value)})},Ot=function(i,e,t){return function(r){i(e,r,t)}},Vt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Lv,Ql(i,!0))},Ws=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Hl("Promise can't be resolved itself");var r=zl(e);r?Ta(function(){var s={done:!1};try{Si(r,e,Ot(Ws,s,i),Ot(Vt,s,i))}catch(n){Vt(s,n,i)}}):(i.value=e,i.state=Yl,Ql(i,!1))}catch(s){Vt({done:!1},s,i)}}};jl&&(Nt=function(e){Ev(this,hs),yv(e),Si(Bi,this);var t=ds(this);try{e(Ot(Ws,t),Ot(Vt,t))}catch(r){Vt(t,r)}},hs=Nt.prototype,Bi=function(e){Cv(this,{type:vr,done:!1,notified:!1,parent:!1,reactions:new Pv,rejection:!1,state:to,value:void 0})},Bi.prototype=bv(hs,"then",function(e,t){var r=ds(this),s=zs($v(this,Nt));return r.parent=!0,s.ok=Gs(e)?e:!0,s.fail=Gs(t)&&t,s.domain=tr?$a.domain:void 0,r.state==to?r.reactions.add(s):Ta(function(){Wl(s,r)}),s.promise}),io=function(){var i=new Bi,e=ds(i);this.promise=i,this.resolve=Ot(Ws,e),this.reject=Ot(Vt,e)},Ul.f=zs=function(i){return i===Nt||i===xv?new io(i):Rv(i)});vv({global:!0,constructor:!0,wrap:!0,forced:jl},{Promise:Nt});Sv(Nt,vr,!1,!0);gv(vr);var Mv=ue,Jl=Mv("iterator"),Xl=!1;try{var Bv=0,so={next:function(){return{done:!!Bv++}},return:function(){Xl=!0}};so[Jl]=function(){return this},Array.from(so,function(){throw 2})}catch(i){}var Vv=function(i,e){if(!e&&!Xl)return!1;var t=!1;try{var r={};r[Jl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},Fv=Gt,Uv=Vv,jv=bi.CONSTRUCTOR,Zl=jv||!Uv(function(i){Fv.all(i).then(void 0,function(){})}),Hv=Pe,Gv=pe,Yv=mt,qv=Yt,zv=ya,Wv=ba,Qv=Zl;Hv({target:"Promise",stat:!0,forced:Qv},{all:function(e){var t=this,r=qv.f(t),s=r.resolve,n=r.reject,o=zv(function(){var l=Yv(t.resolve),c=[],u=0,d=1;Wv(e,function(h){var f=u++,p=!1;d++,Gv(l,t,h).then(function(v){p||(p=!0,c[f]=v,--d||s(c))},n)}),--d||s(c)});return o.error&&n(o.value),r.promise}});var Kv=Pe,Jv=bi.CONSTRUCTOR,ao=Gt;ao&&ao.prototype;Kv({target:"Promise",proto:!0,forced:Jv,real:!0},{catch:function(i){return this.then(void 0,i)}});var Xv=Pe,Zv=pe,eb=mt,tb=Yt,ib=ya,rb=ba,sb=Zl;Xv({target:"Promise",stat:!0,forced:sb},{race:function(e){var t=this,r=tb.f(t),s=r.reject,n=ib(function(){var o=eb(t.resolve);rb(e,function(l){Zv(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var ab=Pe,nb=pe,ob=Yt,lb=bi.CONSTRUCTOR;ab({target:"Promise",stat:!0,forced:lb},{reject:function(e){var t=ob.f(this);return nb(t.reject,void 0,e),t.promise}});var ub=Ye,cb=Ge,db=Yt,eu=function(i,e){if(ub(i),cb(e)&&e.constructor===i)return e;var t=db.f(i),r=t.resolve;return r(e),t.promise},hb=Pe,fb=pt,pb=Gc,mb=Gt,vb=bi.CONSTRUCTOR,bb=eu,Sb=fb("Promise"),gb=!vb;hb({target:"Promise",stat:!0,forced:pb},{resolve:function(e){return bb(gb&&this===Sb?mb:this,e)}});var yb=Pe,Qs=Gt,Tb=ge,Eb=pt,$b=te,kb=_l,no=eu,wb=Qs&&Qs.prototype,Pb=!!Qs&&Tb(function(){wb.finally.call({then:function(){}},function(){})});yb({target:"Promise",proto:!0,real:!0,forced:Pb},{finally:function(i){var e=kb(this,Eb("Promise")),t=$b(i);return this.then(t?function(r){return no(e,i()).then(function(){return r})}:i,t?function(r){return no(e,i()).then(function(){throw r})}:i)}});var Ab=pt,wa=Ab,Cb=wa,Ib=Cb("Promise","finally"),Rb=Ib,_b=Rb,Db=_b,Lb=Db,Pa=nr(Lb),ie;(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"})(ie||(ie={}));var we=(i,e=0,t=ie.OFFSET_P)=>{switch(t){case ie.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ie.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case ie.DASH_CMAF_OFFSET_P:{const r=new URL(i);return!r.searchParams.get("offset_p")&&e===0?i:(r.searchParams.set("offset_p",e.toFixed(0)),r.toString())}default:a.assertNever(t)}return i};const oo=(i,e)=>{var t;switch(e){case ie.OFFSET_P:return NaN;case ie.PLAYBACK_SHIFT:{const r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case ie.DASH_CMAF_OFFSET_P:{const r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var A=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};class X{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.prevState=r,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.prevState=r,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const xb=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 a.assertNever(i)}};var _;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(_||(_={}));const Nb=5,Ob=5,Mb=500,lo=7e3;class Bb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new X(_.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==_.STOPPED&&(this.videoState.startTransitionTo(_.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===N.Requested&&r!==_.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case _.PLAYING:case _.PAUSED:case _.READY:break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case _.PLAYING:break;case _.PAUSED:this.videoState.startTransitionTo(_.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case _.READY:this.videoState.startTransitionTo(_.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case _.PLAYING:this.videoState.startTransitionTo(_.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case _.PAUSED:break;case _.READY:this.videoState.startTransitionTo(_.PAUSED),this.videoState.setState(_.PAUSED);break;case _.STOPPED:this.videoState.startTransitionTo(_.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(xb(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 a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(Mb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===N.Applying||Math.abs(l-n)>Nb)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),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<Ob&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(_.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(_.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:N.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===_.PAUSED||e===_.PLAYING)&&(this.videoState.setState(_.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===_.PLAYING||e===_.PAUSED)&&(this.videoState.setState(_.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===_.READY&&this.videoState.setState(_.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==_.STOPPED&&this.videoState.setState(_.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const d=r[e];a.assertNonNullable(d);const h=a.getHighestQuality(Object.keys(d));a.assertNonNullable(h);const f=d[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const d=r[e];a.assertNonNullable(d),s=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=r[e];a.assertNonNullable(d),s=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const d=r[e];a.assertNonNullable(d),s=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=r[e];a.assertNonNullable(d),s=we(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:a.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 a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:u}=this.params.meta;return a.isNonNullable(c)&&(l.metadata.title=c),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===N.Applying||r.state===N.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(lo).subscribe(()=>n(`timeout(${lo})`)))});Pa(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}const Aa=i=>{i.removeAttribute("src"),i.load()},Vb=i=>{try{i.pause(),i.playbackRate=0,Aa(i),i.remove()}catch(e){console.error(e)}};class Fb{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 Ks=window.WeakMap?new WeakMap:new Fb,vt=i=>{let e=i.querySelector("video");const t=!!e;return e?Aa(e):(e=document.createElement("video"),i.appendChild(e)),Ks.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=i=>{const e=Ks.get(i);Ks.delete(i),e?Aa(i):Vb(i)},Ve=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),c=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(d=>{const h=i.getState();r(d,h)&&i.setState(d)},n)),r(l,o)||(t(o),c&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},n)),u},gi=(i,e,t)=>Ve(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),St=(i,e,t,r)=>Ve(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),qt=(i,e,t,r)=>Ve(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Ub=i=>["__",i.language,i.label].join("|"),jb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Ze{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Ve(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{a.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Ve(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Ve(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Ve(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var 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=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ze.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,r;const{language:s,label:n}=e,o=e.id?e.id:Ub(e),l=this.externalTracks.has(o),c=o.includes("auto");return l?{id:o,type:"external",isAuto:c,language:s,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:c,language:s,label:n,url:(r=this.internalTracks.get(o))===null||r===void 0?void 0:r.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(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:r,language:s,isAuto:n})=>!this.internalTracks.has(r)&&!t.some(([,o])=>o.language===s&&o.isAuto===n)).forEach(r=>this.attach(r)),Array.from(this.internalTracks).filter(([r])=>!e.find(s=>s.id===r)).forEach(([,r])=>this.detach(r))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!jb(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){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}class Ca{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 tu=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},uo=i=>{const e=tu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Hb=i=>{const e=tu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Gb=3;var Yb=(i,e,t=Gb)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let c=n-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=n+1;c<i.length;c++)i.start(c)-t<=s&&(s=i.end(c))}}return{from:r,to:s}};const gt=i=>{const e=T=>a.fromEvent(i,T).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(T=>a.fromEvent(i,T))).pipe(a.map(T=>T.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Yb(i.buffered,i.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),c=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>!!(i.error||i.played.length)),a.map(()=>{var T;const E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:a.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=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;d.subscribe(T=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(T)&&p>=i.duration-f&&T<=f&&h.next(p),p=T});const v=a.fromEvent(i,"enterpictureinpicture"),m=a.fromEvent(i,"leavepictureinpicture"),b=new a.ValueSubject(Hb(i));v.subscribe(()=>b.next(!0)),m.subscribe(()=>b.next(!1));const S=new a.ValueSubject(uo(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>uo(i))).subscribe(S),{playing$:o,pause$:e("pause").pipe(a.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$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,playbackRateState$:c,inPiP$:b,inFullscreen$:S}};var br=i=>{switch(i){case"mobile":return a.VideoQuality.Q_144P;case"lowest":return a.VideoQuality.Q_240P;case"low":return a.VideoQuality.Q_360P;case"sd":case"medium":return a.VideoQuality.Q_480P;case"hd":case"high":return a.VideoQuality.Q_720P;case"fullhd":case"full":return a.VideoQuality.Q_1080P;case"quadhd":case"quad":return a.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return a.VideoQuality.Q_2160P}},qb=Pe,zb=hr,Wb=fa,Qb=ha;qb({target:"Array",proto:!0},{at:function(e){var t=zb(this),r=Wb(t),s=Qb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Kb=wa,Jb=Kb("Array","at"),Xb=Jb,Zb=Xb,eS=Zb,tS=eS,Be=nr(tS);let Ia=!1,Fe={};const iS=i=>{Ia=i},rS=()=>{Fe={}},sS=i=>{i(Fe)},Vi=(i,e)=>{var t;Ia&&(Fe.meta=(t=Fe.meta)!==null&&t!==void 0?t:{},Fe.meta[i]=e)};class De{constructor(e){this.name=e}next(e){var t,r;if(!Ia)return;Fe.series=(t=Fe.series)!==null&&t!==void 0?t:{};const s=(r=Fe.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Fe.series[this.name]=s}}var ct;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(ct||(ct={}));const aS=new De("best_bitrate"),nS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class oS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const lS='Assertion "ABR Tracks is empty array" failed',Sr=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:c,history:u,droppedVideoMaxQualityLimit:d,abrLogger:h})=>{var f,p,v,m,b;a.assertNotEmptyArray(i,lS);const S=r.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*S*r.containerSizeFactor,height:e.height*S*r.containerSizeFactor},T=y&&a.videoSizeToQuality(y),E=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,$=i.filter(R=>!a.isInvariantQuality(R.quality)).sort((R,w)=>a.isHigher(R.quality,w.quality)?-1:1),O=(p=Be($,-1))===null||p===void 0?void 0:p.quality,M=(v=Be($,0))===null||v===void 0?void 0:v.quality,F=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&a.isLower(s.max,s.min)||a.isNonNullable(s.min)&&M&&a.isHigher(s.min,M)||a.isNonNullable(s.max)&&O&&a.isLower(s.max,O),x=E*nS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),U={},I=$.filter(R=>(T?a.isLower(R.quality,T):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(R.bitrate)?t-n>=R.bitrate*x:!0)?r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&c&&!a.isInvariantQuality(c.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&a.isHigher(R.quality,c.quality)?(U[R.quality]=ct.Buffer,!1):!!d&&a.isHigherOrEqual(R.quality,d)?(U[R.quality]=ct.DroppedFramesLimit,!1):F||(a.isNullable(s.max)||a.isLowerOrEqual(R.quality,s.max))&&(a.isNullable(s.min)||a.isHigherOrEqual(R.quality,s.min))?!0:(U[R.quality]=ct.FitsQualityLimits,!1):(U[R.quality]=ct.FitsThroughput,!1):(U[R.quality]=ct.FitsContainer,!1))[0];I&&I.bitrate&&aS.next(I.bitrate);const P=(m=I!=null?I:$[Math.ceil(($.length-1)/2)])!==null&&m!==void 0?m:i[0];P.quality!==((b=u==null?void 0:u.last)===null||b===void 0?void 0:b.quality)&&h({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${i.map(R=>`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -13,13 +13,13 @@
|
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${T},
|
|
17
17
|
throughput: ${t},
|
|
18
18
|
reserve: ${n},
|
|
19
19
|
playbackRate: ${l},
|
|
20
|
-
playbackRateFactor: ${
|
|
20
|
+
playbackRateFactor: ${E},
|
|
21
21
|
forwardBufferHealth: ${o},
|
|
22
|
-
bitrateFactor: ${
|
|
22
|
+
bitrateFactor: ${x},
|
|
23
23
|
minBufferToSwitchUp: ${r.minBufferToSwitchUp},
|
|
24
24
|
droppedVideoMaxQualityLimit: ${d},
|
|
25
25
|
limitsAreInvalid: ${F},
|
|
@@ -34,7 +34,7 @@
|
|
|
34
34
|
[selected track] ${P==null?void 0:P.quality}
|
|
35
35
|
`});const z=P&&u&&u.history[P.id]&&a.now()-u.history[P.id]<=r.trackCooldown&&(!u.last||P.id!==u.last.id);if(P!=null&&P.id&&u&&!z&&u.recordSelection(P),z&&(u!=null&&u.last)){const R=u.last;return u==null||u.recordSwitch(R),h({message:`
|
|
36
36
|
[last selected] ${R==null?void 0:R.quality}
|
|
37
|
-
`}),R}return u==null||u.recordSwitch(P),P};var Ne=i=>new URL(i).hostname;const co=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 yt=i=>H(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!co(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return co(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});function le(){return a.now()}function iu(i){return le()-i}function ho(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,c=!1)=>{s(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 uS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Ki(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,c=!1,u=0,d,h,f=!1,p="arraybuffer",v=7e3,m=2e3,b=()=>{if(c)return;a.assertNonNullable(d);const I=iu(d);let P;if(I<m){P=m-I,setTimeout(b,P);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,x()};const S=I=>(n=I,G),y=I=>(h=I,G),E=()=>(p="json",G),T=()=>{if(!c){if(--u>=0){b(),r&&r();return}c=!0,h&&h(),t&&t()}},$=I=>(f=I,G),x=()=>{d=le(),o=new s,o.open("get",i);let I=0,P,z=0;const R=()=>(a.assertNonNullable(d),Math.max(d,Math.max(P||0,z||0)));if(n&&o.addEventListener("progress",w=>{const j=le();n.updateChunk&&w.loaded>I&&(n.updateChunk(R(),w.loaded-I),I=w.loaded,P=j)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(c)return;a.assertNonNullable(o);const w=o.status;if(w>=200&&w<300){if(o.response.byteLength&&n){const j=o.response.byteLength-I;j&&n.updateChunk&&n.updateChunk(R(),j)}o.responseType==="json"&&!Object.values(o.response).length?T():(h&&h(),e(o.response))}else T()}),o.addEventListener("error",()=>{T()}),f){const w=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=le(),o.removeEventListener("readystatechange",w))};o.addEventListener("readystatechange",w)}return o.responseType=p,o.send(),G},G={withBitrateReporting:S,withParallel:$,withJSONResponse:E,withRetryCount:I=>(u=I,G),withRetryInterval:(I,P)=>(a.isNonNullable(I)&&(m=I),a.isNonNullable(P)&&(v=P),G),withTimeout:I=>(l=I,G),withFinally:y,send:x,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return G}const cS=100,dS=2e3,hS=500;let fS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-hS;if(t-e>dS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const c=n.bytes*o/l;s+=c,n.start=t,n.bytes-=c}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>cS&&(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 pS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=le(),s=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=le()-r,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=Ki(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_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=le();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Fi=1e4,fs=3,mS=6e4,vS=10,bS=1,SS=500;class gS{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 fS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ho(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ho(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{uS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new pS(fs,Fi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,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=Ki(this.urlResolver.resolve(T,!1),$,x,()=>this._retryCallback()).withTimeout(Fi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fs).withFinally(()=>{c=null}).send()},p=(T,$,x)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),$,x,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=T=>{const $=r.playbackRate;r.playbackRate!==T&&(t(`Playback rate switch: ${$}=>${T}`),r.playbackRate=T)},m=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const x=le()-1e4;let N=0;for(let O=0;O<this.bufferStates.length;O++){const U=this.bufferStates[O];T=Math.min(T,U.buf),U.ts<x&&N++}this.bufferStates.splice(0,N),t(`update playback rate; minBuffer=${T} drop=${N} jitter=${this.sourceJitter}`);let F=T-bS;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?v(1.15):F>1?v(1.1):F>.3?v(1.05):v(1)}},S=T=>{let $;const x=()=>$&&$.start?$.start.length:0,N=w=>$.start[w]/1e3,F=w=>$.dur[w]/1e3,O=w=>$.fragIndex+w,U=(w,j)=>({chunkIdx:O(w),startTS:N(w),dur:F(w),discontinuity:j}),G=()=>{let w=0;if($&&$.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=j;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let re=$.dur.length-1;for(;re>=0&&(Z-=$.dur[re],!(Z<=0));--re);w=Math.min(re,$.dur.length-1-K),w=Math.max(w,0)}return U(w,!0)},I=w=>{const j=x();if(!(j<=0)){if(a.isNonNullable(w)){for(let K=0;K<j;K++)if(N(K)>w)return U(K)}return G()}},P=w=>{const j=x(),K=w?w.chunkIdx+1:0,Z=K-$.fragIndex;if(!(j<=0)){if(!w||Z<0||Z-j>vS)return t(`Resync: offset=${Z} bChunks=${j} chunk=`+JSON.stringify(w)),G();if(!(Z>=j))return U(K-$.fragIndex,!1)}},z=(w,j,K)=>{u&&u.abort(),u=Ki(this.urlResolver.resolve(w,!0,this.lowLatency),j,K,()=>this._retryCallback()).withTimeout(Fi).withRetryCount(fs).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,j)=>{z(T,K=>{if(!h())return;$=K;const Z=!!$.lowLatency;Z!==this.lowLatency&&m(Z);let re=0;for(let Ae=0;Ae<$.dur.length;++Ae)re+=$.dur[Ae];re>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(re/$.dur.length)),s({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,w(I(j))},()=>this._handleNetworkError())},nextChunk:P}},y=()=>{n=!1,l&&l.abort(),c&&c.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:T=>{const{videoElement:$,logger:x}=this.params;let N=S(e.jidxUrl),F,O,U,G,I=0,P,z,R;const w=()=>{P&&(clearTimeout(P),P=void 0);const V=Math.max(SS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=I+V,ce=le(),he=Math.min(1e4,ne-ce);I=ce;const Et=()=>{u||h()&&N.seek(()=>{h()&&(I=le(),j(),w())})};he>0?P=window.setTimeout(()=>{this.paused?w():Et()},he):Et()},j=()=>{let V;for(;V=N.nextChunk(G);)G=V,zt(V);const ne=N.nextChunk(U);if(ne){if(U&&ne.discontinuity){x("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}Ae(ne)}else w()},K=(V,ne)=>{if(!h()||!this.sourceBuffer)return;let ce,he,Et;const Wt=Me=>{window.setTimeout(()=>{h()&&K(V,ne)},Me)};if(this.sourceBuffer.updating)x("Source buffer is updating; delaying appendBuffer"),Wt(100);else{const Me=le(),me=$.currentTime;!this.paused&&$.buffered.length>1&&z===me&&Me-R>500&&(x("Stall suspected; trying to fix"),this._fixupStall()),z!==me&&(z=me,R=Me);const $t=this._getBufferSizeSec();if($t>30)x(`Buffered ${$t} seconds; delaying appendBuffer`),Wt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:Me,buf:$t}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Qt){if(Qt.name==="QuotaExceededError")x("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(ce=this.sourceBuffer.buffered.start(0),he=me,he-ce>4&&this.sourceBuffer.remove(ce,he-3)),Wt(1e3);else throw Qt}}},Z=()=>{O&&F&&(x([`Appending chunk, sz=${O.byteLength}:`,JSON.stringify(U)]),K(O,function(){O=null,j()}))},re=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),Ae=V=>{h()&&p(re(V),(ne,ce)=>{if(h()){if(ce/=1e3,O=ne,U=V,o=V.startTS,ce){const he=Math.min(10,V.dur/ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}Z()}},()=>this._handleNetworkError())},zt=V=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(re(V),!1)))},Tt=V=>{h()&&(e.cachedHeader=V,K(V,()=>{F=!0,Z()}))};n=!0,N.seek(V=>{if(h()){if(I=le(),!V){w();return}G=V,!a.isNullable(T)||V.startTS>T?Ae(V):(U=V,j())}},T),e.cachedHeader?Tt(e.cachedHeader):f(e.headerUrl,Tt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),v=h/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const v=le();if(this.chunkRateEstimator.addInterval(f,v,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:b}),!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&&iu(o)<3e4)return;r(h)}c=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=le();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=Ki(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Fi).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;yt(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((c,u)=>{c.video&&s.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):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},mS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class ru{constructor(){this.onDroopedVideoFramesLimit$=new a.Subject,this.subscription=new a.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new a.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&&!a.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality(),s=t-this.prevTotalVideoFrames,n=r-this.prevDroppedVideoFrames,o=1-(s-n)/s;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&a.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,r)}}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(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),r=a.merge(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),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,r;const s=(r=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>a.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||r===void 0?void 0:r[0];return e!=null?e:s}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 L;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const yS=[L.PAUSED,L.PLAYING,L.READY],TS=[L.PAUSED,L.PLAYING,L.READY];class ES{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(L.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Ze,this.droppedFramesManager=new ru,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new Ca,this._dashCb=s=>{var n,o,l,c;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,d=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=br(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),v=h.bitrate/1e3,m=Object.assign({},h.video);if(!p)continue;const b={id:f,quality:p,bitrate:v,size:m};d.push({track:b,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)===L.MANIFEST_READY&&this.videoState.setState(L.MANIFEST_READY);break}case"qualitySwitch":{const u=s.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),a.isNonNullable(d)&&this.params.output.currentVideoTrack$.next(d);break}case"bandwidth":{const{size:u,duration:d}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,d);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration||0),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(c)};`}),o===exports.PlaybackState.STOPPED){s!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(L.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(TS.includes(s)&&(u||d)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&c.state===M.Requested&&yS.includes(s)){this.seek(c.position-this.liveOffset.getTotalPausedTime());return}switch(s){case L.STOPPED:this.videoState.startTransitionTo(L.MANIFEST_READY),this.dash.attachSource(we(this.params.source.url));return;case L.MANIFEST_READY:this.videoState.startTransitionTo(L.READY),this.prepare();break;case L.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(L.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(L.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(L.PAUSED)})}return;case L.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(L.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case L.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(L.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(L.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(we(this.params.source.url,h))}return;default:return a.assertNever(s)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=vt(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(Ne(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 r=gt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(a.map(s=>s.map(({track:n})=>n)))}),this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===L.READY&&this.videoState.setState(L.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===M.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(L.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(gi(this.video,this.params.desiredState.isLooped,t)).add(St(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(qt(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const n=s&&a.videoQualityToHeight(s);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case L.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case L.MANIFEST_READY:case L.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 L.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case L.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.observableFrom(["init"])).pipe(a.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),bt(this.video)}createLiveDashPlayer(){const e=new gS({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,r,s,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=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!u&&a.isNonNullable(c)?c:Sr(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,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(f||h!==p)&&this.setVideoTrack(d),v&&this.setAutoQuality(u),f||v||h!==p){const m=(o=l.find(({track:b})=>b.id===h))===null||o===void 0?void 0:o.representation;a.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e.id))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e.id}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===L.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(we(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}}var se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(se||(se={}));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 ir;(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"})(ir||(ir={}));var Se;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Se||(Se={}));var D;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(D||(D={}));var Ut;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ut||(Ut={}));var rr;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(rr||(rr={}));var Q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));var Mt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const $S=300,kS=(i,e=$S)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(a.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),a.isNonNullable(c)&&a.isNonNullable(u)&&t.next({width:c,height:u})},e));return n.observe(i),()=>n.disconnect()});class fo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class su extends fo{constructor(){super(),this.listeners||fo.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 au=class{constructor(){Object.defineProperty(this,"signal",{value:new su,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(au.prototype[Symbol.toStringTag]="AbortController",su.prototype[Symbol.toStringTag]="AbortSignal");function nu(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 wS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!nu({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,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,v)=>{d.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(c,u)])}return o(c,u)},Request:n}}const gr=nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ou=gr?wS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ui=gr?ou.fetch:window.fetch;gr?ou.Request:window.Request;const Ft=gr?au:window.AbortController;var Js=(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 PS=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},AS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",po=AS?PS:window.requestIdleCallback;var ps,ms;const CS=16;let lu=!1;try{lu=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((ms=(ps=navigator.userAgent.match(/Version\/(\d+)/))===null||ps===void 0?void 0:ps[1])!==null&&ms!==void 0?ms:"",10)<=CS}catch(i){console.error(i)}class IS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return H(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return H(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return H(this,void 0,void 0,function*(){return new Promise(t=>{let r;lu&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),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:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var mo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Te{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 s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}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 uu extends Te{}class RS extends Te{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const r=this.readString(4);this.compatibleBrands.push(r),t-=4}}}class _S extends Te{parseChildrenBoxes(){return et(this.content)}}class DS extends Te{parseChildrenBoxes(){return et(this.content)}}class LS extends Te{constructor(e){super(e),this.data=this.content}}class qe extends Te{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class xS extends qe{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 r=this.readUint32();const s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const l=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:c})}}}class NS extends Te{parseChildrenBoxes(){return et(this.content)}}class OS extends Te{parseChildrenBoxes(){return et(this.content)}}var dt;(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"})(dt||(dt={}));class MS extends qe{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=dt.MONOSCOPIC;break;case 1:this.stereoMode=dt.TOP_BOTTOM;break;case 2:this.stereoMode=dt.LEFT_RIGHT;break;case 3:this.stereoMode=dt.STEREO_CUSTOM;break;case 4:this.stereoMode=dt.RIGHT_LEFT;break}this.cursor+=1}}class BS extends qe{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class VS extends qe{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class FS extends Te{parseChildrenBoxes(){return et(this.content)}}class US extends qe{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 jS extends Te{parseChildrenBoxes(){return et(this.content)}}class HS extends Te{parseChildrenBoxes(){return et(this.content)}}class GS extends qe{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class YS extends Te{parseChildrenBoxes(){return et(this.content)}}class qS extends qe{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 zS extends qe{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 WS extends qe{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 QS={ftyp:RS,moov:_S,moof:DS,mdat:LS,sidx:xS,trak:NS,mdia:FS,mfhd:GS,tkhd:US,traf:YS,tfhd:qS,tfdt:zS,trun:WS,minf:jS,sv3d:OS,st3d:MS,prhd:BS,proj:HS,equi:VS,unknown:uu};class KS{createBox(e,t){const r=QS[e];return r?new r(t):new uu(t)}createFromView(e){const r=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return yr.createBox(r,new DataView(e.buffer,e.byteOffset))}}const yr=new KS;function ri(i,e){const t=new Uint8Array(i.buffer),r=e.split("").map(o=>o.charCodeAt(0));let s=i.byteOffset,n=[];for(;s<t.byteLength;){if(t[s]===r[n.length]?n.push(t[s]):n=[],n.length===4){const l=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+l>i.buffer.byteLength?null:yr.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function Xs(i,e){const t=[];let r=i.byteOffset;for(;r<i.buffer.byteLength;){const s=ri(new DataView(i.buffer,r,i.buffer.byteLength-r),e);if(s)t.push(s),r=s.source.byteOffset+s.size;else break}return t}function et(i){const e=[];let t=0;for(;t<i.byteLength;){const r=yr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(r),!r.size)break;t+=r.size}return e}const JS=new TextDecoder("ascii"),XS=i=>JS.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",ZS=i=>{const e=yr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,r=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:D.NONE,time:{from:t,to:t+o},byte:{from:r,to:r+n.referencedSize-1}};return t+=o,r+=n.referencedSize,l})},eg=i=>{const e=Xs(i,"mdat"),t=Xs(i,"moof");if(!(e.length&&t.length))return null;const r=t[0],s=e[e.length-1],n=r.source.byteOffset,l=s.source.byteOffset-r.source.byteOffset+s.size;return new DataView(i.buffer,n,l)},tg=(i,e)=>{const t=Xs(i,"traf"),r=t[t.length-1].children.find(c=>c.type==="tfhd"),s=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=r.defaultSampleDuration*n.sampleCount,(Number(s.baseMediaDecodeTime)+o)/e*1e3},ig=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:rr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ri(i,"sv3d")){e.is3dVideo=!0;const r=ri(i,"st3d");r&&(e.stereoMode=r.stereoMode);const s=ri(i,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=ri(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},rg={validateData:XS,parseInit:ig,getIndexRange:()=>{},parseSegments:ZS,parseFeedableSegmentChunk:eg,getSegmentEndTime:tg};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 vo={[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}},cu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=sr(i,t),s=r in vo,n=s?vo[r].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=sr(c),h=u*Math.pow(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:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},sr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Le=(i,e)=>{switch(e){case k.SignedInteger:return i.getInt8(0);case k.UnsignedInteger:return sr(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:a.assertNever(e)}},jt=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=cu(r);if(!e(s))return;s.type===k.Master&&jt(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},sg=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,r;const s=cu(i);return jt(s.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=Le(l,o):n===g.DocType?t=Le(l,o):n===g.DocTypeReadVersion&&(r=Le(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},du=[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],ag=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],ng=i=>{let e,t,r,s,n=!1,o=!1,l=!1,c,u,d=!1;const h=0;return jt(i,({tag:f,type:p,value:v,valueSize:m})=>{if(f===g.SeekID){const b=Le(v,p);u=sr(b)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=v.byteOffset,t=v.byteOffset+m):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?r=Le(v,p):f===g.Duration?s=Le(v,p):f===g.SeekPosition&&u===g.Cues?c=Le(v,p):f===g.Tracks?jt(v,({tag:b,type:S,value:y})=>b===g.ProjectionType?(d=Le(y,S)===1,!1):!0):n&&o&&du.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:h,projectionType:rr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},og=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lg=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return jt(i,({tag:l,type:c,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&s(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=Le(u,c));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=Le(u,c));break;default:t&&du.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,c)=>{const{time:u,position:d}=l,h=n[c+1];return{status:D.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}}})},ug=i=>{let e=0,t=!1;try{jt(i,r=>r.tag===g.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ag.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},cg={validateData:sg,parseInit:ng,getIndexRange:og,parseSegments:lg,parseFeedableSegmentChunk:ug};var dg=Ge,hg=di,fg=ue,pg=fg("match"),mg=function(i){var e;return dg(i)&&((e=i[pg])!==void 0?!!e:hg(i)=="RegExp")},vg=vi,bg=String,Sg=function(i){if(vg(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return bg(i)},gg=Ye,yg=function(){var i=gg(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},Tg=pe,Eg=Oe,$g=lr,kg=yg,bo=RegExp.prototype,wg=function(i){var e=i.flags;return e===void 0&&!("flags"in bo)&&!Eg(i,"flags")&&$g(bo,i)?Tg(kg,i):e},Ra=ye,Pg=hr,Ag=Math.floor,vs=Ra("".charAt),Cg=Ra("".replace),bs=Ra("".slice),Ig=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Rg=/\$([$&'`]|\d{1,2})/g,_g=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,c=Rg;return s!==void 0&&(s=Pg(s),c=Ig),Cg(n,c,function(u,d){var h;switch(vs(d,0)){case"$":return"$";case"&":return i;case"`":return bs(e,0,t);case"'":return bs(e,o);case"<":h=s[bs(d,1,-1)];break;default:var f=+d;if(f===0)return u;if(f>l){var p=Ag(f/10);return p===0?u:p<=l?r[p-1]===void 0?vs(d,1):r[p-1]+vs(d,1):u}h=r[f-1]}return h===void 0?"":h})},Dg=Pe,Lg=pe,_a=ye,So=ra,xg=te,Ng=hi,Og=mg,_t=Sg,Mg=dr,Bg=wg,Vg=_g,Fg=ue,Ug=Fg("replace"),jg=TypeError,hu=_a("".indexOf),Hg=_a("".replace),go=_a("".slice),Gg=Math.max,yo=function(i,e,t){return t>i.length?-1:e===""?t:hu(i,e,t)};Dg({target:"String",proto:!0},{replaceAll:function(e,t){var r=So(this),s,n,o,l,c,u,d,h,f,p=0,v=0,m="";if(!Ng(e)){if(s=Og(e),s&&(n=_t(So(Bg(e))),!~hu(n,"g")))throw jg("`.replaceAll` does not allow non-global regexes");if(o=Mg(e,Ug),o)return Lg(o,e,r,t);if(s)return Hg(_t(r),e,t)}for(l=_t(r),c=_t(e),u=xg(t),u||(t=_t(t)),d=c.length,h=Gg(1,d),p=yo(l,c,0);p!==-1;)f=u?_t(t(c,p,l)):Vg(c,l,p,[],void 0,t),m+=go(l,v,p)+f,v=p+d,p=yo(l,c,p+h);return v<l.length&&(m+=go(l,v)),m}});var Yg=wa,qg=Yg("String","replaceAll"),zg=qg,Wg=zg,Qg=Wg,Kg=Qg,To=nr(Kg);const Jg=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Eo=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const c=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(c)?0:c)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Lt=(i,e)=>{let t=i;t=To(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=To(t,o,(l,c)=>a.isNullable(n)?l:a.isNullable(c)?n:n.padStart(parseInt(c,10),"0"))}return t},Xg=(i,e)=>{var t,r,s,n,o,l,c,u,d,h,f,p,v,m,b,S,y,E,T,$,x,N,F,O,U,G,I,P,z,R,w,j,K,Z,re,Ae,zt,Tt,V,ne,ce,he;const Wt=new DOMParser().parseFromString(i,"application/xml"),Me={video:[],audio:[],text:[]},me=Wt.children[0],$t=me.getElementsByTagName("Period")[0],Qt=(s=(r=(t=me.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||r===void 0?void 0:r.trim())!==null&&s!==void 0?s:"",gu=$t.children,yu=me.getAttribute("type")==="dynamic",xa=me.getAttribute("availabilityStartTime"),Tu=xa?new Date(xa).getTime():void 0;let tt;const Na=me.getAttribute("mediaPresentationDuration"),Oa=$t.getAttribute("duration"),Tr=me.getElementsByTagName("vk:Attrs")[0],Ma=Tr==null?void 0:Tr.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Na)tt=Eo(Na);else if(Oa){const Ee=Eo(Oa);a.isNonNullable(Ee)&&(tt=Ee)}else Ma&&(tt=parseInt(Ma,10));let Eu=0;const Er=(o=(n=me.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],$u=Er.includes(ir.WEBM_AS_IN_FFMPEG)||Er.includes(ir.WEBM_AS_IN_SPEC)?Ut.WEBM:Ut.MP4;for(const Ee of gu){const yi=Ee.getAttribute("mimeType"),ku=Ee.getAttribute("codecs"),Ba=(l=Ee.getAttribute("contentType"))!==null&&l!==void 0?l:yi==null?void 0:yi.split("/")[0],wu=(u=(c=Ee.getAttribute("profiles"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[],Va=Ee.querySelectorAll("Representation"),Pu=Ee.querySelector("SegmentTemplate");if(Ba===se.TEXT){for(const ee of Va){const ze=ee.getAttribute("id")||"",Ti=Ee.getAttribute("lang"),kt=(f=(h=(d=ee.querySelector("BaseURL"))===null||d===void 0?void 0:d.textContent)===null||h===void 0?void 0:h.trim())!==null&&f!==void 0?f:"",$r=new URL(kt||Qt,e).toString(),kr=ze.includes("_auto");Me[se.TEXT].push({id:ze,lang:Ti,isAuto:kr,kind:se.TEXT,url:$r})}continue}for(const ee of Va){const ze=(p=ee.getAttribute("mimeType"))!==null&&p!==void 0?p:yi,Ti=(m=(v=ee.getAttribute("codecs"))!==null&&v!==void 0?v:ku)!==null&&m!==void 0?m:"",kt=(S=(b=ee.getAttribute("contentType"))!==null&&b!==void 0?b:ze==null?void 0:ze.split("/")[0])!==null&&S!==void 0?S:Ba,$r=(E=(y=Ee.getAttribute("profiles"))===null||y===void 0?void 0:y.split(","))!==null&&E!==void 0?E:[],kr=parseInt((T=ee.getAttribute("width"))!==null&&T!==void 0?T:"",10),Fa=parseInt(($=ee.getAttribute("height"))!==null&&$!==void 0?$:"",10),Ua=parseInt((x=ee.getAttribute("bandwidth"))!==null&&x!==void 0?x:"",10)/1e3,ja=(N=ee.getAttribute("frameRate"))!==null&&N!==void 0?N:"",Au=(F=ee.getAttribute("quality"))!==null&&F!==void 0?F:void 0,Cu=ja?Jg(ja):void 0,Iu=(O=ee.getAttribute("id"))!==null&&O!==void 0?O:(Eu++).toString(10),Ru=kt==="video"?`${Fa}p`:kt==="audio"?`${Ua}Kbps`:Ti,_u=`${Iu}@${Ru}`,Du=(I=(G=(U=ee.querySelector("BaseURL"))===null||U===void 0?void 0:U.textContent)===null||G===void 0?void 0:G.trim())!==null&&I!==void 0?I:"",Ha=new URL(Du||Qt,e).toString(),Lu=[...Er,...wu,...$r];let wr;const xu=ee.querySelector("SegmentBase"),it=(P=ee.querySelector("SegmentTemplate"))!==null&&P!==void 0?P:Pu;if(xu){const rt=(R=(z=ee.querySelector("SegmentBase Initialization"))===null||z===void 0?void 0:z.getAttribute("range"))!==null&&R!==void 0?R:"",[st,Ar]=rt.split("-").map(wt=>parseInt(wt,10)),We={from:st,to:Ar},Kt=(w=ee.querySelector("SegmentBase"))===null||w===void 0?void 0:w.getAttribute("indexRange"),[Cr,Ei]=Kt?Kt.split("-").map(wt=>parseInt(wt,10)):[],Jt=Kt?{from:Cr,to:Ei}:void 0;wr={type:Se.BYTE_RANGE,url:Ha,initRange:We,indexRange:Jt}}else if(it){const rt={representationId:(j=ee.getAttribute("id"))!==null&&j!==void 0?j:void 0,bandwidth:(K=ee.getAttribute("bandwidth"))!==null&&K!==void 0?K:void 0},st=parseInt((Z=it.getAttribute("timescale"))!==null&&Z!==void 0?Z:"",10),Ar=(re=it.getAttribute("initialization"))!==null&&re!==void 0?re:"",We=it.getAttribute("media"),Kt=(zt=parseInt((Ae=it.getAttribute("startNumber"))!==null&&Ae!==void 0?Ae:"",10))!==null&&zt!==void 0?zt:1,Cr=Lt(Ar,rt);if(!We)throw new ReferenceError("No media attribute in SegmentTemplate");const Ei=(Tt=it.querySelectorAll("SegmentTimeline S"))!==null&&Tt!==void 0?Tt:[],Jt=[];let wt=0,Ir="",Rr=0;if(Ei.length){let $i=Kt,$e=0;for(const Pt of Ei){const Ce=parseInt((V=Pt.getAttribute("d"))!==null&&V!==void 0?V:"",10),at=parseInt((ne=Pt.getAttribute("r"))!==null&&ne!==void 0?ne:"",10)||0,ki=parseInt((ce=Pt.getAttribute("t"))!==null&&ce!==void 0?ce:"",10);$e=Number.isFinite(ki)?ki:$e;const _r=Ce/st*1e3,Dr=$e/st*1e3;for(let wi=0;wi<at+1;wi++){const Ou=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:$i.toString(10),segmentTime:($e+wi*Ce).toString(10)})),Ga=(Dr!=null?Dr:0)+wi*_r,Mu=Ga+_r;$i++,Jt.push({time:{from:Ga,to:Mu},url:Ou})}$e+=(at+1)*Ce,wt+=(at+1)*_r}Rr=$e/st*1e3,Ir=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:$i.toString(10),segmentTime:$e.toString(10)}))}else if(a.isNonNullable(tt)){const $e=parseInt((he=it.getAttribute("duration"))!==null&&he!==void 0?he:"",10)/st*1e3,Pt=Math.ceil(tt/$e);let Ce=0;for(let at=1;at<Pt;at++){const ki=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:at.toString(10),segmentTime:Ce.toString(10)}));Jt.push({time:{from:Ce,to:Ce+$e},url:ki}),Ce+=$e}Rr=Ce,Ir=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:Pt.toString(10),segmentTime:Ce.toString(10)}))}const Nu={time:{from:Rr,to:1/0},url:Ir};wr={type:Se.TEMPLATE,baseUrl:Ha,segmentTemplateUrl:We,initUrl:Cr,totalSegmentsDurationMs:wt,segments:Jt,nextSegmentBeyondManifest:Nu,timescale:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!ze)continue;const Pr={video:se.VIDEO,audio:se.AUDIO,text:se.TEXT}[kt];Pr&&Me[Pr].push({id:_u,kind:Pr,segmentReference:wr,profiles:Lu,duration:tt,bitrate:Ua,mime:ze,codecs:Ti,width:kr,height:Fa,fps:Cu,quality:Au})}}return{dynamic:yu,liveAvailabilityStartTime:Tu,duration:tt,container:$u,representations:Me}},Zg=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?br(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},ey=({id:i,bitrate:e})=>({id:i,bitrate:e}),ty=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=Be(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:Be(i,-1)},iy=({id:i,lang:e,url:t,isAuto:r})=>({id:i,url:t,isAuto:r,type:"internal",language:e}),$o=i=>"size"in i,Dt=i=>i.type===Se.TEMPLATE,Zs=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class ko{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:c,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ft,this.destroyAbortController=new Ft,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(h){return de(this,arguments,function*(){const f=this.representations.get(h);a.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 IS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,mo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield C(this.loadInit(f,"high",!0));const p=this.initData.get(f.id),v=this.segments.get(f.id),m=this.parsedInitData.get(f.id);if(a.assertNonNullable(p,"No init buffer for starting representation"),a.assertNonNullable(v,"No segments for starting representation"),!(p instanceof ArrayBuffer))return yield C(void 0);this.searchGaps(v,f),yield yield C(this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(h){return de(this,arguments,function*(){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return yield C(void 0);this.switchingToRepresentationId=h;const f=this.representations.get(h);a.assertNonNullable(f,`No such representation ${h}`);let p=this.segments.get(h),v=this.initData.get(h);if(a.isNullable(v)||a.isNullable(p)?yield yield C(this.loadInit(f,"high",!1)):v instanceof Promise&&(yield yield C(v)),p=this.segments.get(h),a.assertNonNullable(p,"No segments for starting representation"),v=this.initData.get(h),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return yield C(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield yield C(this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.isLive||(p.forEach(b=>b.status=D.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(h){var f;return de(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return yield C(void 0);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||!Dt(T.segmentReference))return yield C(void 0);const $=this.getActualLiveStartingSegments(T.segmentReference);this.segments.set(T.id,$)}const p=(f=this.switchingToRepresentationId)!==null&&f!==void 0?f:this.downloadingRepresentationId,v=this.representations.get(p);a.assertNonNullable(v);const m=this.segments.get(p);a.assertNonNullable(m,"No segments for starting representation");const b=this.initData.get(p);if(a.assertNonNullable(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return yield C(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield C(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(m,v),yield yield C(this.sourceBufferTaskQueue.append(b,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=r,r){case Ut.MP4:this.containerParser=rg;break;case Ut.WEBM:this.containerParser=cg;break;default:a.assertNever(r)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.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 Ft,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=Mt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&mo(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Mt(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(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const d=Be(l,0);d&&d.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===D.FED&&!l.length&&Mt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=Be(r,-1);c&&c.status===D.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let r=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:n.time.from+s}),r=n.time.to;a.isNonNullable(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let n=0,o=t.length-1;do s.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,s,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Dt(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:D.NONE,size:void 0})),c=(r=this.segments.get(o.id))!==null&&r!==void 0?r:[],u=(n=(s=Be(c,-1))===null||s===void 0?void 0:s.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 r of this.representations.values()){const s=r.segmentReference;if(!Dt(s))return;const n=Math.round(e.segment.time.to*s.timescale/1e3).toString(10),o=Lt(s.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(r.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:D.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(c=>c.time.from<=e&&c.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;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,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){const r=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},v)=>{const m=f<=r&&p>=r,b=f>r||m||v===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=r+S||p<=r+S;return(h===D.NONE||h===D.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Js(this.sourceBuffer.buffered,r))&&b&&y});if(s===-1)return[];if(t!==Se.BYTE_RANGE)return e.slice(s,s+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=s;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===D.NONE||f.status===D.PARTIALLY_EJECTED)c.push(f);else break}return c}loadSegments(e,t,r="auto"){return H(this,void 0,void 0,function*(){t.segmentReference.type===Se.TEMPLATE?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return H(this,void 0,void 0,function*(){e.status=D.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:n,url:o,signal:l,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(yield a.abortable(l,function(){return de(this,arguments,function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(h=>setTimeout(h,d)))})}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const d=yield this.fetcher.fetch(o,{range:n,signal:l,onProgress:c,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}c&&s.feedingBytes&&u?yield Promise.all(u):yield this.sourceBufferTaskQueue.append(h,l),s.segment.status=D.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(d){if(!Zs(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}})}loadByteRangeSegments(e,t,r="auto"){return H(this,void 0,void 0,function*(){if(!e.length)return;for(const c of e)c.status=D.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:n,signal:o,onProgress:l}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield a.abortable(o,function(){return de(this,arguments,function*(){const c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(u=>setTimeout(u,c)))})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(n,{range:s,onProgress:l,signal:o,priority:r}),this.failedDownloads=0}catch(c){if(!Zs(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}})}prepareByteRangeFetchSegmentParams(e,t){if(Dt(t.segmentReference))throw new Error("Representation is not byte range type");const r=t.segmentReference.url,s={from:Be(e,0).byte.from,to:Be(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:r,range:s,signal:n,onProgress:(c,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:s?s.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Dt(t.segmentReference))throw new Error("Representation is not template type");const r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");const s=r.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:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:s,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 r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=Mt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:s,signal:n}){return H(this,void 0,void 0,function*(){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){s();continue}if(l.loadedBytes=r,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=D.PARTIALLY_FED,l.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),l.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:s,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===Se.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(d.representationId!==t||!(!f||h.byte.from>=r&&h.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const m=f?h.byte.from-r:0,b=f?h.byte.to-r:e.byteLength,S=m<s,y=b<=s;if(h.status===D.DOWNLOADING&&S&&y){h.status=D.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,s-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=D.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 r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=D.FED,$o(e.segment)&&(e.segment.size=e.fedBytes);for(const s of this.representations.values())if(s.id!==t)for(const n of(r=this.segments.get(s.id))!==null&&r!==void 0?r:[])n.status===D.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=D.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===D.PARTIALLY_FED||e.status===D.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=D.NONE),e.status=D.PARTIALLY_EJECTED):e.status=D.NONE;for(const r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=po(()=>Pa(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return H(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return de(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(c=>setTimeout(c,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>H(this,void 0,void 0,function*(){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&&Dt(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),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return H(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const c=u=>{var d;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h=$o(u)?(d=u.size)!==null&&d!==void 0?d:0:u.byte.to-u.byte.from;s+=h};for(const u of this.segments.values())for(const d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;d.status===D.FED&&c(d)}if(l=isFinite(n)&&isFinite(o),!l){s=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)||s>t)break;d.status===D.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===D.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&&r){s=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===D.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 r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=po(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==D.FED&&n!==D.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.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?s.status=D.PARTIALLY_EJECTED:s.status=D.NONE)}}}var ea=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},ry=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Bt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Bt||(Bt={}));class sy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Ft,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return de(this,arguments,function*(){let n=s;this.requestQuic&&(n=ea(n));const o=yield yield C(ui(n,{signal:this.abortAllController.signal}).catch(Zt));return o?(this.onHeadersReceived(o.headers),yield C(o.text())):yield C(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Bt.HEADER:Bt.PARAM,range:o,onProgress:l,priority:c="auto",signal:u,measureThroughput:d=!0,isLowLatency:h=!1}={}){var f,p;return de(this,arguments,function*(){let v=s;const m=new Headers;if(o)switch(n){case Bt.HEADER:{m.append("Range",`bytes=${o.from}-${o.to}`);break}case Bt.PARAM:{const P=new URL(v,location.href);P.searchParams.append("bytes",`${o.from}-${o.to}`),v=P.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=ea(v));let b=this.abortAllController.signal,S;if(u){const P=new Ft;if(S=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{P.abort()}catch(z){Zt(z)}}),this.abortAllController.signal.aborted||u.aborted)try{P.abort()}catch(z){Zt(z)}b=P.signal}const y=a.now(),E=yield yield C(ui(v,{priority:c,headers:m,signal:b}).catch(Zt)),T=a.now();if(!E)return S==null||S.unsubscribe(),yield C(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!E.ok||!E.body)return S==null||S.unsubscribe(),yield C(Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`)));if(this.onHeadersReceived(E.headers),!l&&!d)return S==null||S.unsubscribe(),yield C(E.arrayBuffer());const[$,x]=E.body.tee(),N=$.getReader();d&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(x,h));let F=0,O=new Uint8Array(0),U=!1;const G=P=>{S==null||S.unsubscribe(),U=!0,Zt(P)},I=a.abortable(b,function({done:P,value:z}){return de(this,arguments,function*(){if(F===0&&this.lastRequestFirstBytes$.next(a.now()-y),b.aborted)return S==null||S.unsubscribe(),yield C(void 0);if(!P&&z){const R=new Uint8Array(O.length+z.length);R.set(O),R.set(z,O.length),O=R,F+=z.byteLength,l==null||l(new DataView(O.buffer),F),yield yield C(N==null?void 0:N.read().then(I,G))}})}.bind(this));return yield yield C(N==null?void 0:N.read().then(I,G)),S==null||S.unsubscribe(),yield C(U?null:O.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return de(this,arguments,function*(){if(s.type!==Se.BYTE_RANGE)return yield C(null);const{from:c,to:u}=s.initRange;let d=c,h=u,f=!1,p,v;s.indexRange&&(p=s.indexRange.from,v=s.indexRange.to,f=u+1===p,f&&(d=Math.min(p,c),h=Math.max(v,u))),d=Math.min(d,0);const m=yield yield C(this.fetch(s.url,{range:{from:d,to:h},priority:o,measureThroughput:!1}));if(!m)return yield C(null);const b=new DataView(m,c-d,u-d+1);if(!n.validateData(b))throw new Error("Invalid media file");const S=n.parseInit(b),y=(l=s.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 yield C(this.fetch(s.url,{range:y,priority:o,measureThroughput:!1}));if(!$)return yield C(null);E=new DataView($)}const T=n.parseSegments(E,S,y);return yield C({init:S,dataView:new DataView(m),segments:T})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return de(this,arguments,function*(){if(s.type!==Se.TEMPLATE)return yield C(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield C(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield C(null);const c=s.segments.map(u=>Object.assign(Object.assign({},u),{status:D.NONE,size:void 0}));return yield C({init:null,segments:c,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=ry(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return H(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case Se.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case Se.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Zt=i=>{if(!Zs(i))throw i},ta=1e3,ar=(i,e,t)=>t*e+(1-t)*i,fu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,ay=(i,e,t,r)=>{let s=0,n=t;const o=fu(i,e),l=e<r?e:r;for(let c=0;c<l;c++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class Da{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new De(`raw_${r}`),this.smoothedSeries$=new De(`smoothed_${r}`),this.reportedSeries$=new De(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class ny extends Da{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ar(this.slow,e,this.params.emaAlphaSlow),this.fast=ar(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class oy extends Da{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=fu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);const r=ay(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class ly extends Da{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?ar(this.smoothed,e,this.params.emaAlpha):e}}class ia{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ny({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new oy({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ly(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const uy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},ot=()=>window.ManagedMediaSource||window.MediaSource,pu=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},cy=()=>{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))},dy=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,wo=["timeupdate","progress","play","seeked","stalled","waiting"];var be;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(be||(be={}));let hy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new X(be.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.livePositionFromPlayer$=new a.ValueSubject(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ft,this.initManifest=a.abortable(this.destroyController.signal,function(t,r,s){var n;return de(this,arguments,function*(){this.element=t,this.manifestUrlString=we(r,s,ie.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(be.MANIFEST_READY),this.manifest=yield yield C(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(be.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=a.abortable(this.destroyController.signal,function(){var t;return de(this,arguments,function*(){const r=yield yield C(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!r)return yield C(null);let s;try{s=Xg(r!=null?r:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!s)return yield C(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=ot())===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${c}"`))||o===se.TEXT)};return s.dynamic&&this.isLive$.getValue()!==s.dynamic&&(this.isLive$.next(s.dynamic),this.liveDuration$.getValue()!==s.duration&&this.liveDuration$.next(-1*((t=s.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==s.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(s.liveAvailabilityStartTime)),yield C(Object.assign(Object.assign({},s),{representations:er(Object.entries(s.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r,s){var n;return de(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(be.REPRESENTATIOS_READY);const o=m=>{this.representationSubscription.add(a.fromEvent(m,"error").pipe(a.filter(b=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?dy():new MediaSource;const l=document.createElement("source");if(o(l),l.src=URL.createObjectURL(this.source),this.element.appendChild(l),this.tuning.useManagedMediaSource&&pu())if(s){const m=document.createElement("source");o(m),m.type="application/x-mpegurl",m.src=s.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 ko(se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,c),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new ko(se.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(a.interval(ta).subscribe(m=>{var b;if(!((b=this.element)===null||b===void 0)&&b.paused){const S=oo(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P);this.manifestUrlString=we(this.manifestUrlString,S+ta,ie.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...wo.map(m=>a.fromEvent(this.element,m))).pipe(a.map(m=>this.element?Mt(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(m=>!!m),a.tap(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(a.filter(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,E=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,T=b-S;let $=1+Math.sign(T)*E;Math.abs(T)<y?$=1:Math.abs(T)>y*2&&($=1+Math.sign(T)*E*2),uy(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,y;let E=0;if(b){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 N,F;return(F=(N=x.getLiveSegmentsToLoadState(this.manifest))===null||N===void 0?void 0:N.to)!==null&&F!==void 0?F:0}))-T}E&&this.liveLoadBufferLength$.getValue()!==E&&this.liveLoadBufferLength$.next(E)}));let m=0;this.representationSubscription.add(a.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:b,bufferLength:S})=>H(this,void 0,void 0,function*(){if(a.assertNonNullable(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,E=oo(this.manifestUrlString,ie.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,N=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,F=this.isActiveLowLatency?S:b;let O=_e.None;if(this.isActiveLowLatency?O=_e.ActiveLowLatency:F<$+N&&F>=$?O=_e.LiveWithTargetOffset:E!==0&&F<$&&(O=_e.LiveForwardBuffering),isFinite(b)&&(m=b>m?b:m),O===_e.LiveForwardBuffering||O===_e.LiveWithTargetOffset){const U=m-($+x),G=this.normolizeLiveOffset(Math.trunc(E+U/y)),I=Math.abs(G-E);let P;!b||I<=this.tuning.dashCmafLive.offsetCalculationError?P=E:G>0&&I>this.tuning.dashCmafLive.offsetCalculationError?P=G:P=0,this.manifestUrlString=we(this.manifestUrlString,P,ie.DASH_CMAF_OFFSET_P)}O!==_e.None&&O!==_e.ActiveLowLatency&&(m=0,this.updateLive())})))}const u=a.merge(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),d=a.merge(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:u,someBufferEnded:d}).pipe(a.filter(({allBuffersFull:m,someBufferEnded:b})=>m&&b))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(a.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 yield C(new Promise(m=>{var b;return(b=this.source)===null||b===void 0?void 0:b.addEventListener("sourceopen",m)})));const h=(n=this.manifest.duration)!==null&&n!==void 0?n:0,f=(m,b)=>{var S;return Math.max(m,(S=b.duration)!==null&&S!==void 0?S:0)},p=this.manifest.representations.audio.reduce(f,h),v=this.manifest.representations.video.reduce(f,h);(p||v)&&(this.source.duration=Math.max(p,v)/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield C(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield C(this.videoBufferManager.startWith(t)),this.state$.setState(be.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new sy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=ia.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,r,s,n;return H(this,void 0,void 0,function*(){a.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=we(this.manifestUrlString,o,ie.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((r=this.manifest)===null||r===void 0?void 0:r.representations.video),yield(s=this.audioBufferManager)===null||s===void 0?void 0:s.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio))})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(be.RUNNING),this.subscription.add(a.merge(...wo.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Js(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()}switchRepresentation(e,t){return H(this,void 0,void 0,function*(){const r={[se.VIDEO]:this.videoBufferManager,[se.AUDIO]:this.audioBufferManager,[se.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let c;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?c=e:c=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Js(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,r;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(s=>s.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,(r=this.audioBufferManager)===null||r===void 0||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(be.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}waitingEventCallback(){return H(this,void 0,void 0,function*(){try{if(!this.element)return;this.isLive$.getValue()?yield this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:a.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return H(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield 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,r=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){const s=Math.max(...r);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class fy{constructor(e,t){this.fov=e,this.orientation=t}}class py{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/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:s,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r: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,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=Object.assign({},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,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var my=`#define GLSLIFY 1
|
|
37
|
+
`}),R}return u==null||u.recordSwitch(P),P};var Ne=i=>new URL(i).hostname;const co=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 yt=i=>H(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!co(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return co(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});function le(){return a.now()}function iu(i){return le()-i}function ho(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,c=!1)=>{s(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 uS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Ki(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,c=!1,u=0,d,h,f=!1,p="arraybuffer",v=7e3,m=2e3,b=()=>{if(c)return;a.assertNonNullable(d);const I=iu(d);let P;if(I<m){P=m-I,setTimeout(b,P);return}m*=2,m>v&&(m=v),o&&o.abort(),o=new s,O()};const S=I=>(n=I,G),y=I=>(h=I,G),T=()=>(p="json",G),E=()=>{if(!c){if(--u>=0){b(),r&&r();return}c=!0,h&&h(),t&&t()}},$=I=>(f=I,G),O=()=>{d=le(),o=new s,o.open("get",i);let I=0,P,z=0;const R=()=>(a.assertNonNullable(d),Math.max(d,Math.max(P||0,z||0)));if(n&&o.addEventListener("progress",w=>{const j=le();n.updateChunk&&w.loaded>I&&(n.updateChunk(R(),w.loaded-I),I=w.loaded,P=j)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(c)return;a.assertNonNullable(o);const w=o.status;if(w>=200&&w<300){if(o.response.byteLength&&n){const j=o.response.byteLength-I;j&&n.updateChunk&&n.updateChunk(R(),j)}o.responseType==="json"&&!Object.values(o.response).length?E():(h&&h(),e(o.response))}else E()}),o.addEventListener("error",()=>{E()}),f){const w=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=le(),o.removeEventListener("readystatechange",w))};o.addEventListener("readystatechange",w)}return o.responseType=p,o.send(),G},G={withBitrateReporting:S,withParallel:$,withJSONResponse:T,withRetryCount:I=>(u=I,G),withRetryInterval:(I,P)=>(a.isNonNullable(I)&&(m=I),a.isNonNullable(P)&&(v=P),G),withTimeout:I=>(l=I,G),withFinally:y,send:O,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return G}const cS=100,dS=2e3,hS=500;let fS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-hS;if(t-e>dS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const c=n.bytes*o/l;s+=c,n.start=t,n.bytes-=c}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>cS&&(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 pS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=le(),s=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=le()-r,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=Ki(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_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=le();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Fi=1e4,fs=3,mS=6e4,vS=10,bS=1,SS=500;class gS{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 fS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=ho(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=ho(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{uS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new pS(fs,Fi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,c=null,u=null,d=!1;const h=()=>{const E=n&&(!d||d===this.rep);return E||t("Not running!"),E},f=(E,$,O)=>{c&&c.abort(),c=Ki(this.urlResolver.resolve(E,!1),$,O,()=>this._retryCallback()).withTimeout(Fi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fs).withFinally(()=>{c=null}).send()},p=(E,$,O)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),$,O,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=E=>{const $=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${$}=>${E}`),r.playbackRate=E)},m=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const O=le()-1e4;let M=0;for(let x=0;x<this.bufferStates.length;x++){const U=this.bufferStates[x];E=Math.min(E,U.buf),U.ts<O&&M++}this.bufferStates.splice(0,M),t(`update playback rate; minBuffer=${E} drop=${M} jitter=${this.sourceJitter}`);let F=E-bS;this.sourceJitter>=0?F-=this.sourceJitter/2:this.sourceJitter-=1,F>3?v(1.15):F>1?v(1.1):F>.3?v(1.05):v(1)}},S=E=>{let $;const O=()=>$&&$.start?$.start.length:0,M=w=>$.start[w]/1e3,F=w=>$.dur[w]/1e3,x=w=>$.fragIndex+w,U=(w,j)=>({chunkIdx:x(w),startTS:M(w),dur:F(w),discontinuity:j}),G=()=>{let w=0;if($&&$.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=j;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let re=$.dur.length-1;for(;re>=0&&(Z-=$.dur[re],!(Z<=0));--re);w=Math.min(re,$.dur.length-1-K),w=Math.max(w,0)}return U(w,!0)},I=w=>{const j=O();if(!(j<=0)){if(a.isNonNullable(w)){for(let K=0;K<j;K++)if(M(K)>w)return U(K)}return G()}},P=w=>{const j=O(),K=w?w.chunkIdx+1:0,Z=K-$.fragIndex;if(!(j<=0)){if(!w||Z<0||Z-j>vS)return t(`Resync: offset=${Z} bChunks=${j} chunk=`+JSON.stringify(w)),G();if(!(Z>=j))return U(K-$.fragIndex,!1)}},z=(w,j,K)=>{u&&u.abort(),u=Ki(this.urlResolver.resolve(w,!0,this.lowLatency),j,K,()=>this._retryCallback()).withTimeout(Fi).withRetryCount(fs).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(w,j)=>{z(E,K=>{if(!h())return;$=K;const Z=!!$.lowLatency;Z!==this.lowLatency&&m(Z);let re=0;for(let Ae=0;Ae<$.dur.length;++Ae)re+=$.dur[Ae];re>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(re/$.dur.length)),s({name:"index",zeroTime:$.zeroTime,shiftDuration:$.shiftDuration}),this.sourceJitter=$.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,$.jitter/1e3)):1,w(I(j))},()=>this._handleNetworkError())},nextChunk:P}},y=()=>{n=!1,l&&l.abort(),c&&c.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{const{videoElement:$,logger:O}=this.params;let M=S(e.jidxUrl),F,x,U,G,I=0,P,z,R;const w=()=>{P&&(clearTimeout(P),P=void 0);const V=Math.max(SS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=I+V,ce=le(),he=Math.min(1e4,ne-ce);I=ce;const Et=()=>{u||h()&&M.seek(()=>{h()&&(I=le(),j(),w())})};he>0?P=window.setTimeout(()=>{this.paused?w():Et()},he):Et()},j=()=>{let V;for(;V=M.nextChunk(G);)G=V,zt(V);const ne=M.nextChunk(U);if(ne){if(U&&ne.discontinuity){O("Detected discontinuity; restarting playback"),this.paused?w():(y(),this._initPlayerWith(e));return}Ae(ne)}else w()},K=(V,ne)=>{if(!h()||!this.sourceBuffer)return;let ce,he,Et;const Wt=Me=>{window.setTimeout(()=>{h()&&K(V,ne)},Me)};if(this.sourceBuffer.updating)O("Source buffer is updating; delaying appendBuffer"),Wt(100);else{const Me=le(),me=$.currentTime;!this.paused&&$.buffered.length>1&&z===me&&Me-R>500&&(O("Stall suspected; trying to fix"),this._fixupStall()),z!==me&&(z=me,R=Me);const $t=this._getBufferSizeSec();if($t>30)O(`Buffered ${$t} seconds; delaying appendBuffer`),Wt(2e3);else try{this.sourceBuffer.appendBuffer(V),this.videoPlayStarted?(this.bufferStates.push({ts:Me,buf:$t}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Qt){if(Qt.name==="QuotaExceededError")O("QuotaExceededError; delaying appendBuffer"),Et=this.sourceBuffer.buffered.length,Et!==0&&(ce=this.sourceBuffer.buffered.start(0),he=me,he-ce>4&&this.sourceBuffer.remove(ce,he-3)),Wt(1e3);else throw Qt}}},Z=()=>{x&&F&&(O([`Appending chunk, sz=${x.byteLength}:`,JSON.stringify(U)]),K(x,function(){x=null,j()}))},re=V=>e.fragUrlTemplate.replace("%%id%%",V.chunkIdx),Ae=V=>{h()&&p(re(V),(ne,ce)=>{if(h()){if(ce/=1e3,x=ne,U=V,o=V.startTS,ce){const he=Math.min(10,V.dur/ce);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}Z()}},()=>this._handleNetworkError())},zt=V=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(re(V),!1)))},Tt=V=>{h()&&(e.cachedHeader=V,K(V,()=>{F=!0,Z()}))};n=!0,M.seek(V=>{if(h()){if(I=le(),!V){w();return}G=V,!a.isNullable(E)||V.startTS>E?Ae(V):(U=V,j())}},E),e.cachedHeader?Tt(e.cachedHeader):f(e.headerUrl,Tt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),v=h/this.bitrate,p>10&&v>.8||p>15&&v>.5||p>20&&v>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const v=le();if(this.chunkRateEstimator.addInterval(f,v,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:v-f,speed:b}),!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&&iu(o)<3e4)return;r(h)}c=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=le();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=Ki(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Fi).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;yt(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((c,u)=>{c.video&&s.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):(r({name:"error",type:"empty_manifest"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},mS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}class ru{constructor(){this.onDroopedVideoFramesLimit$=new a.Subject,this.subscription=new a.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new a.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&&!a.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality(),s=t-this.prevTotalVideoFrames,n=r-this.prevDroppedVideoFrames,o=1-(s-n)/s;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&a.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,r)}}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(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),r=a.merge(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),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,r;const s=(r=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>a.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||r===void 0?void 0:r[0];return e!=null?e:s}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 L;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const yS=[L.PAUSED,L.PLAYING,L.READY],TS=[L.PAUSED,L.PLAYING,L.READY];class ES{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(L.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Ze,this.droppedFramesManager=new ru,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new Ca,this._dashCb=s=>{var n,o,l,c;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,d=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=br(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),v=h.bitrate/1e3,m=Object.assign({},h.video);if(!p)continue;const b={id:f,quality:p,bitrate:v,size:m};d.push({track:b,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)===L.MANIFEST_READY&&this.videoState.setState(L.MANIFEST_READY);break}case"qualitySwitch":{const u=s.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),a.isNonNullable(d)&&this.params.output.currentVideoTrack$.next(d);break}case"bandwidth":{const{size:u,duration:d}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,d);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration||0),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{const s=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: ${s}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(c)};`}),o===exports.PlaybackState.STOPPED){s!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(L.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(TS.includes(s)&&(u||d)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&c.state===N.Requested&&yS.includes(s)){this.seek(c.position-this.liveOffset.getTotalPausedTime());return}switch(s){case L.STOPPED:this.videoState.startTransitionTo(L.MANIFEST_READY),this.dash.attachSource(we(this.params.source.url));return;case L.MANIFEST_READY:this.videoState.startTransitionTo(L.READY),this.prepare();break;case L.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(L.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(L.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(L.PAUSED)})}return;case L.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(L.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case L.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(L.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(L.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(we(this.params.source.url,h))}return;default:return a.assertNever(s)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=vt(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(Ne(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 r=gt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(a.map(s=>s.map(({track:n})=>n)))}),this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===L.READY&&this.videoState.setState(L.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(L.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===N.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(L.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(gi(this.video,this.params.desiredState.isLooped,t)).add(St(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(qt(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const n=s&&a.videoQualityToHeight(s);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case L.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case L.MANIFEST_READY:case L.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 L.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case L.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.observableFrom(["init"])).pipe(a.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),bt(this.video)}createLiveDashPlayer(){const e=new gS({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,r,s,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=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!u&&a.isNonNullable(c)?c:Sr(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,v=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(d&&(f||h!==p)&&this.setVideoTrack(d),v&&this.setAutoQuality(u),f||v||h!==p){const m=(o=l.find(({track:b})=>b.id===h))===null||o===void 0?void 0:o.representation;a.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e.id))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e.id}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===L.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(we(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}}var se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(se||(se={}));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 ir;(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"})(ir||(ir={}));var Se;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Se||(Se={}));var D;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(D||(D={}));var Ut;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ut||(Ut={}));var rr;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(rr||(rr={}));var Q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));var Mt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const $S=300,kS=(i,e=$S)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(a.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),a.isNonNullable(c)&&a.isNonNullable(u)&&t.next({width:c,height:u})},e));return n.observe(i),()=>n.disconnect()});class fo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class su extends fo{constructor(){super(),this.listeners||fo.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 au=class{constructor(){Object.defineProperty(this,"signal",{value:new su,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(au.prototype[Symbol.toStringTag]="AbortController",su.prototype[Symbol.toStringTag]="AbortSignal");function nu(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 wS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!nu({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,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,v)=>{d.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(c,u)])}return o(c,u)},Request:n}}const gr=nu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ou=gr?wS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ui=gr?ou.fetch:window.fetch;gr?ou.Request:window.Request;const Ft=gr?au:window.AbortController;var Js=(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 PS=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},AS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",po=AS?PS:window.requestIdleCallback;var ps,ms;const CS=16;let lu=!1;try{lu=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((ms=(ps=navigator.userAgent.match(/Version\/(\d+)/))===null||ps===void 0?void 0:ps[1])!==null&&ms!==void 0?ms:"",10)<=CS}catch(i){console.error(i)}class IS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return H(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return H(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return H(this,void 0,void 0,function*(){return new Promise(t=>{let r;lu&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),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:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var mo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Te{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 s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}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 uu extends Te{}class RS extends Te{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const r=this.readString(4);this.compatibleBrands.push(r),t-=4}}}class _S extends Te{parseChildrenBoxes(){return et(this.content)}}class DS extends Te{parseChildrenBoxes(){return et(this.content)}}class LS extends Te{constructor(e){super(e),this.data=this.content}}class qe extends Te{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class xS extends qe{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 r=this.readUint32();const s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const l=r>>>28,c=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:c})}}}class NS extends Te{parseChildrenBoxes(){return et(this.content)}}class OS extends Te{parseChildrenBoxes(){return et(this.content)}}var dt;(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"})(dt||(dt={}));class MS extends qe{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=dt.MONOSCOPIC;break;case 1:this.stereoMode=dt.TOP_BOTTOM;break;case 2:this.stereoMode=dt.LEFT_RIGHT;break;case 3:this.stereoMode=dt.STEREO_CUSTOM;break;case 4:this.stereoMode=dt.RIGHT_LEFT;break}this.cursor+=1}}class BS extends qe{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class VS extends qe{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class FS extends Te{parseChildrenBoxes(){return et(this.content)}}class US extends qe{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 jS extends Te{parseChildrenBoxes(){return et(this.content)}}class HS extends Te{parseChildrenBoxes(){return et(this.content)}}class GS extends qe{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class YS extends Te{parseChildrenBoxes(){return et(this.content)}}class qS extends qe{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 zS extends qe{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 WS extends qe{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 QS={ftyp:RS,moov:_S,moof:DS,mdat:LS,sidx:xS,trak:NS,mdia:FS,mfhd:GS,tkhd:US,traf:YS,tfhd:qS,tfdt:zS,trun:WS,minf:jS,sv3d:OS,st3d:MS,prhd:BS,proj:HS,equi:VS,unknown:uu};class KS{createBox(e,t){const r=QS[e];return r?new r(t):new uu(t)}createFromView(e){const r=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return yr.createBox(r,new DataView(e.buffer,e.byteOffset))}}const yr=new KS;function ri(i,e){const t=new Uint8Array(i.buffer),r=e.split("").map(o=>o.charCodeAt(0));let s=i.byteOffset,n=[];for(;s<t.byteLength;){if(t[s]===r[n.length]?n.push(t[s]):n.length&&(n=[],s--),n.length===4){const l=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+l>i.buffer.byteLength?null:yr.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function Xs(i,e){const t=[];let r=i.byteOffset;for(;r<i.buffer.byteLength;){const s=ri(new DataView(i.buffer,r,i.buffer.byteLength-r),e);if(s)t.push(s),r=s.source.byteOffset+s.size;else break}return t}function et(i){const e=[];let t=0;for(;t<i.byteLength;){const r=yr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(r),!r.size)break;t+=r.size}return e}const JS=new TextDecoder("ascii"),XS=i=>JS.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",ZS=i=>{const e=yr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,r=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:D.NONE,time:{from:t,to:t+o},byte:{from:r,to:r+n.referencedSize-1}};return t+=o,r+=n.referencedSize,l})},eg=i=>{const e=Xs(i,"mdat"),t=Xs(i,"moof");if(!(e.length&&t.length))return null;const r=t[0],s=e[e.length-1],n=r.source.byteOffset,l=s.source.byteOffset-r.source.byteOffset+s.size;return new DataView(i.buffer,n,l)},tg=(i,e)=>{const t=Xs(i,"traf"),r=t[t.length-1].children.find(c=>c.type==="tfhd"),s=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=r.defaultSampleDuration*n.sampleCount,(Number(s.baseMediaDecodeTime)+o)/e*1e3},ig=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:rr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ri(i,"sv3d")){e.is3dVideo=!0;const r=ri(i,"st3d");r&&(e.stereoMode=r.stereoMode);const s=ri(i,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=ri(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},rg={validateData:XS,parseInit:ig,getIndexRange:()=>{},parseSegments:ZS,parseFeedableSegmentChunk:eg,getSegmentEndTime:tg};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 vo={[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}},cu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=sr(i,t),s=r in vo,n=s?vo[r].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=sr(c),h=u*Math.pow(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:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},sr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Le=(i,e)=>{switch(e){case k.SignedInteger:return i.getInt8(0);case k.UnsignedInteger:return sr(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:a.assertNever(e)}},jt=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=cu(r);if(!e(s))return;s.type===k.Master&&jt(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},sg=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,r;const s=cu(i);return jt(s.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=Le(l,o):n===g.DocType?t=Le(l,o):n===g.DocTypeReadVersion&&(r=Le(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},du=[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],ag=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],ng=i=>{let e,t,r,s,n=!1,o=!1,l=!1,c,u,d=!1;const h=0;return jt(i,({tag:f,type:p,value:v,valueSize:m})=>{if(f===g.SeekID){const b=Le(v,p);u=sr(b)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=v.byteOffset,t=v.byteOffset+m):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?r=Le(v,p):f===g.Duration?s=Le(v,p):f===g.SeekPosition&&u===g.Cues?c=Le(v,p):f===g.Tracks?jt(v,({tag:b,type:S,value:y})=>b===g.ProjectionType?(d=Le(y,S)===1,!1):!0):n&&o&&du.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:c,is3dVideo:d,stereoMode:h,projectionType:rr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},og=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},lg=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return jt(i,({tag:l,type:c,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&s(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=Le(u,c));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=Le(u,c));break;default:t&&du.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,c)=>{const{time:u,position:d}=l,h=n[c+1];return{status:D.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}}})},ug=i=>{let e=0,t=!1;try{jt(i,r=>r.tag===g.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ag.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},cg={validateData:sg,parseInit:ng,getIndexRange:og,parseSegments:lg,parseFeedableSegmentChunk:ug};var dg=Ge,hg=di,fg=ue,pg=fg("match"),mg=function(i){var e;return dg(i)&&((e=i[pg])!==void 0?!!e:hg(i)=="RegExp")},vg=vi,bg=String,Sg=function(i){if(vg(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return bg(i)},gg=Ye,yg=function(){var i=gg(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},Tg=pe,Eg=Oe,$g=lr,kg=yg,bo=RegExp.prototype,wg=function(i){var e=i.flags;return e===void 0&&!("flags"in bo)&&!Eg(i,"flags")&&$g(bo,i)?Tg(kg,i):e},Ra=ye,Pg=hr,Ag=Math.floor,vs=Ra("".charAt),Cg=Ra("".replace),bs=Ra("".slice),Ig=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Rg=/\$([$&'`]|\d{1,2})/g,_g=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,c=Rg;return s!==void 0&&(s=Pg(s),c=Ig),Cg(n,c,function(u,d){var h;switch(vs(d,0)){case"$":return"$";case"&":return i;case"`":return bs(e,0,t);case"'":return bs(e,o);case"<":h=s[bs(d,1,-1)];break;default:var f=+d;if(f===0)return u;if(f>l){var p=Ag(f/10);return p===0?u:p<=l?r[p-1]===void 0?vs(d,1):r[p-1]+vs(d,1):u}h=r[f-1]}return h===void 0?"":h})},Dg=Pe,Lg=pe,_a=ye,So=ra,xg=te,Ng=hi,Og=mg,_t=Sg,Mg=dr,Bg=wg,Vg=_g,Fg=ue,Ug=Fg("replace"),jg=TypeError,hu=_a("".indexOf),Hg=_a("".replace),go=_a("".slice),Gg=Math.max,yo=function(i,e,t){return t>i.length?-1:e===""?t:hu(i,e,t)};Dg({target:"String",proto:!0},{replaceAll:function(e,t){var r=So(this),s,n,o,l,c,u,d,h,f,p=0,v=0,m="";if(!Ng(e)){if(s=Og(e),s&&(n=_t(So(Bg(e))),!~hu(n,"g")))throw jg("`.replaceAll` does not allow non-global regexes");if(o=Mg(e,Ug),o)return Lg(o,e,r,t);if(s)return Hg(_t(r),e,t)}for(l=_t(r),c=_t(e),u=xg(t),u||(t=_t(t)),d=c.length,h=Gg(1,d),p=yo(l,c,0);p!==-1;)f=u?_t(t(c,p,l)):Vg(c,l,p,[],void 0,t),m+=go(l,v,p)+f,v=p+d,p=yo(l,c,p+h);return v<l.length&&(m+=go(l,v)),m}});var Yg=wa,qg=Yg("String","replaceAll"),zg=qg,Wg=zg,Qg=Wg,Kg=Qg,To=nr(Kg);const Jg=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)},Eo=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const c=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(c)?0:c)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Lt=(i,e)=>{let t=i;t=To(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=To(t,o,(l,c)=>a.isNullable(n)?l:a.isNullable(c)?n:n.padStart(parseInt(c,10),"0"))}return t},Xg=(i,e)=>{var t,r,s,n,o,l,c,u,d,h,f,p,v,m,b,S,y,T,E,$,O,M,F,x,U,G,I,P,z,R,w,j,K,Z,re,Ae,zt,Tt,V,ne,ce,he;const Wt=new DOMParser().parseFromString(i,"application/xml"),Me={video:[],audio:[],text:[]},me=Wt.children[0],$t=me.getElementsByTagName("Period")[0],Qt=(s=(r=(t=me.querySelector("BaseURL"))===null||t===void 0?void 0:t.textContent)===null||r===void 0?void 0:r.trim())!==null&&s!==void 0?s:"",gu=$t.children,yu=me.getAttribute("type")==="dynamic",xa=me.getAttribute("availabilityStartTime"),Tu=xa?new Date(xa).getTime():void 0;let tt;const Na=me.getAttribute("mediaPresentationDuration"),Oa=$t.getAttribute("duration"),Tr=me.getElementsByTagName("vk:Attrs")[0],Ma=Tr==null?void 0:Tr.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Na)tt=Eo(Na);else if(Oa){const Ee=Eo(Oa);a.isNonNullable(Ee)&&(tt=Ee)}else Ma&&(tt=parseInt(Ma,10));let Eu=0;const Er=(o=(n=me.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],$u=Er.includes(ir.WEBM_AS_IN_FFMPEG)||Er.includes(ir.WEBM_AS_IN_SPEC)?Ut.WEBM:Ut.MP4;for(const Ee of gu){const yi=Ee.getAttribute("mimeType"),ku=Ee.getAttribute("codecs"),Ba=(l=Ee.getAttribute("contentType"))!==null&&l!==void 0?l:yi==null?void 0:yi.split("/")[0],wu=(u=(c=Ee.getAttribute("profiles"))===null||c===void 0?void 0:c.split(","))!==null&&u!==void 0?u:[],Va=Ee.querySelectorAll("Representation"),Pu=Ee.querySelector("SegmentTemplate");if(Ba===se.TEXT){for(const ee of Va){const ze=ee.getAttribute("id")||"",Ti=Ee.getAttribute("lang"),kt=(f=(h=(d=ee.querySelector("BaseURL"))===null||d===void 0?void 0:d.textContent)===null||h===void 0?void 0:h.trim())!==null&&f!==void 0?f:"",$r=new URL(kt||Qt,e).toString(),kr=ze.includes("_auto");Me[se.TEXT].push({id:ze,lang:Ti,isAuto:kr,kind:se.TEXT,url:$r})}continue}for(const ee of Va){const ze=(p=ee.getAttribute("mimeType"))!==null&&p!==void 0?p:yi,Ti=(m=(v=ee.getAttribute("codecs"))!==null&&v!==void 0?v:ku)!==null&&m!==void 0?m:"",kt=(S=(b=ee.getAttribute("contentType"))!==null&&b!==void 0?b:ze==null?void 0:ze.split("/")[0])!==null&&S!==void 0?S:Ba,$r=(T=(y=Ee.getAttribute("profiles"))===null||y===void 0?void 0:y.split(","))!==null&&T!==void 0?T:[],kr=parseInt((E=ee.getAttribute("width"))!==null&&E!==void 0?E:"",10),Fa=parseInt(($=ee.getAttribute("height"))!==null&&$!==void 0?$:"",10),Ua=parseInt((O=ee.getAttribute("bandwidth"))!==null&&O!==void 0?O:"",10)/1e3,ja=(M=ee.getAttribute("frameRate"))!==null&&M!==void 0?M:"",Au=(F=ee.getAttribute("quality"))!==null&&F!==void 0?F:void 0,Cu=ja?Jg(ja):void 0,Iu=(x=ee.getAttribute("id"))!==null&&x!==void 0?x:(Eu++).toString(10),Ru=kt==="video"?`${Fa}p`:kt==="audio"?`${Ua}Kbps`:Ti,_u=`${Iu}@${Ru}`,Du=(I=(G=(U=ee.querySelector("BaseURL"))===null||U===void 0?void 0:U.textContent)===null||G===void 0?void 0:G.trim())!==null&&I!==void 0?I:"",Ha=new URL(Du||Qt,e).toString(),Lu=[...Er,...wu,...$r];let wr;const xu=ee.querySelector("SegmentBase"),it=(P=ee.querySelector("SegmentTemplate"))!==null&&P!==void 0?P:Pu;if(xu){const rt=(R=(z=ee.querySelector("SegmentBase Initialization"))===null||z===void 0?void 0:z.getAttribute("range"))!==null&&R!==void 0?R:"",[st,Ar]=rt.split("-").map(wt=>parseInt(wt,10)),We={from:st,to:Ar},Kt=(w=ee.querySelector("SegmentBase"))===null||w===void 0?void 0:w.getAttribute("indexRange"),[Cr,Ei]=Kt?Kt.split("-").map(wt=>parseInt(wt,10)):[],Jt=Kt?{from:Cr,to:Ei}:void 0;wr={type:Se.BYTE_RANGE,url:Ha,initRange:We,indexRange:Jt}}else if(it){const rt={representationId:(j=ee.getAttribute("id"))!==null&&j!==void 0?j:void 0,bandwidth:(K=ee.getAttribute("bandwidth"))!==null&&K!==void 0?K:void 0},st=parseInt((Z=it.getAttribute("timescale"))!==null&&Z!==void 0?Z:"",10),Ar=(re=it.getAttribute("initialization"))!==null&&re!==void 0?re:"",We=it.getAttribute("media"),Kt=(zt=parseInt((Ae=it.getAttribute("startNumber"))!==null&&Ae!==void 0?Ae:"",10))!==null&&zt!==void 0?zt:1,Cr=Lt(Ar,rt);if(!We)throw new ReferenceError("No media attribute in SegmentTemplate");const Ei=(Tt=it.querySelectorAll("SegmentTimeline S"))!==null&&Tt!==void 0?Tt:[],Jt=[];let wt=0,Ir="",Rr=0;if(Ei.length){let $i=Kt,$e=0;for(const Pt of Ei){const Ce=parseInt((V=Pt.getAttribute("d"))!==null&&V!==void 0?V:"",10),at=parseInt((ne=Pt.getAttribute("r"))!==null&&ne!==void 0?ne:"",10)||0,ki=parseInt((ce=Pt.getAttribute("t"))!==null&&ce!==void 0?ce:"",10);$e=Number.isFinite(ki)?ki:$e;const _r=Ce/st*1e3,Dr=$e/st*1e3;for(let wi=0;wi<at+1;wi++){const Ou=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:$i.toString(10),segmentTime:($e+wi*Ce).toString(10)})),Ga=(Dr!=null?Dr:0)+wi*_r,Mu=Ga+_r;$i++,Jt.push({time:{from:Ga,to:Mu},url:Ou})}$e+=(at+1)*Ce,wt+=(at+1)*_r}Rr=$e/st*1e3,Ir=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:$i.toString(10),segmentTime:$e.toString(10)}))}else if(a.isNonNullable(tt)){const $e=parseInt((he=it.getAttribute("duration"))!==null&&he!==void 0?he:"",10)/st*1e3,Pt=Math.ceil(tt/$e);let Ce=0;for(let at=1;at<Pt;at++){const ki=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:at.toString(10),segmentTime:Ce.toString(10)}));Jt.push({time:{from:Ce,to:Ce+$e},url:ki}),Ce+=$e}Rr=Ce,Ir=Lt(We,Object.assign(Object.assign({},rt),{segmentNumber:Pt.toString(10),segmentTime:Ce.toString(10)}))}const Nu={time:{from:Rr,to:1/0},url:Ir};wr={type:Se.TEMPLATE,baseUrl:Ha,segmentTemplateUrl:We,initUrl:Cr,totalSegmentsDurationMs:wt,segments:Jt,nextSegmentBeyondManifest:Nu,timescale:st}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!kt||!ze)continue;const Pr={video:se.VIDEO,audio:se.AUDIO,text:se.TEXT}[kt];Pr&&Me[Pr].push({id:_u,kind:Pr,segmentReference:wr,profiles:Lu,duration:tt,bitrate:Ua,mime:ze,codecs:Ti,width:kr,height:Fa,fps:Cu,quality:Au})}}return{dynamic:yu,liveAvailabilityStartTime:Tu,duration:tt,container:$u,representations:Me}},Zg=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?br(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},ey=({id:i,bitrate:e})=>({id:i,bitrate:e}),ty=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=Be(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:Be(i,-1)},iy=({id:i,lang:e,url:t,isAuto:r})=>({id:i,url:t,isAuto:r,type:"internal",language:e}),$o=i=>"url"in i,Dt=i=>i.type===Se.TEMPLATE,Zs=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class ko{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:c,compatibilityMode:u=!1,manifest:d}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ft,this.destroyAbortController=new Ft,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(h){return de(this,arguments,function*(){const f=this.representations.get(h);a.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 IS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,mo(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield C(this.loadInit(f,"high",!0));const p=this.initData.get(f.id),v=this.segments.get(f.id),m=this.parsedInitData.get(f.id);if(a.assertNonNullable(p,"No init buffer for starting representation"),a.assertNonNullable(v,"No segments for starting representation"),!(p instanceof ArrayBuffer))return yield C(void 0);this.searchGaps(v,f),yield yield C(this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(h){return de(this,arguments,function*(){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return yield C(void 0);this.switchingToRepresentationId=h;const f=this.representations.get(h);a.assertNonNullable(f,`No such representation ${h}`);let p=this.segments.get(h),v=this.initData.get(h);if(a.isNullable(v)||a.isNullable(p)?yield yield C(this.loadInit(f,"high",!1)):v instanceof Promise&&(yield yield C(v)),p=this.segments.get(h),a.assertNonNullable(p,"No segments for starting representation"),v=this.initData.get(h),!v||!(v instanceof ArrayBuffer)||!this.sourceBuffer)return yield C(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield yield C(this.sourceBufferTaskQueue.append(v,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.isLive||(p.forEach(b=>b.status=D.NONE),this.pruneBuffer(m,1/0,!0)),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(h){var f;return de(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return yield C(void 0);for(const y of this.representations.keys()){const T=h.find(O=>O.id===y);T&&this.representations.set(y,T);const E=this.representations.get(y);if(!E||!Dt(E.segmentReference))return yield C(void 0);const $=this.getActualLiveStartingSegments(E.segmentReference);this.segments.set(E.id,$)}const p=(f=this.switchingToRepresentationId)!==null&&f!==void 0?f:this.downloadingRepresentationId,v=this.representations.get(p);a.assertNonNullable(v);const m=this.segments.get(p);a.assertNonNullable(m,"No segments for starting representation");const b=this.initData.get(p);if(a.assertNonNullable(b,"No init buffer for starting representation"),!(b instanceof ArrayBuffer))return yield C(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield C(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(m,v),yield yield C(this.sourceBufferTaskQueue.append(b,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=r,r){case Ut.MP4:this.containerParser=rg;break;case Ut.WEBM:this.containerParser=cg;break;default:a.assertNever(r)}this.initData=new Map(s.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.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 Ft,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=Mt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&s.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&d>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&mo(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Mt(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(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const d=Be(l,0);d&&d.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===D.FED&&!l.length&&Mt(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const c=Be(r,-1);c&&c.status===D.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(s===c))}searchGaps(e,t){this.gaps=[];let r=0;const s=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-r)>0&&this.gaps.push({representation:t.id,from:r,to:n.time.from+s}),r=n.time.to;a.isNonNullable(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,r=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,s=[];let n=0,o=t.length-1;do s.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<r&&o>=0);return this.liveInitialAdditionalOffset=n-r,this.isActiveLowLatency()?[s[0]]:s}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,s,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Dt(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:D.NONE,size:void 0})),c=(r=this.segments.get(o.id))!==null&&r!==void 0?r:[],u=(n=(s=Be(c,-1))===null||s===void 0?void 0:s.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 r of this.representations.values()){const s=r.segmentReference;if(!Dt(s))return;const n=Math.round(e.segment.time.to*s.timescale/1e3).toString(10),o=Lt(s.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(r.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:D.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(c=>c.time.from<=e&&c.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;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,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){const r=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},v)=>{const m=f<=r&&p>=r,b=f>r||m||v===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=r+S||p<=r+S;return(h===D.NONE||h===D.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!Js(this.sourceBuffer.buffered,r))&&b&&y});if(s===-1)return[];if(t!==Se.BYTE_RANGE)return e.slice(s,s+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=s;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===D.NONE||f.status===D.PARTIALLY_EJECTED)c.push(f);else break}return c}loadSegments(e,t,r="auto"){return H(this,void 0,void 0,function*(){t.segmentReference.type===Se.TEMPLATE?yield this.loadTemplateSegment(e[0],t,r):yield this.loadByteRangeSegments(e,t,r)})}loadTemplateSegment(e,t,r="auto"){return H(this,void 0,void 0,function*(){e.status=D.DOWNLOADING;const s={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(s);const{range:n,url:o,signal:l,onProgress:c,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(yield a.abortable(l,function(){return de(this,arguments,function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(h=>setTimeout(h,d)))})}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const d=yield this.fetcher.fetch(o,{range:n,signal:l,onProgress:c,priority:r,isLowLatency:this.isActiveLowLatency()});if(!d)return;const h=new DataView(d);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;s.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}c&&s.feedingBytes&&u?yield Promise.all(u):yield this.sourceBufferTaskQueue.append(h,l),s.segment.status=D.DOWNLOADED,this.onSegmentFullyAppended(s,t.id),this.failedDownloads=0}catch(d){if(!Zs(d))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(d)}})}loadByteRangeSegments(e,t,r="auto"){return H(this,void 0,void 0,function*(){if(!e.length)return;for(const c of e)c.status=D.DOWNLOADING,this.activeSegments.add({segment:c,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:s,url:n,signal:o,onProgress:l}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield a.abortable(o,function(){return de(this,arguments,function*(){const c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(u=>setTimeout(u,c)))})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(n,{range:s,onProgress:l,signal:o,priority:r}),this.failedDownloads=0}catch(c){if(!Zs(c))return;this.abortActiveSegments(e),this.onSegmentDownloadError(c)}})}prepareByteRangeFetchSegmentParams(e,t){if(Dt(t.segmentReference))throw new Error("Representation is not byte range type");const r=t.segmentReference.url,s={from:Be(e,0).byte.from,to:Be(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:r,range:s,signal:n,onProgress:(c,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:c,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:s?s.from:0,representationId:t.id})}catch(d){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:d})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Dt(t.segmentReference))throw new Error("Representation is not template type");const r=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&r.searchParams.set("low-latency","yes");const s=r.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:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:s,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 r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=Mt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:r,onSegmentAppendFailed:s,signal:n}){return H(this,void 0,void 0,function*(){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){s();continue}if(l.loadedBytes=r,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=D.PARTIALLY_FED,l.feedingBytes+=d.byteLength,yield this.sourceBufferTaskQueue.append(d),l.fedBytes+=d.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:r,loaded:s,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===Se.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(d.representationId!==t||!(!f||h.byte.from>=r&&h.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const m=f?h.byte.from-r:0,b=f?h.byte.to-r:e.byteLength,S=m<s,y=b<=s;if(h.status===D.DOWNLOADING&&S&&y){h.status=D.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,s-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=D.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 r;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=D.FED,$o(e.segment)&&(e.segment.size=e.fedBytes);for(const s of this.representations.values())if(s.id!==t)for(const n of(r=this.segments.get(s.id))!==null&&r!==void 0?r:[])n.status===D.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=D.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===D.PARTIALLY_FED||e.status===D.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=D.NONE),e.status=D.PARTIALLY_EJECTED):e.status=D.NONE;for(const r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=po(()=>Pa(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return H(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return de(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(c=>setTimeout(c,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>H(this,void 0,void 0,function*(){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&&Dt(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),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return H(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const c=u=>{var d;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h=$o(u)?(d=u.size)!==null&&d!==void 0?d:0:u.byte.to-u.byte.from;s+=h};for(const u of this.segments.values())for(const d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;d.status===D.FED&&c(d)}if(l=isFinite(n)&&isFinite(o),!l){s=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)||s>t)break;d.status===D.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===D.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&&r){s=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===D.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 r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=po(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==D.FED&&n!==D.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.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?s.status=D.PARTIALLY_EJECTED:s.status=D.NONE)}}}var ea=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},ry=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Bt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Bt||(Bt={}));class sy{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Ft,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return de(this,arguments,function*(){let n=s;this.requestQuic&&(n=ea(n));const o=yield yield C(ui(n,{signal:this.abortAllController.signal}).catch(Zt));return o?(this.onHeadersReceived(o.headers),yield C(o.text())):yield C(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Bt.HEADER:Bt.PARAM,range:o,onProgress:l,priority:c="auto",signal:u,measureThroughput:d=!0,isLowLatency:h=!1}={}){var f,p;return de(this,arguments,function*(){let v=s;const m=new Headers;if(o)switch(n){case Bt.HEADER:{m.append("Range",`bytes=${o.from}-${o.to}`);break}case Bt.PARAM:{const P=new URL(v,location.href);P.searchParams.append("bytes",`${o.from}-${o.to}`),v=P.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=ea(v));let b=this.abortAllController.signal,S;if(u){const P=new Ft;if(S=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{P.abort()}catch(z){Zt(z)}}),this.abortAllController.signal.aborted||u.aborted)try{P.abort()}catch(z){Zt(z)}b=P.signal}const y=a.now(),T=yield yield C(ui(v,{priority:c,headers:m,signal:b}).catch(Zt)),E=a.now();if(!T)return S==null||S.unsubscribe(),yield C(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(E-y),!T.ok||!T.body)return S==null||S.unsubscribe(),yield C(Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`)));if(this.onHeadersReceived(T.headers),!l&&!d)return S==null||S.unsubscribe(),yield C(T.arrayBuffer());const[$,O]=T.body.tee(),M=$.getReader();d&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(O,h));let F=0,x=new Uint8Array(0),U=!1;const G=P=>{S==null||S.unsubscribe(),U=!0,Zt(P)},I=a.abortable(b,function({done:P,value:z}){return de(this,arguments,function*(){if(F===0&&this.lastRequestFirstBytes$.next(a.now()-y),b.aborted)return S==null||S.unsubscribe(),yield C(void 0);if(!P&&z){const R=new Uint8Array(x.length+z.length);R.set(x),R.set(z,x.length),x=R,F+=z.byteLength,l==null||l(new DataView(x.buffer),F),yield yield C(M==null?void 0:M.read().then(I,G))}})}.bind(this));return yield yield C(M==null?void 0:M.read().then(I,G)),S==null||S.unsubscribe(),yield C(U?null:x.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return de(this,arguments,function*(){if(s.type!==Se.BYTE_RANGE)return yield C(null);const{from:c,to:u}=s.initRange;let d=c,h=u,f=!1,p,v;s.indexRange&&(p=s.indexRange.from,v=s.indexRange.to,f=u+1===p,f&&(d=Math.min(p,c),h=Math.max(v,u))),d=Math.min(d,0);const m=yield yield C(this.fetch(s.url,{range:{from:d,to:h},priority:o,measureThroughput:!1}));if(!m)return yield C(null);const b=new DataView(m,c-d,u-d+1);if(!n.validateData(b))throw new Error("Invalid media file");const S=n.parseInit(b),y=(l=s.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 yield C(this.fetch(s.url,{range:y,priority:o,measureThroughput:!1}));if(!$)return yield C(null);T=new DataView($)}const E=n.parseSegments(T,S,y);return yield C({init:S,dataView:new DataView(m),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return de(this,arguments,function*(){if(s.type!==Se.TEMPLATE)return yield C(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield C(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield C(null);const c=s.segments.map(u=>Object.assign(Object.assign({},u),{status:D.NONE,size:void 0}));return yield C({init:null,segments:c,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=ry(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return H(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case Se.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case Se.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Zt=i=>{if(!Zs(i))throw i},ta=1e3,ar=(i,e,t)=>t*e+(1-t)*i,fu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,ay=(i,e,t,r)=>{let s=0,n=t;const o=fu(i,e),l=e<r?e:r;for(let c=0;c<l;c++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class Da{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new De(`raw_${r}`),this.smoothedSeries$=new De(`smoothed_${r}`),this.reportedSeries$=new De(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class ny extends Da{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ar(this.slow,e,this.params.emaAlphaSlow),this.fast=ar(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class oy extends Da{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=fu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ar(this.emaSmoothed,e,this.params.emaAlpha);const r=ay(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class ly extends Da{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?ar(this.smoothed,e,this.params.emaAlpha):e}}class ia{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ny({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new oy({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new ly(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const uy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},ot=()=>window.ManagedMediaSource||window.MediaSource,pu=()=>{var i,e;return!!(window.ManagedMediaSource&&(!((e=(i=window.ManagedSourceBuffer)===null||i===void 0?void 0:i.prototype)===null||e===void 0)&&e.appendBuffer))},cy=()=>{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))},dy=()=>window.ManagedMediaSource?new ManagedMediaSource:new MediaSource,wo=["timeupdate","progress","play","seeked","stalled","waiting"];var be;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(be||(be={}));let hy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new X(be.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.livePositionFromPlayer$=new a.ValueSubject(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ft,this.initManifest=a.abortable(this.destroyController.signal,function(t,r,s){var n;return de(this,arguments,function*(){this.element=t,this.manifestUrlString=we(r,s,ie.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(be.MANIFEST_READY),this.manifest=yield yield C(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(be.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=a.abortable(this.destroyController.signal,function(){var t;return de(this,arguments,function*(){const r=yield yield C(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!r)return yield C(null);let s;try{s=Xg(r!=null?r:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!s)return yield C(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=ot())===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${c}"`))||o===se.TEXT)};return s.dynamic&&this.isLive$.getValue()!==s.dynamic&&(this.isLive$.next(s.dynamic),this.liveDuration$.getValue()!==s.duration&&this.liveDuration$.next(-1*((t=s.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==s.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(s.liveAvailabilityStartTime)),yield C(Object.assign(Object.assign({},s),{representations:er(Object.entries(s.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r,s){var n;return de(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(be.REPRESENTATIOS_READY);const o=m=>{this.representationSubscription.add(a.fromEvent(m,"error").pipe(a.filter(b=>{var S;return!!(!((S=this.element)===null||S===void 0)&&S.played.length)})).subscribe(b=>{this.error$.next({id:"VideoSource",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Unexpected video source error",thrown:b})}))};this.source=this.tuning.useManagedMediaSource?dy():new MediaSource;const l=document.createElement("source");if(o(l),l.src=URL.createObjectURL(this.source),this.element.appendChild(l),this.tuning.useManagedMediaSource&&pu())if(s){const m=document.createElement("source");o(m),m.type="application/x-mpegurl",m.src=s.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 ko(se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,c),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new ko(se.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(a.interval(ta).subscribe(m=>{var b;if(!((b=this.element)===null||b===void 0)&&b.paused){const S=oo(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P);this.manifestUrlString=we(this.manifestUrlString,S+ta,ie.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...wo.map(m=>a.fromEvent(this.element,m))).pipe(a.map(m=>this.element?Mt(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(m=>!!m),a.tap(m=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(a.filter(b=>this.isActiveLowLatency&&!!b)).subscribe(b=>this.liveEstimatedDelay.next(b))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(b=>{if(!this.isActiveLowLatency)return;const S=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,y=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,T=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,E=b-S;let $=1+Math.sign(E)*T;Math.abs(E)<y?$=1:Math.abs(E)>y*2&&($=1+Math.sign(E)*T*2),uy(this.element,$)})),this.representationSubscription.add(this.bufferLength$.subscribe(b=>{var S,y;let T=0;if(b){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(O=>{var M,F;return(F=(M=O.getLiveSegmentsToLoadState(this.manifest))===null||M===void 0?void 0:M.to)!==null&&F!==void 0?F:0}))-E}T&&this.liveLoadBufferLength$.getValue()!==T&&this.liveLoadBufferLength$.next(T)}));let m=0;this.representationSubscription.add(a.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:b,bufferLength:S})=>H(this,void 0,void 0,function*(){if(a.assertNonNullable(this.element),this.isUpdatingLive)return;const y=this.element.playbackRate,T=oo(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P),E=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,$=Math.min(E,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*y),O=this.tuning.dashCmafLive.normalizedActualBufferOffset*y,M=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*y,F=this.isActiveLowLatency?S:b;let x=_e.None;if(this.isActiveLowLatency?x=_e.ActiveLowLatency:F<$+M&&F>=$?x=_e.LiveWithTargetOffset:T!==0&&F<$&&(x=_e.LiveForwardBuffering),isFinite(b)&&(m=b>m?b:m),x===_e.LiveForwardBuffering||x===_e.LiveWithTargetOffset){const U=m-($+O),G=this.normolizeLiveOffset(Math.trunc(T+U/y)),I=Math.abs(G-T);let P;!b||I<=this.tuning.dashCmafLive.offsetCalculationError?P=T:G>0&&I>this.tuning.dashCmafLive.offsetCalculationError?P=G:P=0,this.manifestUrlString=we(this.manifestUrlString,P,ie.DASH_CMAF_OFFSET_P)}x!==_e.None&&x!==_e.ActiveLowLatency&&(m=0,this.updateLive())})))}const u=a.merge(...this.bufferManagers.map(m=>m.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(m=>m.fullyBuffered$.getValue()))),d=a.merge(...this.bufferManagers.map(m=>m.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(m=>m.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:u,someBufferEnded:d}).pipe(a.filter(({allBuffersFull:m,someBufferEnded:b})=>m&&b))).subscribe(()=>{var m;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(b=>!b.updating))try{(m=this.source)===null||m===void 0||m.endOfStream()}catch(b){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:b})}})),this.representationSubscription.add(a.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 yield C(new Promise(m=>{var b;return(b=this.source)===null||b===void 0?void 0:b.addEventListener("sourceopen",m)})));const h=(n=this.manifest.duration)!==null&&n!==void 0?n:0,f=(m,b)=>{var S;return Math.max(m,(S=b.duration)!==null&&S!==void 0?S:0)},p=this.manifest.representations.audio.reduce(f,h),v=this.manifest.representations.video.reduce(f,h);(p||v)&&(this.source.duration=Math.max(p,v)/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield C(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield C(this.videoBufferManager.startWith(t)),this.state$.setState(be.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new sy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=ia.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,r,s,n;return H(this,void 0,void 0,function*(){a.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=we(this.manifestUrlString,o,ie.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((r=this.manifest)===null||r===void 0?void 0:r.representations.video),yield(s=this.audioBufferManager)===null||s===void 0?void 0:s.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio))})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(be.RUNNING),this.subscription.add(a.merge(...wo.map(e=>a.fromEvent(this.element,e)),a.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:a.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(a.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(a.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Js(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()}switchRepresentation(e,t){return H(this,void 0,void 0,function*(){const r={[se.VIDEO]:this.videoBufferManager,[se.AUDIO]:this.audioBufferManager,[se.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let c;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?c=e:c=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Js(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,r;(e=this.element)===null||e===void 0||e.querySelectorAll("source").forEach(s=>s.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,(r=this.audioBufferManager)===null||r===void 0||r.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(be.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}waitingEventCallback(){return H(this,void 0,void 0,function*(){try{if(!this.element)return;this.isLive$.getValue()?yield this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:a.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return H(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield 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,r=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){const s=Math.max(...r);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(s)&&(this.element.currentTime=s/1e3)}}};class fy{constructor(e,t){this.fov=e,this.orientation=t}}class py{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/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:s,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r: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,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=Object.assign({},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,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var my=`#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;}`,vy=`#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 by{constructor(e,t,r){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new fy(this.params.fov,this.params.orientation),this.cameraRotationManager=new py(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"),r=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(s,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(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(my,this.gl.VERTEX_SHADER),r=this.createShader(vy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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,r=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:r=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),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,r=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,n=e-r,o=t-s,l=e+r,c=t-s,u=e+r,d=t+s,h=e-r,f=t+s;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 Sy=(i,e)=>new a.Observable(t=>{if(!window.IntersectionObserver)return;const r=()=>!!window.documentPictureInPicture.window||!!document.pictureInPictureElement,s={root:null},n=new IntersectionObserver((l,c)=>{l.forEach(u=>t.next(u.isIntersecting||r()))},Object.assign(Object.assign({},s),e));n.observe(i);const o=a.fromEvent(document,"visibilitychange").pipe(a.map(l=>!document.hidden||r())).subscribe(l=>t.next(l));return()=>{n.unobserve(i),o.unsubscribe}});class mu{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(Q.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.elementVisible$=new a.ValueSubject(!0),this.textTracksManager=new Ze,this.droppedFramesManager=new ru,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new oS,this.textTracks=[],this.syncPlayback=()=>{var t,r,s;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===M.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==Q.STOPPED&&o!==exports.PlaybackState.STOPPED){const d=(r=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&r!==void 0?r:0;this.seek(c.position-d,c.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.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(Q.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();return;case Q.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Q.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),(s=this.liveOffset)===null||s===void 0||s.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.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&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var r,s,n;if(this.scene3D)return;this.scene3D=new by(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=t.projectionData)===null||r===void 0?void 0:r.pose.yaw)||0,y:((s=t.projectionData)===null||s===void 0?void 0:s.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=vt(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(Ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,r=gt(this.video),s=this.constructor.name,n=l=>{e.error$.next({id:s,category:a.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:n,connect:(l,c)=>this.subscription.add(l.subscribe(c,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,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$:r.playing$,pause$:r.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:d})=>d)))}),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.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(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(gi(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(qt(this.video,t.playbackRate,r.playbackRateState$,s)),n(kS(this.video),this.elementSize$),n(Sy(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var d;if(u===be.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();a.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((S,y)=>y.bitrate-S.bitrate),v=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=ey(S);y&&this.audioTracks.push({track:y,representation:S})}for(const S of v){const y=Zg(S);if(y){h.push({track:y,representation:S});const E=!this.params.tuning.isAudioDisabled&&ty(p,v,S);E&&this.audioRepresentations.set(S.id,E)}}this.videoTracks$.next(h);for(const S of m){const y=iy(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 b=this.selectVideoRepresentation();a.assertNonNullable(b),this.player.initRepresentations(b.id,(d=this.audioRepresentations.get(b.id))===null||d===void 0?void 0:d.id,this.params.sourceHls)}else u===be.REPRESENTATIOS_READY&&(this.videoState.setState(Q.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),d=this.player.state$.getTransition();if(u!==be.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(),v=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",N=Math.min(T,$)+"p";return a.isLowerOrEqual(x,N)&&a.isLowerOrEqual(x,v)}).map(S=>S.id)[0]),this.player.switchRepresentation(se.VIDEO,m).catch(o);const b=this.audioRepresentations.get(h.id);b&&this.player.switchRepresentation(se.AUDIO,b.id).catch(o)}},s)),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(a.filterChanged(),a.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$,s)),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)},s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const c=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,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=Mt(this.video.buffered,this.video.currentTime*1e3),p=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!c&&(s=(r=this.audioRepresentations.get(d.id))===null||r===void 0?void 0:r.bitrate)!==null&&s!==void 0?s:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),b=Sr(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:v,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=c?b!=null?b:d:d!=null?d:b;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(){yt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.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),bt(this.video)}}class gy extends mu{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class yy extends mu{constructor(e){super(e),this.liveOffset=new Ca}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(ta),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()===Q.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(s-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===Q.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,s)})}}const Re={};var B;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const ei=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Ty{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(B.INITIALIZING),this.textTracksManager=new Ze,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==B.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===M.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case B.STOPPED:break;case B.READY:case B.PLAYING:case B.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case B.STOPPED:this.prepare();break;case B.READY:case B.PLAYING:case B.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case B.PLAYING:break;case B.STOPPED:this.prepare();break;case B.READY:case B.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case B.PAUSED:break;case B.STOPPED:this.prepare();break;case B.READY:this.videoState.setState(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case B.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=vt(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(Ne(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),bt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Pa(import("hls.js").then(s=>{e||(Re.Hls=s.default,Re.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Re.Hls,"hls.js not loaded"),this.hls=new Re.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(B.STOPPED)}subscribe(){a.assertNonNullable(Re.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=gt(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(gi(this.video,e.isLooped,r)),this.subscription.add(St(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qt(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(ei(this.hls,Re.Events.ERROR).subscribe(u=>{var d;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.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(s.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===B.READY&&this.videoState.setState(B.READY),this.videoState.getState()===B.PLAYING&&this.playIfAllowed()},r)),n(ei(this.hls,Re.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((d,h)=>{var f,p;const v=h.name||h.height.toString(10),{width:m,height:b}=h,S=(p=br((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:m,height:b});if(!S)return d;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,E={id:v.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:m,height:b},fps:y};return this.trackLevels.set(v,{track:E,level:h}),d.push(E),d},[]))),t.availableVideoTracks$),n(ei(this.hls,Re.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||"",v=h.lang,m="internal";d.push({id:f,url:p,language:v,type:m})}e.internalTextTracks.startTransitionTo(d)}}),n(ei(this.hls,Re.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>Ne(u))),t.hostname$),this.subscription.add(Ve(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||d===void 0?void 0:d.track},l=ei(this.hls,Re.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ve(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var d;if(a.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,v=this.hls.levels[p];!v||h.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(B.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return H(this,void 0,void 0,function*(){this.videoState.startTransitionTo(B.PLAYING),(yield yt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(B.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(B.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Po="X-Playback-Duration";var Ao=i=>H(void 0,void 0,void 0,function*(){var e;const t=yield ui(i),r=yield t.text(),s=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(r))===null||e===void 0?void 0:e[1];return s?parseInt(s,10):t.headers.has(Po)?parseInt(t.headers.get(Po),10):void 0});const Ey=i=>{let e=null;if(i.QUALITY&&(e=br(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=a.videoSizeToQuality({width:t,height:r})}return e!=null?e:null},$y=(i,e)=>{var t,r;const s=i.split(`
|
|
46
|
-
`),n=[],o=[];for(let l=0;l<s.length;l++){const c=s[l],u=c.match(/^#EXT-X-STREAM-INF:(.+)/),d=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!d)){if(u){const h=er(u[1].split(",").map(y=>y.split("="))),f=(t=h.QUALITY)!==null&&t!==void 0?t:`stream-${h.BANDWIDTH}`,p=Ey(h);let v;h.BANDWIDTH&&(v=parseInt(h.BANDWIDTH,10)/1e3||void 0),!v&&h["AVERAGE-BANDWIDTH"]&&(v=parseInt(h["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=h["FRAME-RATE"]?parseFloat(h["FRAME-RATE"]):void 0;let b;if(h.RESOLUTION){const[y,E]=h.RESOLUTION.split("x").map(T=>parseInt(T,10));y&&E&&(b={width:y,height:E})}const S=new URL(s[++l],e).toString();p&&n.push({id:f,quality:p,url:S,bandwidth:v,size:b,fps:m})}if(d){const h=er(d[1].split(",").map(m=>m.split("=")).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),f=(r=h.URI)===null||r===void 0?void 0:r.replace(/playlist$/,"subtitles.vtt"),p=h.LANGUAGE,v=h.NAME;f&&p&&o.push({type:"internal",id:p,label:v,language:p,url:f,isAuto:!1})}}}if(!n.length)throw new Error("Empty manifest");return{qualityManifests:n,textTracks:o}},ky=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Ss=0;const La=(i,e=i,t)=>H(void 0,void 0,void 0,function*(){const s=yield(yield ui(i)).text();Ss+=1;try{const{qualityManifests:n,textTracks:o}=$y(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Ss<=t.manifestRetryMaxCount)return yield ky(a.getExponentialDelay(Ss-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),La(i,e,t)}return{qualityManifests:[],textTracks:[]}});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class wy{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new X(Y.STOPPED),this.textTracksManager=new Ze,this.manifests$=new a.ValueSubject([]),this.liveOffset=new Ca,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=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){s!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||c||u){const f=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===M.None&&this.params.desiredState.seekState.setState({state:M.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===M.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(Y.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);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&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},La(we(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:a.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,r,s;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(s=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(r=o.getState())===null||r===void 0?void 0:r.id)!==null&&s!==void 0?s:"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,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=gt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(St(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qt(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.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(Ne(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from===Y.CHANGING_MANIFEST&&this.videoState.setState(c.to),l&&l.state===M.Requested&&this.seek(l.position)},r)),this.subscription.add(s.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)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:c})=>this.params.output.liveTime$.next(l+c*1e3),r)),this.subscription.add(this.manifests$.pipe(a.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$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const r=this.selectManifest();if(a.isNullable(r))return;const s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(r.url);if((s||n)&&r.id===this.masterManifest.id){const{max:u,min:d}=(t=(e=s==null?void 0:s.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?ie.DASH_CMAF_OFFSET_P:ie.OFFSET_P,c=we(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",c),this.video.load(),Ao(c).then(u=>{var d;if(!a.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(d=this.params.source.maxSeekBackTime)!==null&&d!==void 0?d:this.maxSeekBackTime$.getValue();if(a.isNullable(h)||!isFinite(h))try{ui(c).then(f=>f.text()).then(f=>{var p;const v=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(v){const m=new URL(v,c).toString();Ao(m).then(b=>{a.isNullable(b)||this.maxSeekBackTime$.next(b)})}})}catch(f){}}})}playIfAllowed(){yt(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class Py{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(W.STOPPED),this.textTracksManager=new Ze,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(s===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(r===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l||c){const h=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),d.state===M.None&&this.params.desiredState.seekState.setState({state:M.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&d.state===M.Requested&&this.seek(d.position),r){case W.READY:s===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.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(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),La(we(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,r,s;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(s=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(r=o.getState())===null||r===void 0?void 0:r.id)!==null&&s!==void 0?s:"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,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=gt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c));if(n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gi(this.video,t.isLooped,r)),this.subscription.add(St(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qt(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{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&&a.isNonNullable(d.to)){const f=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const p=this.manifests$.getValue().find(v=>v.id===f);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Ne(p.url));const v=this.params.desiredState.playbackRate.getState(),m=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(v!==m){const b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(v),b.playbackRate=v)}}}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),u&&u.from===W.CHANGING_MANIFEST&&this.videoState.setState(u.to),c.state===M.Requested&&this.seek(c.position)},r))),this.subscription.add(this.manifests$.pipe(a.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$,r)),!a.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(a.merge(a.fromEvent(l,"addtrack"),a.fromEvent(l,"removetrack"),a.fromEvent(l,"change"),a.observableFrom(["init"])).subscribe(()=>{for(let c=0;c<l.length;c++)l[c].mode="hidden"},r))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const r=this.selectManifest();if(a.isNullable(r))return;const s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(r.url);if((s||n)&&r.id===this.masterManifest.id){const{max:l,min:c}=(t=(e=s==null?void 0:s.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(){yt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var J;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));class Ay{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(J.STOPPED),this.trackUrls={},this.textTracksManager=new Ze,this.syncPlayback=()=>{var t,r,s;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==J.STOPPED&&(this.videoState.startTransitionTo(J.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(J.STOPPED),A(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!==J.READY&&!d){this.handleQualityLimitTransition(u.to.max);return}if(n===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(d){const{currentTime:f}=this.video;this.prepare(),h.state===M.None&&this.params.desiredState.seekState.setState({state:M.Requested,position:f*1e3,forcePrecise:!0}),d.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((s=(r=this.trackUrls[d.to.id])===null||r===void 0?void 0:r.track)===null||s===void 0?void 0:s.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===M.Requested&&this.seek(h.position),n){case J.READY:o===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),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,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=gt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gi(this.video,t.isLooped,r)),this.subscription.add(St(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qt(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l,c;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===J.READY&&this.videoState.setState(J.READY);const u=this.params.desiredState.videoTrack.getTransition();if(u&&a.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()===J.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;a.assertNonNullable(t,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[t];a.assertNonNullable(r,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(r=ea(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ne(r))}playIfAllowed(){yt(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,r,s,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const c=(r=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||r===void 0?void 0:r.track,u=(s=this.params.desiredState.videoTrack.getState())===null||s===void 0?void 0:s.id,d=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(c&&d&&a.isHigherOrEqual(d.quality,c.quality)&&(o=c),!o){const h=Object.values(this.trackUrls).filter(p=>!a.isInvariantQuality(p.track.quality)&&a.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=Sr(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 Co=["stun:videostun.mycdn.me:80"],Cy=1e3,Iy=3,gs=()=>null;class Ry{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=gs,this.externalStopCallback=gs,this.externalErrorCallback=gs,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return H(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return H(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Co}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return H(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return H(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return H(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return H(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Cy)}normalizeOptions(e={}){const t={stunServerList:Co,maxRetryNumber:Iy,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class _y{constructor(e){this.videoState=new X(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=vt(e.container),this.liveStreamClient=new Ry(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),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=gt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===q.READY&&this.videoState.setState(q.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(St(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ne(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:a.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){yt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Io{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 ys,Ts,Es,$s,Ui,ks,ji,ws,Hi,Ps,Gi,As,Yi,Cs,qi,Is;const vu=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Ke=document.createElement("video"),Dy='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ly='video/mp4; codecs="hev1.1.6.L93.B0"',bu='video/webm; codecs="vp09.00.10.08"',Su='video/webm; codecs="av01.0.00M.08"',xy='audio/mp4; codecs="mp4a.40.2"',Ny='audio/webm; codecs="opus"',lt={mms:pu(),mse:cy(),hls:!!(!((ys=Ke.canPlayType)===null||ys===void 0)&&ys.call(Ke,"application/x-mpegurl")||!((Ts=Ke.canPlayType)===null||Ts===void 0)&&Ts.call(Ke,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ve={mp4:!!(!((Es=Ke.canPlayType)===null||Es===void 0)&&Es.call(Ke,"video/mp4")),webm:!!(!(($s=Ke.canPlayType)===null||$s===void 0)&&$s.call(Ke,"video/webm")),cmaf:!0},xe={h264:!!(!((ks=(Ui=ot())===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||ks===void 0)&&ks.call(Ui,Dy)),h265:!!(!((ws=(ji=ot())===null||ji===void 0?void 0:ji.isTypeSupported)===null||ws===void 0)&&ws.call(ji,Ly)),vp9:!!(!((Ps=(Hi=ot())===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||Ps===void 0)&&Ps.call(Hi,bu)),av1:!!(!((As=(Gi=ot())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||As===void 0)&&As.call(Gi,Su)),aac:!!(!((Cs=(Yi=ot())===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||Cs===void 0)&&Cs.call(Yi,xy)),opus:!!(!((Is=(qi=ot())===null||qi===void 0?void 0:qi.isTypeSupported)===null||Is===void 0)&&Is.call(qi,Ny))},ti=(xe.h264||xe.h265)&&xe.aac;var Qe;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Qe||(Qe={}));var je;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(je||(je={}));let ut;const Oy=()=>H(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Su})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:bu})}))]);ut={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{Oy()}catch(i){console.error(i)}const ci=lt.hls&&ve.mp4,My=()=>Object.keys(xe).filter(i=>xe[i]),By=(i,e=!1,t=!1)=>{const r=lt.mse||lt.mms&&t;return i.filter(s=>{switch(s){case exports.VideoFormat.DASH_SEP:return r&&ve.mp4&&ti;case exports.VideoFormat.DASH_WEBM:return r&&ve.webm&&xe.vp9&&xe.opus;case exports.VideoFormat.DASH_WEBM_AV1:return r&&ve.webm&&xe.av1&&xe.opus;case exports.VideoFormat.DASH_LIVE:return lt.mse&&ve.mp4&&ti;case exports.VideoFormat.DASH_LIVE_CMAF:return r&&ve.mp4&&ti&&ve.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return r&&ve.mp4&&ti;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ci||e&<.mse&&ve.mp4&&ti;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ci;case exports.VideoFormat.MPEG:return ve.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return lt.webrtc&<.ws&&xe.h264&&(ve.mp4||ve.webm);default:return a.assertNever(s)}})},ii=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case Qe.VP9:return[e,t];case Qe.AV1:return[t,e];case Qe.NONE:return[];case Qe.SMOOTH:return ut?ut[t].smooth?[t,e]:ut[e].smooth?[e,t]:[t,e]:[e,t];case Qe.POWER_EFFICIENT:return ut?ut[t].powerEfficient?[t,e]:ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(i)}return[e,t]},Vy=({webmCodec:i,androidPreferredFormat:e})=>{if(vu)switch(e){case je.MPEG:return[exports.VideoFormat.MPEG,...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case je.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case je.DASH:return[...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return ci?[...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Fy=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const r=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],s=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...r,...s],o=[...s,...r];let l;if(vu)switch(i){case je.DASH:{l=n;break}case je.HLS:case je.MPEG:{l=o;break}}else ci?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},Ro=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 Uy=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:d})=>`${u}-${d}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,c="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),c=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.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 jy={chunkDuration:5e3,maxParallelRequests:5};class Hy{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),autoVideoTrackLimits$:new a.ValueSubject(void 0),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,warning$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),isLowLatency$:new a.ValueSubject(!1),canChangePlaybackSpeed$:new a.ValueSubject(!0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=By([...Fy(this.params.tuning),...Vy(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:r,formatsToAvoid:s}=this.params.tuning;let n=[];r?n=[r]:s.length?n=[...t.filter(l=>!s.includes(l)),...t.filter(l=>s.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Io(n);const o=[...Ro(!0),...Ro(!1)];this.chromecastFormatsIterator=new Io(o.filter(l=>a.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(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.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,r=this.params.desiredState.seekState.getState(),s=r.state!==M.None;if(this.params.desiredState.seekState.setState({state:M.Requested,position:s?r.position:t,forcePrecise:s?r.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 oe.SCREEN:return this.createScreenProvider(t);case oe.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH_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 a.assertNonNullable(l),new gy(Object.assign(Object.assign({},o),{source:l,sourceHls:c}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new yy(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),ci||!this.params.tuning.useHlsJs?new Py(Object.assign(Object.assign({},o),{source:l})):new Ty(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new wy(Object.assign(Object.assign({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Ay(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new ES(Object.assign(Object.assign({},o),{source:l,config:Object.assign(Object.assign({},jy),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new _y({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Bb({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?oe.CHROMECAST:oe.SCREEN}chooseFormat(e){switch(e){case oe.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case oe.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case oe.SCREEN:return this.screenFormatsIterator.next();case oe.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case oe.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case oe.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:r(e.url)})}return er(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Uy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const n=this.current$.getValue().destination;if(n===oe.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(oe.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=s.category===a.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit;l&&(o&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(r++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:oe.SCREEN)}})),e}}const Gy=5e3,_o="one_video_throughput",Do="one_video_rtt",He=window.navigator.connection,Lo=()=>{const i=He==null?void 0:He.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},xo=()=>{const i=He==null?void 0:He.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},No=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ni{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ni.load(_o)||(e.useBrowserEstimation?Lo():void 0)||Gy,n=(r=(t=ni.load(Do))!==null&&t!==void 0?t:e.useBrowserEstimation?xo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(No(s,n,e.rttPenaltyRequestSize)),this.throughput=ia.getSmoothedValue(s,-1,e),this.rtt=ia.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const c=Lo();c&&this.throughput.next(c);const u=xo();a.isNonNullable(u)&&this.rtt.next(u)};He&&"onchange"in He&&this.subscription.add(a.fromEvent(He,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(_o,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(Do,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>No(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),c=o-t,u=l-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const r=e.getReader();if(!r){e.cancel("Could not get reader");return}let s=0,n=a.now(),o=0,l=a.now();const c=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=({done:d,value:h})=>H(this,void 0,void 0,function*(){if(d)!t&&this.addRawSpeed(s,a.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(a.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=a.now()}l=a.now()}else s+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&a.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,a.now()-l,this.concurrentDownloads.size),o=0,l=a.now());yield r==null?void 0:r.read().then(u,c)}});this.concurrentDownloads.add(e),r==null||r.read().then(u,c)}addRawSpeed(e,t,r=1,s=!1){if(ni.sanityCheck(e,t,s)){const n=e*8/t;this.throughput.next(n*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var t;const r=a.safeStorage.get(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const Oo={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:a.VideoQuality.Q_480P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:a.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:Qe.VP9,androidPreferredFormat:je.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}},Yy=i=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(i,Oo)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Oo.configName]})};var Mo=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===M.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===M.None))),qy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const zy=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(a.filter(s=>s.length>0),a.once()).subscribe(s=>{s.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};class Wy{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new X(exports.PlaybackState.STOPPED),seekState:new X({state:M.None}),volume:new X({volume:1,muted:!1}),videoTrack:new X(void 0),autoVideoTrackSwitching:new X(!0),autoVideoTrackLimits:new X({}),isLooped:new X(!1),playbackRate:new X(1),externalTextTracks:new X([]),internalTextTracks:new X([]),currentTextTrack:new X(void 0),textTrackCuesSettings:new X({}),cameraOrientation:new X({x:0,y:0})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),canChangePlaybackSpeed$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),atLiveDurationEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:sS},this.initLogs(),this.tuning=Yy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new qu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ni(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const c=o.map(h=>JSON.stringify(h,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(r)}`,d=`Exception calling ${u} (${c.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:d,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=qy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Hy({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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?a.fromEvent(document,"visibilitychange").pipe(a.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 r=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=r&&!s&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:M.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){a.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(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setVideoTrackIdByQuality(r,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;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return zy(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,r=>r.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 r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const r=this.getScene3D();if(r){const s=r.getCameraRotation(),n=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.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(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===M.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const r=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=r==null?void 0:r.provider)===null||t===void 0)&&t.scene3D)return r.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.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===M.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:M.Applying})):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===M.Applying&&(this.desiredState.seekState.setState({state:M.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:l})=>l).sort((l,c)=>a.isInvariantQuality(l)?1:a.isInvariantQuality(c)?-1:a.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(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(a.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(a.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(a.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}),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(a.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(a.map(({isLive:o,position:l,duration:c})=>o&&(Math.abs(c)-Math.abs(l))*1e3<this.tuning.live.activeLiveDelay),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Mo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.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(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||r.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(a.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(a.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(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var t;let r;const s=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;s&&(r=e.find(({quality:n})=>n===s),r||this.setAutoQuality(!0)),r||(r=Sr(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(r),this.info.currentQuality$.next(r.quality),this.info.videoBitrate$.next(r.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),rS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>iS(r)),this.providerContainer.current$.subscribe(({type:r})=>Vi("provider",r)),t.duration$.subscribe(r=>Vi("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Vi("tracks",r)),this.events.fatalError$.subscribe(new De("fatalError")),this.events.managedError$.subscribe(new De("managedError")),t.position$.subscribe(new De("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new De("quality")),this.info.currentBuffer$.subscribe(new De("buffer")),t.isBuffering$.subscribe(new De("isBuffering"))].forEach(r=>this.subscription.add(r)),Vi("codecs",My())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>H(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const r=e.find(s=>s.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}}const Qy=`@vkontakte/videoplayer-core@${Bo}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return a.VideoQuality}});exports.Player=Wy;exports.SDK_VERSION=Qy;exports.VERSION=Bo;
|
|
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 by{constructor(e,t,r){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new fy(this.params.fov,this.params.orientation),this.cameraRotationManager=new py(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"),r=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),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(r,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(s,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(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(my,this.gl.VERTEX_SHADER),r=this.createShader(vy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),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,r=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:r=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),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,r=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,n=e-r,o=t-s,l=e+r,c=t-s,u=e+r,d=t+s,h=e-r,f=t+s;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 Sy=(i,e)=>new a.Observable(t=>{if(!window.IntersectionObserver)return;const r=()=>{var l;return!!(!((l=window.documentPictureInPicture)===null||l===void 0)&&l.window)||!!document.pictureInPictureElement},s={root:null},n=new IntersectionObserver((l,c)=>{l.forEach(u=>t.next(u.isIntersecting||r()))},Object.assign(Object.assign({},s),e));n.observe(i);const o=a.fromEvent(document,"visibilitychange").pipe(a.map(l=>!document.hidden||r())).subscribe(l=>t.next(l));return()=>{n.unobserve(i),o.unsubscribe}});class mu{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(Q.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.elementVisible$=new a.ValueSubject(!0),this.textTracksManager=new Ze,this.droppedFramesManager=new ru,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new oS,this.textTracks=[],this.syncPlayback=()=>{var t,r,s;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===N.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==Q.STOPPED&&o!==exports.PlaybackState.STOPPED){const d=(r=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&r!==void 0?r:0;this.seek(c.position-d,c.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.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(Q.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case Q.STOPPED:this.videoState.startTransitionTo(Q.READY),this.prepare();return;case Q.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Q.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),(s=this.liveOffset)===null||s===void 0||s.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.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&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var r,s,n;if(this.scene3D)return;this.scene3D=new by(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=t.projectionData)===null||r===void 0?void 0:r.pose.yaw)||0,y:((s=t.projectionData)===null||s===void 0?void 0:s.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=vt(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(Ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,r=gt(this.video),s=this.constructor.name,n=l=>{e.error$.next({id:s,category:a.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:n,connect:(l,c)=>this.subscription.add(l.subscribe(c,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,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$:r.playing$,pause$:r.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:d})=>d)))}),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.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(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(gi(this.video,t.isLooped,s)),this.subscription.add(St(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(qt(this.video,t.playbackRate,r.playbackRateState$,s)),n(kS(this.video),this.elementSize$),n(Sy(this.video,{threshold:this.params.tuning.autoTrackSelection.activeVideoAreaThreshold}),this.elementVisible$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var d;if(u===be.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();a.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((S,y)=>y.bitrate-S.bitrate),v=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=ey(S);y&&this.audioTracks.push({track:y,representation:S})}for(const S of v){const y=Zg(S);if(y){h.push({track:y,representation:S});const T=!this.params.tuning.isAudioDisabled&&ty(p,v,S);T&&this.audioRepresentations.set(S.id,T)}}this.videoTracks$.next(h);for(const S of m){const y=iy(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 b=this.selectVideoRepresentation();a.assertNonNullable(b),this.player.initRepresentations(b.id,(d=this.audioRepresentations.get(b.id))===null||d===void 0?void 0:d.id,this.params.sourceHls)}else u===be.REPRESENTATIOS_READY&&(this.videoState.setState(Q.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.elementVisible$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),d=this.player.state$.getTransition();if(u!==be.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(),v=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=a.videoSizeToQuality(S),T=a.videoSizeToQuality(h);if(y&&T)return a.isLowerOrEqual(y,T)&&a.isLowerOrEqual(y,v)}).map(S=>S.id)[0]),this.player.switchRepresentation(se.VIDEO,m).catch(o);const b=this.audioRepresentations.get(h.id);b&&this.player.switchRepresentation(se.AUDIO,b.id).catch(o)}},s)),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(a.filterChanged(),a.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$,s)),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)},s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const c=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,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=Mt(this.video.buffered,this.video.currentTime*1e3),p=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,v=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(d&&!c&&(s=(r=this.audioRepresentations.get(d.id))===null||r===void 0?void 0:r.bitrate)!==null&&s!==void 0?s:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),b=Sr(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:v,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),S=c?b!=null?b:d:d!=null?d:b;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(){yt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.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),bt(this.video)}}class gy extends mu{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class yy extends mu{constructor(e){super(e),this.liveOffset=new Ca}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(ta),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()===Q.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(s-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===Q.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,s)})}}const Re={};var B;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const ei=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Ty{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(B.INITIALIZING),this.textTracksManager=new Ze,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==B.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case B.STOPPED:break;case B.READY:case B.PLAYING:case B.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case B.STOPPED:this.prepare();break;case B.READY:case B.PLAYING:case B.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case B.PLAYING:break;case B.STOPPED:this.prepare();break;case B.READY:case B.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case B.PAUSED:break;case B.STOPPED:this.prepare();break;case B.READY:this.videoState.setState(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case B.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=vt(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(Ne(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),bt(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Pa(import("hls.js").then(s=>{e||(Re.Hls=s.default,Re.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Re.Hls,"hls.js not loaded"),this.hls=new Re.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(B.STOPPED)}subscribe(){a.assertNonNullable(Re.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=gt(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(gi(this.video,e.isLooped,r)),this.subscription.add(St(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qt(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(ei(this.hls,Re.Events.ERROR).subscribe(u=>{var d;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.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(s.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===B.READY&&this.videoState.setState(B.READY),this.videoState.getState()===B.PLAYING&&this.playIfAllowed()},r)),n(ei(this.hls,Re.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((d,h)=>{var f,p;const v=h.name||h.height.toString(10),{width:m,height:b}=h,S=(p=br((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:m,height:b});if(!S)return d;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,T={id:v.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:m,height:b},fps:y};return this.trackLevels.set(v,{track:T,level:h}),d.push(T),d},[]))),t.availableVideoTracks$),n(ei(this.hls,Re.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||"",v=h.lang,m="internal";d.push({id:f,url:p,language:v,type:m})}e.internalTextTracks.startTransitionTo(d)}}),n(ei(this.hls,Re.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>Ne(u))),t.hostname$),this.subscription.add(Ve(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||d===void 0?void 0:d.track},l=ei(this.hls,Re.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Ve(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var d;if(a.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,v=this.hls.levels[p];!v||h.bitrate>v.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(B.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return H(this,void 0,void 0,function*(){this.videoState.startTransitionTo(B.PLAYING),(yield yt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(B.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(B.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Po="X-Playback-Duration";var Ao=i=>H(void 0,void 0,void 0,function*(){var e;const t=yield ui(i),r=yield t.text(),s=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(r))===null||e===void 0?void 0:e[1];return s?parseInt(s,10):t.headers.has(Po)?parseInt(t.headers.get(Po),10):void 0});const Ey=i=>{let e=null;if(i.QUALITY&&(e=br(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=a.videoSizeToQuality({width:t,height:r})}return e!=null?e:null},$y=(i,e)=>{var t,r;const s=i.split(`
|
|
46
|
+
`),n=[],o=[];for(let l=0;l<s.length;l++){const c=s[l],u=c.match(/^#EXT-X-STREAM-INF:(.+)/),d=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!u&&!d)){if(u){const h=er(u[1].split(",").map(y=>y.split("="))),f=(t=h.QUALITY)!==null&&t!==void 0?t:`stream-${h.BANDWIDTH}`,p=Ey(h);let v;h.BANDWIDTH&&(v=parseInt(h.BANDWIDTH,10)/1e3||void 0),!v&&h["AVERAGE-BANDWIDTH"]&&(v=parseInt(h["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=h["FRAME-RATE"]?parseFloat(h["FRAME-RATE"]):void 0;let b;if(h.RESOLUTION){const[y,T]=h.RESOLUTION.split("x").map(E=>parseInt(E,10));y&&T&&(b={width:y,height:T})}const S=new URL(s[++l],e).toString();p&&n.push({id:f,quality:p,url:S,bandwidth:v,size:b,fps:m})}if(d){const h=er(d[1].split(",").map(m=>m.split("=")).map(([m,b])=>[m,b.replace(/^"|"$/g,"")])),f=(r=h.URI)===null||r===void 0?void 0:r.replace(/playlist$/,"subtitles.vtt"),p=h.LANGUAGE,v=h.NAME;f&&p&&o.push({type:"internal",id:p,label:v,language:p,url:f,isAuto:!1})}}}if(!n.length)throw new Error("Empty manifest");return{qualityManifests:n,textTracks:o}},ky=i=>new Promise(e=>{setTimeout(()=>{e()},i)});let Ss=0;const La=(i,e=i,t)=>H(void 0,void 0,void 0,function*(){const s=yield(yield ui(i)).text();Ss+=1;try{const{qualityManifests:n,textTracks:o}=$y(s,e);return{qualityManifests:n,textTracks:o}}catch(n){if(Ss<=t.manifestRetryMaxCount)return yield ky(a.getExponentialDelay(Ss-1,{start:t.manifestRetryInterval,max:t.manifestRetryMaxInterval})),La(i,e,t)}return{qualityManifests:[],textTracks:[]}});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class wy{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new X(Y.STOPPED),this.textTracksManager=new Ze,this.manifests$=new a.ValueSubject([]),this.liveOffset=new Ca,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=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){s!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||c||u){const f=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===N.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(Y.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);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&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},La(we(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:r})=>{r.length===0&&this.params.output.error$.next({id:"HlsLiveProviderInternal:empty_manifest",category:a.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"}),this.manifests$.next([this.masterManifest,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(Ne(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,r,s;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(s=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(r=o.getState())===null||r===void 0?void 0:r.id)!==null&&s!==void 0?s:"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,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=gt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(St(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qt(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.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(Ne(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from===Y.CHANGING_MANIFEST&&this.videoState.setState(c.to),l&&l.state===N.Requested&&this.seek(l.position)},r)),this.subscription.add(s.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)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:c})=>this.params.output.liveTime$.next(l+c*1e3),r)),this.subscription.add(this.manifests$.pipe(a.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$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const r=this.selectManifest();if(a.isNullable(r))return;const s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(r.url);if((s||n)&&r.id===this.masterManifest.id){const{max:u,min:d}=(t=(e=s==null?void 0:s.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?ie.DASH_CMAF_OFFSET_P:ie.OFFSET_P,c=we(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",c),this.video.load(),Ao(c).then(u=>{var d;if(!a.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(d=this.params.source.maxSeekBackTime)!==null&&d!==void 0?d:this.maxSeekBackTime$.getValue();if(a.isNullable(h)||!isFinite(h))try{ui(c).then(f=>f.text()).then(f=>{var p;const v=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(v){const m=new URL(v,c).toString();Ao(m).then(b=>{a.isNullable(b)||this.maxSeekBackTime$.next(b)})}})}catch(f){}}})}playIfAllowed(){yt(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class Py{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(W.STOPPED),this.textTracksManager=new Ze,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),c=this.params.desiredState.autoVideoTrackLimits.getTransition();if(s===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const d=this.params.desiredState.seekState.getState();if(r===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l||c){const h=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),c&&this.params.output.autoVideoTrackLimits$.next(c.to),d.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&d.state===N.Requested&&this.seek(d.position),r){case W.READY:s===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.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(Ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),La(we(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:r})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(r)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,r,s;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),c=o.getTransition(),u=(s=(t=(e=c==null?void 0:c.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(r=o.getState())===null||r===void 0?void 0:r.id)!==null&&s!==void 0?s:"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,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=gt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c));if(n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gi(this.video,t.isLooped,r)),this.subscription.add(St(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qt(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{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&&a.isNonNullable(d.to)){const f=d.to.id;this.params.desiredState.videoTrack.setState(d.to);const p=this.manifests$.getValue().find(v=>v.id===f);if(p){this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(Ne(p.url));const v=this.params.desiredState.playbackRate.getState(),m=(l=this.params.output.element$.getValue())===null||l===void 0?void 0:l.playbackRate;if(v!==m){const b=this.params.output.element$.getValue();b&&(this.params.desiredState.playbackRate.setState(v),b.playbackRate=v)}}}h&&this.params.desiredState.autoVideoTrackSwitching.setState(h.to),u&&u.from===W.CHANGING_MANIFEST&&this.videoState.setState(u.to),c.state===N.Requested&&this.seek(c.position)},r))),this.subscription.add(this.manifests$.pipe(a.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$,r)),!a.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(a.merge(a.fromEvent(l,"addtrack"),a.fromEvent(l,"removetrack"),a.fromEvent(l,"change"),a.observableFrom(["init"])).subscribe(()=>{for(let c=0;c<l.length;c++)l[c].mode="hidden"},r))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const r=this.selectManifest();if(a.isNullable(r))return;const s=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(r.url);if((s||n)&&r.id===this.masterManifest.id){const{max:l,min:c}=(t=(e=s==null?void 0:s.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(){yt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var J;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(J||(J={}));class Ay{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(J.STOPPED),this.trackUrls={},this.textTracksManager=new Ze,this.syncPlayback=()=>{var t,r,s;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==J.STOPPED&&(this.videoState.startTransitionTo(J.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(J.STOPPED),A(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!==J.READY&&!d){this.handleQualityLimitTransition(u.to.max);return}if(n===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(d){const{currentTime:f}=this.video;this.prepare(),h.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:f*1e3,forcePrecise:!0}),d.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((s=(r=this.trackUrls[d.to.id])===null||r===void 0?void 0:r.track)===null||s===void 0?void 0:s.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===N.Requested&&this.seek(h.position),n){case J.READY:o===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=vt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),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,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=gt(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gi(this.video,t.isLooped,r)),this.subscription.add(St(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(qt(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l,c;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===J.READY&&this.videoState.setState(J.READY);const u=this.params.desiredState.videoTrack.getTransition();if(u&&a.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()===J.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;a.assertNonNullable(t,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[t];a.assertNonNullable(r,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(r=ea(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(Ne(r))}playIfAllowed(){yt(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,r,s,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const c=(r=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||r===void 0?void 0:r.track,u=(s=this.params.desiredState.videoTrack.getState())===null||s===void 0?void 0:s.id,d=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(c&&d&&a.isHigherOrEqual(d.quality,c.quality)&&(o=c),!o){const h=Object.values(this.trackUrls).filter(p=>!a.isInvariantQuality(p.track.quality)&&a.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=Sr(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 Co=["stun:videostun.mycdn.me:80"],Cy=1e3,Iy=3,gs=()=>null;class Ry{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=gs,this.externalStopCallback=gs,this.externalErrorCallback=gs,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return H(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return H(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Co}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return H(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return H(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return H(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return H(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Cy)}normalizeOptions(e={}){const t={stunServerList:Co,maxRetryNumber:Iy,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class _y{constructor(e){this.videoState=new X(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=vt(e.container),this.liveStreamClient=new Ry(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),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=gt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===q.READY&&this.videoState.setState(q.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(St(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(Ne(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:a.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){yt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Io{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 ys,Ts,Es,$s,Ui,ks,ji,ws,Hi,Ps,Gi,As,Yi,Cs,qi,Is;const vu=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Ke=document.createElement("video"),Dy='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ly='video/mp4; codecs="hev1.1.6.L93.B0"',bu='video/webm; codecs="vp09.00.10.08"',Su='video/webm; codecs="av01.0.00M.08"',xy='audio/mp4; codecs="mp4a.40.2"',Ny='audio/webm; codecs="opus"',lt={mms:pu(),mse:cy(),hls:!!(!((ys=Ke.canPlayType)===null||ys===void 0)&&ys.call(Ke,"application/x-mpegurl")||!((Ts=Ke.canPlayType)===null||Ts===void 0)&&Ts.call(Ke,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ve={mp4:!!(!((Es=Ke.canPlayType)===null||Es===void 0)&&Es.call(Ke,"video/mp4")),webm:!!(!(($s=Ke.canPlayType)===null||$s===void 0)&&$s.call(Ke,"video/webm")),cmaf:!0},xe={h264:!!(!((ks=(Ui=ot())===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||ks===void 0)&&ks.call(Ui,Dy)),h265:!!(!((ws=(ji=ot())===null||ji===void 0?void 0:ji.isTypeSupported)===null||ws===void 0)&&ws.call(ji,Ly)),vp9:!!(!((Ps=(Hi=ot())===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||Ps===void 0)&&Ps.call(Hi,bu)),av1:!!(!((As=(Gi=ot())===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||As===void 0)&&As.call(Gi,Su)),aac:!!(!((Cs=(Yi=ot())===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||Cs===void 0)&&Cs.call(Yi,xy)),opus:!!(!((Is=(qi=ot())===null||qi===void 0?void 0:qi.isTypeSupported)===null||Is===void 0)&&Is.call(qi,Ny))},ti=(xe.h264||xe.h265)&&xe.aac;var Qe;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Qe||(Qe={}));var je;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(je||(je={}));let ut;const Oy=()=>H(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Su})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:bu})}))]);ut={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{Oy()}catch(i){console.error(i)}const ci=lt.hls&&ve.mp4,My=()=>Object.keys(xe).filter(i=>xe[i]),By=(i,e=!1,t=!1)=>{const r=lt.mse||lt.mms&&t;return i.filter(s=>{switch(s){case exports.VideoFormat.DASH_SEP:return r&&ve.mp4&&ti;case exports.VideoFormat.DASH_WEBM:return r&&ve.webm&&xe.vp9&&xe.opus;case exports.VideoFormat.DASH_WEBM_AV1:return r&&ve.webm&&xe.av1&&xe.opus;case exports.VideoFormat.DASH_LIVE:return lt.mse&&ve.mp4&&ti;case exports.VideoFormat.DASH_LIVE_CMAF:return r&&ve.mp4&&ti&&ve.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return r&&ve.mp4&&ti;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ci||e&<.mse&&ve.mp4&&ti;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ci;case exports.VideoFormat.MPEG:return ve.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return lt.webrtc&<.ws&&xe.h264&&(ve.mp4||ve.webm);default:return a.assertNever(s)}})},ii=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case Qe.VP9:return[e,t];case Qe.AV1:return[t,e];case Qe.NONE:return[];case Qe.SMOOTH:return ut?ut[t].smooth?[t,e]:ut[e].smooth?[e,t]:[t,e]:[e,t];case Qe.POWER_EFFICIENT:return ut?ut[t].powerEfficient?[t,e]:ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(i)}return[e,t]},Vy=({webmCodec:i,androidPreferredFormat:e})=>{if(vu)switch(e){case je.MPEG:return[exports.VideoFormat.MPEG,...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case je.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case je.DASH:return[...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return ci?[...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]:[...ii(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Fy=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const r=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],s=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...r,...s],o=[...s,...r];let l;if(vu)switch(i){case je.DASH:{l=n;break}case je.HLS:case je.MPEG:{l=o;break}}else ci?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},Ro=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 Uy=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:d})=>`${u}-${d}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,c="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),c=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.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 jy={chunkDuration:5e3,maxParallelRequests:5};class Hy{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),autoVideoTrackLimits$:new a.ValueSubject(void 0),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,warning$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),isLowLatency$:new a.ValueSubject(!1),canChangePlaybackSpeed$:new a.ValueSubject(!0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=By([...Fy(this.params.tuning),...Vy(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:r,formatsToAvoid:s}=this.params.tuning;let n=[];r?n=[r]:s.length?n=[...t.filter(l=>!s.includes(l)),...t.filter(l=>s.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Io(n);const o=[...Ro(!0),...Ro(!1)];this.chromecastFormatsIterator=new Io(o.filter(l=>a.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(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.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,r=this.params.desiredState.seekState.getState(),s=r.state!==N.None;if(this.params.desiredState.seekState.setState({state:N.Requested,position:s?r.position:t,forcePrecise:s?r.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 oe.SCREEN:return this.createScreenProvider(t);case oe.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH_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 a.assertNonNullable(l),new gy(Object.assign(Object.assign({},o),{source:l,sourceHls:c}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new yy(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),ci||!this.params.tuning.useHlsJs?new Py(Object.assign(Object.assign({},o),{source:l})):new Ty(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new wy(Object.assign(Object.assign({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Ay(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new ES(Object.assign(Object.assign({},o),{source:l,config:Object.assign(Object.assign({},jy),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new _y({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Bb({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?oe.CHROMECAST:oe.SCREEN}chooseFormat(e){switch(e){case oe.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case oe.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case oe.SCREEN:return this.screenFormatsIterator.next();case oe.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case oe.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case oe.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:r(e.url)})}return er(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Uy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const n=this.current$.getValue().destination;if(n===oe.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(oe.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=s.category===a.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),c=r<this.params.tuning.providerErrorLimit;l&&(o&&t||!c)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):c?(r++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:oe.SCREEN)}})),e}}const Gy=5e3,_o="one_video_throughput",Do="one_video_rtt",He=window.navigator.connection,Lo=()=>{const i=He==null?void 0:He.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},xo=()=>{const i=He==null?void 0:He.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},No=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ni{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ni.load(_o)||(e.useBrowserEstimation?Lo():void 0)||Gy,n=(r=(t=ni.load(Do))!==null&&t!==void 0?t:e.useBrowserEstimation?xo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(No(s,n,e.rttPenaltyRequestSize)),this.throughput=ia.getSmoothedValue(s,-1,e),this.rtt=ia.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const c=Lo();c&&this.throughput.next(c);const u=xo();a.isNonNullable(u)&&this.rtt.next(u)};He&&"onchange"in He&&this.subscription.add(a.fromEvent(He,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(_o,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(Do,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>No(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),c=o-t,u=l-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e,t=!1){const r=e.getReader();if(!r){e.cancel("Could not get reader");return}let s=0,n=a.now(),o=0,l=a.now();const c=d=>{this.concurrentDownloads.delete(e),r.releaseLock(),e.cancel(`Throughput Estimator error: ${d}`).catch(()=>{})},u=({done:d,value:h})=>H(this,void 0,void 0,function*(){if(d)!t&&this.addRawSpeed(s,a.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(a.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=a.now()}l=a.now()}else s+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&a.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,a.now()-l,this.concurrentDownloads.size),o=0,l=a.now());yield r==null?void 0:r.read().then(u,c)}});this.concurrentDownloads.add(e),r==null||r.read().then(u,c)}addRawSpeed(e,t,r=1,s=!1){if(ni.sanityCheck(e,t,s)){const n=e*8/t;this.throughput.next(n*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,r=!1){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||r&&e<1e4||!r&&e<10*1024||!r&&t<=20)}static load(e){var t;const r=a.safeStorage.get(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const Oo={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:a.VideoQuality.Q_4320P,activeVideoAreaThreshold:.1},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:a.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:Qe.VP9,androidPreferredFormat:je.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}},Yy=i=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(i,Oo)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Oo.configName]})};var Mo=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===N.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===N.None))),qy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const zy=(i,e,t,r)=>{i!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(a.filter(s=>s.length>0),a.once()).subscribe(s=>{s.find(r)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(r))&&e.startTransitionTo(i)};class Wy{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new X(exports.PlaybackState.STOPPED),seekState:new X({state:N.None}),volume:new X({volume:1,muted:!1}),videoTrack:new X(void 0),autoVideoTrackSwitching:new X(!0),autoVideoTrackLimits:new X({}),isLooped:new X(!1),playbackRate:new X(1),externalTextTracks:new X([]),internalTextTracks:new X([]),currentTextTrack:new X(void 0),textTrackCuesSettings:new X({}),cameraOrientation:new X({x:0,y:0})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),canChangePlaybackSpeed$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),atLiveDurationEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:sS},this.initLogs(),this.tuning=Yy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new qu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ni(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const c=o.map(h=>JSON.stringify(h,(f,p)=>{const v=typeof p;return["number","string","boolean"].includes(v)?p:p===null?null:`<${v}>`})),u=`Player.${String(r)}`,d=`Exception calling ${u} (${c.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:d,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=qy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Hy({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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?a.fromEvent(document,"visibilitychange").pipe(a.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 r=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=r&&!s&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:N.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){a.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(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setVideoTrackIdByQuality(r,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;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return zy(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,r=>r.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 r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const r=this.getScene3D();if(r){const s=r.getCameraRotation(),n=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.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(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===N.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const r=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=r==null?void 0:r.provider)===null||t===void 0)&&t.scene3D)return r.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.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===N.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:N.Applying})):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===N.Applying&&(this.desiredState.seekState.setState({state:N.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:l})=>l).sort((l,c)=>a.isInvariantQuality(l)?1:a.isInvariantQuality(c)?-1:a.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(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(a.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(a.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Mo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(a.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}),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(a.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(a.map(({isLive:o,position:l,duration:c})=>o&&(Math.abs(c)-Math.abs(l))*1e3<this.tuning.live.activeLiveDelay),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Mo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.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(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||r.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(a.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(a.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(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){var t;let r;const s=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;s&&(r=e.find(({quality:n})=>n===s),r||this.setAutoQuality(!0)),r||(r=Sr(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(r),this.info.currentQuality$.next(r.quality),this.info.videoBitrate$.next(r.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),rS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>iS(r)),this.providerContainer.current$.subscribe(({type:r})=>Vi("provider",r)),t.duration$.subscribe(r=>Vi("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Vi("tracks",r)),this.events.fatalError$.subscribe(new De("fatalError")),this.events.managedError$.subscribe(new De("managedError")),t.position$.subscribe(new De("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new De("quality")),this.info.currentBuffer$.subscribe(new De("buffer")),t.isBuffering$.subscribe(new De("isBuffering"))].forEach(r=>this.subscription.add(r)),Vi("codecs",My())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>H(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const r=e.find(s=>s.quality===t);r?this.desiredState.videoTrack.startTransitionTo(r):this.setAutoQuality(!0)}}const Qy=`@vkontakte/videoplayer-core@${Bo}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return a.VideoQuality}});exports.Player=Wy;exports.SDK_VERSION=Qy;exports.VERSION=Bo;
|