@vkontakte/videoplayer-core 2.0.95 → 2.0.96
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 +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- 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.96
|
|
3
|
+
* Wed, 13 Dec 2023 12:11:59 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-96/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Fu=Object.create;var Ya=Object.defineProperty;var Uu=Object.getOwnPropertyDescriptor;var ju=Object.getOwnPropertyNames;var Hu=Object.getPrototypeOf,Gu=Object.prototype.hasOwnProperty;var Yu=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ju(e))!Gu.call(i,r)&&r!==t&&Ya(i,r,{get:()=>e[r],enumerable:!(s=Uu(e,r))||s.enumerable});return i};var qa=(i,e,t)=>(t=i!=null?Fu(Hu(i)):{},Yu(e||!i||!i.__esModule?Ya(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),qu=require("lodash/debounce.js");const Fo="2.0.95";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_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 ue;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ue||(ue={}));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 B;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(B||(B={}));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 K(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(s.next(c))}catch(h){o(h)}}function d(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(l,d)}u((s=s.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function be(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){s[f]&&(r[f]=function(p){return new Promise(function(m,b){n.push([f,p,m,b])>1||l(f,p)})})}function l(f,p){try{d(s[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var zu=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Wu{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 s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||zu("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 s,r,n;(n=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.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),s=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([s.getCastState()])).pipe(a.filterChanged(),a.map(Qu),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=s.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Qu=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 Ms=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function cs(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ke=function(i){try{return!!i()}catch(e){return!0}},Ku=ke,hs=!Ku(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Uo=hs,jo=Function.prototype,Lr=jo.call,Ju=Uo&&jo.bind.bind(Lr,Lr),Pe=Uo?Ju:function(i){return function(){return Lr.apply(i,arguments)}},Ho=Pe,Xu=Ho({}.toString),Zu=Ho("".slice),fi=function(i){return Zu(Xu(i),8,-1)},ed=Pe,td=ke,id=fi,Bs=Object,sd=ed("".split),rd=td(function(){return!Bs("z").propertyIsEnumerable(0)})?function(i){return id(i)=="String"?sd(i,""):Bs(i)}:Bs,pi=function(i){return i==null},ad=pi,nd=TypeError,na=function(i){if(ad(i))throw nd("Can't call method on "+i);return i},od=rd,ld=na,mi=function(i){return od(ld(i))},Ht={},Ri=function(i){return i&&i.Math==Math&&i},le=Ri(typeof globalThis=="object"&&globalThis)||Ri(typeof window=="object"&&window)||Ri(typeof self=="object"&&self)||Ri(typeof Ms=="object"&&Ms)||function(){return this}()||Ms||Function("return this")(),Or=typeof document=="object"&&document.all,ud=typeof Or=="undefined"&&Or!==void 0,Go={all:Or,IS_HTMLDDA:ud},Yo=Go,dd=Yo.all,ne=Yo.IS_HTMLDDA?function(i){return typeof i=="function"||i===dd}:function(i){return typeof i=="function"},cd=le,hd=ne,za=cd.WeakMap,fd=hd(za)&&/native code/.test(String(za)),Wa=ne,qo=Go,pd=qo.all,ze=qo.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Wa(i)||i===pd}:function(i){return typeof i=="object"?i!==null:Wa(i)},md=ke,nt=!md(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),St={},vd=le,Qa=ze,Mr=vd.document,bd=Qa(Mr)&&Qa(Mr.createElement),oa=function(i){return bd?Mr.createElement(i):{}},Sd=nt,gd=ke,yd=oa,zo=!Sd&&!gd(function(){return Object.defineProperty(yd("div"),"a",{get:function(){return 7}}).a!=7}),Td=nt,Ed=ke,Wo=Td&&Ed(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),$d=ze,kd=String,Pd=TypeError,We=function(i){if($d(i))return i;throw Pd(kd(i)+" is not an object")},Ad=hs,Ci=Function.prototype.call,ge=Ad?Ci.bind(Ci):function(){return Ci.apply(Ci,arguments)},la={},Vs=la,Fs=le,_d=ne,Ka=function(i){return _d(i)?i:void 0},gt=function(i,e){return arguments.length<2?Ka(Vs[i])||Ka(Fs[i]):Vs[i]&&Vs[i][e]||Fs[i]&&Fs[i][e]},wd=Pe,fs=wd({}.isPrototypeOf),ps=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Qo=le,Us=ps,Ja=Qo.process,Xa=Qo.Deno,Za=Ja&&Ja.versions||Xa&&Xa.version,en=Za&&Za.v8,we,is;en&&(we=en.split("."),is=we[0]>0&&we[0]<4?1:+(we[0]+we[1]));!is&&Us&&(we=Us.match(/Edge\/(\d+)/),(!we||we[1]>=74)&&(we=Us.match(/Chrome\/(\d+)/),we&&(is=+we[1])));var Ko=is,tn=Ko,Rd=ke,Cd=le,Dd=Cd.String,Jo=!!Object.getOwnPropertySymbols&&!Rd(function(){var i=Symbol();return!Dd(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&tn&&tn<41}),Id=Jo,Xo=Id&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Nd=gt,xd=ne,Ld=fs,Od=Xo,Md=Object,Zo=Od?function(i){return typeof i=="symbol"}:function(i){var e=Nd("Symbol");return xd(e)&&Ld(e.prototype,Md(i))},Bd=String,ms=function(i){try{return Bd(i)}catch(e){return"Object"}},Vd=ne,Fd=ms,Ud=TypeError,yt=function(i){if(Vd(i))return i;throw Ud(Fd(i)+" is not a function")},jd=yt,Hd=pi,vs=function(i,e){var t=i[e];return Hd(t)?void 0:jd(t)},js=ge,Hs=ne,Gs=ze,Gd=TypeError,Yd=function(i,e){var t,s;if(e==="string"&&Hs(t=i.toString)&&!Gs(s=js(t,i))||Hs(t=i.valueOf)&&!Gs(s=js(t,i))||e!=="string"&&Hs(t=i.toString)&&!Gs(s=js(t,i)))return s;throw Gd("Can't convert object to primitive value")},el={exports:{}},qd=!0,sn=le,zd=Object.defineProperty,Wd=function(i,e){try{zd(sn,i,{value:e,configurable:!0,writable:!0})}catch(t){sn[i]=e}return e},Qd=le,Kd=Wd,rn="__core-js_shared__",Jd=Qd[rn]||Kd(rn,{}),ua=Jd,an=ua;(el.exports=function(i,e){return an[i]||(an[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 tl=el.exports,Xd=na,Zd=Object,bs=function(i){return Zd(Xd(i))},ec=Pe,tc=bs,ic=ec({}.hasOwnProperty),Ve=Object.hasOwn||function(e,t){return ic(tc(e),t)},sc=Pe,rc=0,ac=Math.random(),nc=sc(1 .toString),il=function(i){return"Symbol("+(i===void 0?"":i)+")_"+nc(++rc+ac,36)},oc=le,lc=tl,nn=Ve,uc=il,dc=Jo,cc=Xo,Nt=oc.Symbol,Ys=lc("wks"),hc=cc?Nt.for||Nt:Nt&&Nt.withoutSetter||uc,ce=function(i){return nn(Ys,i)||(Ys[i]=dc&&nn(Nt,i)?Nt[i]:hc("Symbol."+i)),Ys[i]},fc=ge,on=ze,ln=Zo,pc=vs,mc=Yd,vc=ce,bc=TypeError,Sc=vc("toPrimitive"),gc=function(i,e){if(!on(i)||ln(i))return i;var t=pc(i,Sc),s;if(t){if(e===void 0&&(e="default"),s=fc(t,i,e),!on(s)||ln(s))return s;throw bc("Can't convert object to primitive value")}return e===void 0&&(e="number"),mc(i,e)},yc=gc,Tc=Zo,da=function(i){var e=yc(i,"string");return Tc(e)?e:e+""},Ec=nt,$c=zo,kc=Wo,Di=We,un=da,Pc=TypeError,qs=Object.defineProperty,Ac=Object.getOwnPropertyDescriptor,zs="enumerable",Ws="configurable",Qs="writable";St.f=Ec?kc?function(e,t,s){if(Di(e),t=un(t),Di(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Qs in s&&!s[Qs]){var r=Ac(e,t);r&&r[Qs]&&(e[t]=s.value,s={configurable:Ws in s?s[Ws]:r[Ws],enumerable:zs in s?s[zs]:r[zs],writable:!1})}return qs(e,t,s)}:qs:function(e,t,s){if(Di(e),t=un(t),Di(s),$c)try{return qs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw Pc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ss=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},_c=nt,wc=St,Rc=Ss,vi=_c?function(i,e,t){return wc.f(i,e,Rc(1,t))}:function(i,e,t){return i[e]=t,i},Cc=tl,Dc=il,dn=Cc("keys"),ca=function(i){return dn[i]||(dn[i]=Dc(i))},ha={},Ic=fd,sl=le,Nc=ze,xc=vi,Ks=Ve,Js=ua,Lc=ca,Oc=ha,cn="Object already initialized",Br=sl.TypeError,Mc=sl.WeakMap,ss,ui,rs,Bc=function(i){return rs(i)?ui(i):ss(i,{})},Vc=function(i){return function(e){var t;if(!Nc(e)||(t=ui(e)).type!==i)throw Br("Incompatible receiver, "+i+" required");return t}};if(Ic||Js.state){var Ne=Js.state||(Js.state=new Mc);Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,ss=function(i,e){if(Ne.has(i))throw Br(cn);return e.facade=i,Ne.set(i,e),e},ui=function(i){return Ne.get(i)||{}},rs=function(i){return Ne.has(i)}}else{var _t=Lc("state");Oc[_t]=!0,ss=function(i,e){if(Ks(i,_t))throw Br(cn);return e.facade=i,xc(i,_t,e),e},ui=function(i){return Ks(i,_t)?i[_t]:{}},rs=function(i){return Ks(i,_t)}}var rl={set:ss,get:ui,has:rs,enforce:Bc,getterFor:Vc},Fc=hs,al=Function.prototype,hn=al.apply,fn=al.call,nl=typeof Reflect=="object"&&Reflect.apply||(Fc?fn.bind(hn):function(){return fn.apply(hn,arguments)}),Uc=fi,jc=Pe,ol=function(i){if(Uc(i)==="Function")return jc(i)},fa={},ll={},ul={}.propertyIsEnumerable,dl=Object.getOwnPropertyDescriptor,Hc=dl&&!ul.call({1:2},1);ll.f=Hc?function(e){var t=dl(this,e);return!!t&&t.enumerable}:ul;var Gc=nt,Yc=ge,qc=ll,zc=Ss,Wc=mi,Qc=da,Kc=Ve,Jc=zo,pn=Object.getOwnPropertyDescriptor;fa.f=Gc?pn:function(e,t){if(e=Wc(e),t=Qc(t),Jc)try{return pn(e,t)}catch(s){}if(Kc(e,t))return zc(!Yc(qc.f,e,t),e[t])};var Xc=ke,Zc=ne,eh=/#|\.prototype\./,bi=function(i,e){var t=ih[th(i)];return t==rh?!0:t==sh?!1:Zc(e)?Xc(e):!!e},th=bi.normalize=function(i){return String(i).replace(eh,".").toLowerCase()},ih=bi.data={},sh=bi.NATIVE="N",rh=bi.POLYFILL="P",cl=bi,mn=ol,ah=yt,nh=hs,oh=mn(mn.bind),gs=function(i,e){return ah(i),e===void 0?i:nh?oh(i,e):function(){return i.apply(e,arguments)}},Ii=le,lh=nl,uh=ol,dh=ne,ch=fa.f,hh=cl,wt=la,fh=gs,Rt=vi,vn=Ve,ph=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return lh(i,this,arguments)};return e.prototype=i.prototype,e},De=function(i,e){var t=i.target,s=i.global,r=i.stat,n=i.proto,o=s?Ii:r?Ii[t]:(Ii[t]||{}).prototype,l=s?wt:wt[t]||Rt(wt,t,{})[t],d=l.prototype,u,c,h,f,p,m,b,g,E;for(f in e)u=hh(s?f:t+(r?".":"#")+f,i.forced),c=!u&&o&&vn(o,f),m=l[f],c&&(i.dontCallGetSet?(E=ch(o,f),b=E&&E.value):b=o[f]),p=c&&b?b:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?g=fh(p,Ii):i.wrap&&c?g=ph(p):n&&dh(p)?g=uh(p):g=p,(i.sham||p&&p.sham||m&&m.sham)&&Rt(g,"sham",!0),Rt(l,f,g),n&&(h=t+"Prototype",vn(wt,h)||Rt(wt,h,{}),Rt(wt[h],f,p),i.real&&d&&(u||!d[f])&&Rt(d,f,p)))},Vr=nt,mh=Ve,hl=Function.prototype,vh=Vr&&Object.getOwnPropertyDescriptor,pa=mh(hl,"name"),bh=pa&&function(){}.name==="something",Sh=pa&&(!Vr||Vr&&vh(hl,"name").configurable),gh={EXISTS:pa,PROPER:bh,CONFIGURABLE:Sh},fl={},yh=Math.ceil,Th=Math.floor,Eh=Math.trunc||function(e){var t=+e;return(t>0?Th:yh)(t)},$h=Eh,ma=function(i){var e=+i;return e!==e||e===0?0:$h(e)},kh=ma,Ph=Math.max,Ah=Math.min,_h=function(i,e){var t=kh(i);return t<0?Ph(t+e,0):Ah(t,e)},wh=ma,Rh=Math.min,Ch=function(i){return i>0?Rh(wh(i),9007199254740991):0},Dh=Ch,va=function(i){return Dh(i.length)},Ih=mi,Nh=_h,xh=va,bn=function(i){return function(e,t,s){var r=Ih(e),n=xh(r),o=Nh(s,n),l;if(i&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in r)&&r[o]===t)return i||o||0;return!i&&-1}},Lh={includes:bn(!0),indexOf:bn(!1)},Oh=Pe,Xs=Ve,Mh=mi,Bh=Lh.indexOf,Vh=ha,Sn=Oh([].push),Fh=function(i,e){var t=Mh(i),s=0,r=[],n;for(n in t)!Xs(Vh,n)&&Xs(t,n)&&Sn(r,n);for(;e.length>s;)Xs(t,n=e[s++])&&(~Bh(r,n)||Sn(r,n));return r},pl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Uh=Fh,jh=pl,Hh=Object.keys||function(e){return Uh(e,jh)},Gh=nt,Yh=Wo,qh=St,zh=We,Wh=mi,Qh=Hh;fl.f=Gh&&!Yh?Object.defineProperties:function(e,t){zh(e);for(var s=Wh(t),r=Qh(t),n=r.length,o=0,l;n>o;)qh.f(e,l=r[o++],s[l]);return e};var Kh=gt,ml=Kh("document","documentElement"),Jh=We,Xh=fl,gn=pl,Zh=ha,ef=ml,tf=oa,sf=ca,yn=">",Tn="<",Fr="prototype",Ur="script",vl=sf("IE_PROTO"),Zs=function(){},bl=function(i){return Tn+Ur+yn+i+Tn+"/"+Ur+yn},En=function(i){i.write(bl("")),i.close();var e=i.parentWindow.Object;return i=null,e},rf=function(){var i=tf("iframe"),e="java"+Ur+":",t;return i.style.display="none",ef.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(bl("document.F=Object")),t.close(),t.F},Ni,Xi=function(){try{Ni=new ActiveXObject("htmlfile")}catch(e){}Xi=typeof document!="undefined"?document.domain&&Ni?En(Ni):rf():En(Ni);for(var i=gn.length;i--;)delete Xi[Fr][gn[i]];return Xi()};Zh[vl]=!0;var Sl=Object.create||function(e,t){var s;return e!==null?(Zs[Fr]=Jh(e),s=new Zs,Zs[Fr]=null,s[vl]=e):s=Xi(),t===void 0?s:Xh.f(s,t)},af=ke,nf=!af(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),of=Ve,lf=ne,uf=bs,df=ca,cf=nf,$n=df("IE_PROTO"),jr=Object,hf=jr.prototype,gl=cf?jr.getPrototypeOf:function(i){var e=uf(i);if(of(e,$n))return e[$n];var t=e.constructor;return lf(t)&&e instanceof t?t.prototype:e instanceof jr?hf:null},ff=vi,ba=function(i,e,t,s){return s&&s.enumerable?i[e]=t:ff(i,e,t),i},pf=ke,mf=ne,vf=ze,bf=Sl,kn=gl,Sf=ba,gf=ce,Hr=gf("iterator"),yl=!1,Ge,er,tr;[].keys&&(tr=[].keys(),"next"in tr?(er=kn(kn(tr)),er!==Object.prototype&&(Ge=er)):yl=!0);var yf=!vf(Ge)||pf(function(){var i={};return Ge[Hr].call(i)!==i});yf?Ge={}:Ge=bf(Ge);mf(Ge[Hr])||Sf(Ge,Hr,function(){return this});var Tl={IteratorPrototype:Ge,BUGGY_SAFARI_ITERATORS:yl},Tf=ce,Ef=Tf("toStringTag"),El={};El[Ef]="z";var Sa=String(El)==="[object z]",$f=Sa,kf=ne,Zi=fi,Pf=ce,Af=Pf("toStringTag"),_f=Object,wf=Zi(function(){return arguments}())=="Arguments",Rf=function(i,e){try{return i[e]}catch(t){}},Si=$f?Zi:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Rf(e=_f(i),Af))=="string"?t:wf?Zi(e):(s=Zi(e))=="Object"&&kf(e.callee)?"Arguments":s},Cf=Sa,Df=Si,If=Cf?{}.toString:function(){return"[object "+Df(this)+"]"},Nf=Sa,xf=St.f,Lf=vi,Of=Ve,Mf=If,Bf=ce,Pn=Bf("toStringTag"),ga=function(i,e,t,s){if(i){var r=t?i:i.prototype;Of(r,Pn)||xf(r,Pn,{configurable:!0,value:e}),s&&!Nf&&Lf(r,"toString",Mf)}},Vf=Tl.IteratorPrototype,Ff=Sl,Uf=Ss,jf=ga,Hf=Ht,Gf=function(){return this},Yf=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Ff(Vf,{next:Uf(+!s,t)}),jf(i,r,!1,!0),Hf[r]=Gf,i},qf=De,zf=ge,$l=gh,Wf=Yf,Qf=gl,Kf=ga,An=ba,Jf=ce,_n=Ht,kl=Tl,Xf=$l.PROPER;$l.CONFIGURABLE;kl.IteratorPrototype;var xi=kl.BUGGY_SAFARI_ITERATORS,ir=Jf("iterator"),wn="keys",Li="values",Rn="entries",Zf=function(){return this},ep=function(i,e,t,s,r,n,o){Wf(t,e,s);var l=function(E){if(E===r&&f)return f;if(!xi&&E in c)return c[E];switch(E){case wn:return function(){return new t(this,E)};case Li:return function(){return new t(this,E)};case Rn:return function(){return new t(this,E)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[ir]||c["@@iterator"]||r&&c[r],f=!xi&&h||l(r),p=e=="Array"&&c.entries||h,m,b,g;if(p&&(m=Qf(p.call(new i)),m!==Object.prototype&&m.next&&(Kf(m,d,!0,!0),_n[d]=Zf)),Xf&&r==Li&&h&&h.name!==Li&&(u=!0,f=function(){return zf(h,this)}),r)if(b={values:l(Li),keys:n?f:l(wn),entries:l(Rn)},o)for(g in b)(xi||u||!(g in c))&&An(c,g,b[g]);else qf({target:e,proto:!0,forced:xi||u},b);return o&&c[ir]!==f&&An(c,ir,f,{name:r}),_n[e]=f,b},tp=function(i,e){return{value:i,done:e}},ip=mi,Cn=Ht,Pl=rl;St.f;var sp=ep,Oi=tp,Al="Array Iterator",rp=Pl.set,ap=Pl.getterFor(Al);sp(Array,"Array",function(i,e){rp(this,{type:Al,target:ip(i),index:0,kind:e})},function(){var i=ap(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Oi(void 0,!0)):t=="keys"?Oi(s,!1):t=="values"?Oi(e[s],!1):Oi([s,e[s]],!1)},"values");Cn.Arguments=Cn.Array;var np=ce,op=Ht,lp=np("iterator"),up=Array.prototype,dp=function(i){return i!==void 0&&(op.Array===i||up[lp]===i)},cp=Si,Dn=vs,hp=pi,fp=Ht,pp=ce,mp=pp("iterator"),_l=function(i){if(!hp(i))return Dn(i,mp)||Dn(i,"@@iterator")||fp[cp(i)]},vp=ge,bp=yt,Sp=We,gp=ms,yp=_l,Tp=TypeError,Ep=function(i,e){var t=arguments.length<2?yp(i):e;if(bp(t))return Sp(vp(t,i));throw Tp(gp(i)+" is not iterable")},$p=ge,In=We,kp=vs,Pp=function(i,e,t){var s,r;In(i);try{if(s=kp(i,"return"),!s){if(e==="throw")throw t;return t}s=$p(s,i)}catch(n){r=!0,s=n}if(e==="throw")throw t;if(r)throw s;return In(s),t},Ap=gs,_p=ge,wp=We,Rp=ms,Cp=dp,Dp=va,Nn=fs,Ip=Ep,Np=_l,xn=Pp,xp=TypeError,es=function(i,e){this.stopped=i,this.result=e},Ln=es.prototype,ya=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=Ap(e,s),u,c,h,f,p,m,b,g=function(y){return u&&xn(u,"normal",y),new es(!0,y)},E=function(y){return r?(wp(y),l?d(y[0],y[1],g):d(y[0],y[1])):l?d(y,g):d(y)};if(n)u=i.iterator;else if(o)u=i;else{if(c=Np(i),!c)throw xp(Rp(i)+" is not iterable");if(Cp(c)){for(h=0,f=Dp(i);f>h;h++)if(p=E(i[h]),p&&Nn(Ln,p))return p;return new es(!1)}u=Ip(i,c)}for(m=n?i.next:u.next;!(b=_p(m,u)).done;){try{p=E(b.value)}catch(y){xn(u,"throw",y)}if(typeof p=="object"&&p&&Nn(Ln,p))return p}return new es(!1)},Lp=da,Op=St,Mp=Ss,Bp=function(i,e,t){var s=Lp(e);s in i?Op.f(i,s,Mp(0,t)):i[s]=t},Vp=De,Fp=ya,Up=Bp;Vp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Fp(e,function(s,r){Up(t,s,r)},{AS_ENTRIES:!0}),t}});var jp=la,Hp=jp.Object.fromEntries,Gp={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},Yp=Gp,qp=le,zp=Si,Wp=vi,On=Ht,Qp=ce,Mn=Qp("toStringTag");for(var sr in Yp){var Bn=qp[sr],rr=Bn&&Bn.prototype;rr&&zp(rr)!==Mn&&Wp(rr,Mn,sr),On[sr]=On.Array}var Kp=Hp,Jp=Kp,Xp=Jp,Zp=Xp,Vt=cs(Zp),em=fi,ys=typeof process!="undefined"&&em(process)=="process",tm=St,im=function(i,e,t){return tm.f(i,e,t)},sm=gt,rm=im,am=ce,nm=nt,Vn=am("species"),om=function(i){var e=sm(i);nm&&e&&!e[Vn]&&rm(e,Vn,{configurable:!0,get:function(){return this}})},lm=fs,um=TypeError,dm=function(i,e){if(lm(e,i))return i;throw um("Incorrect invocation")},cm=Pe,hm=ne,Gr=ua,fm=cm(Function.toString);hm(Gr.inspectSource)||(Gr.inspectSource=function(i){return fm(i)});var wl=Gr.inspectSource,pm=Pe,mm=ke,Rl=ne,vm=Si,bm=gt,Sm=wl,Cl=function(){},gm=[],Dl=bm("Reflect","construct"),Ta=/^\s*(?:class|function)\b/,ym=pm(Ta.exec),Tm=!Ta.exec(Cl),ei=function(e){if(!Rl(e))return!1;try{return Dl(Cl,gm,e),!0}catch(t){return!1}},Il=function(e){if(!Rl(e))return!1;switch(vm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Tm||!!ym(Ta,Sm(e))}catch(t){return!0}};Il.sham=!0;var Em=!Dl||mm(function(){var i;return ei(ei.call)||!ei(Object)||!ei(function(){i=!0})||i})?Il:ei,$m=Em,km=ms,Pm=TypeError,Am=function(i){if($m(i))return i;throw Pm(km(i)+" is not a constructor")},Fn=We,_m=Am,wm=pi,Rm=ce,Cm=Rm("species"),Nl=function(i,e){var t=Fn(i).constructor,s;return t===void 0||wm(s=Fn(t)[Cm])?e:_m(s)},Dm=Pe,Im=Dm([].slice),Nm=TypeError,xm=function(i,e){if(i<e)throw Nm("Not enough arguments");return i},Lm=ps,xl=/(?:ipad|iphone|ipod).*applewebkit/i.test(Lm),Se=le,Om=nl,Mm=gs,Un=ne,Bm=Ve,Ll=ke,jn=ml,Vm=Im,Hn=oa,Fm=xm,Um=xl,jm=ys,Yr=Se.setImmediate,qr=Se.clearImmediate,Hm=Se.process,ar=Se.Dispatch,Gm=Se.Function,Gn=Se.MessageChannel,Ym=Se.String,nr=0,ni={},Yn="onreadystatechange",di,ft,or,lr;Ll(function(){di=Se.location});var Ea=function(i){if(Bm(ni,i)){var e=ni[i];delete ni[i],e()}},ur=function(i){return function(){Ea(i)}},qn=function(i){Ea(i.data)},zn=function(i){Se.postMessage(Ym(i),di.protocol+"//"+di.host)};(!Yr||!qr)&&(Yr=function(e){Fm(arguments.length,1);var t=Un(e)?e:Gm(e),s=Vm(arguments,1);return ni[++nr]=function(){Om(t,void 0,s)},ft(nr),nr},qr=function(e){delete ni[e]},jm?ft=function(i){Hm.nextTick(ur(i))}:ar&&ar.now?ft=function(i){ar.now(ur(i))}:Gn&&!Um?(or=new Gn,lr=or.port2,or.port1.onmessage=qn,ft=Mm(lr.postMessage,lr)):Se.addEventListener&&Un(Se.postMessage)&&!Se.importScripts&&di&&di.protocol!=="file:"&&!Ll(zn)?(ft=zn,Se.addEventListener("message",qn,!1)):Yn in Hn("script")?ft=function(i){jn.appendChild(Hn("script"))[Yn]=function(){jn.removeChild(this),Ea(i)}}:ft=function(i){setTimeout(ur(i),0)});var Ol={set:Yr,clear:qr},Ml=function(){this.head=null,this.tail=null};Ml.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 Bl=Ml,qm=ps,zm=/ipad|iphone|ipod/i.test(qm)&&typeof Pebble!="undefined",Wm=ps,Qm=/web0s(?!.*chrome)/i.test(Wm),bt=le,Wn=gs,Km=fa.f,dr=Ol.set,Jm=Bl,Xm=xl,Zm=zm,ev=Qm,cr=ys,Qn=bt.MutationObserver||bt.WebKitMutationObserver,Kn=bt.document,Jn=bt.process,Mi=bt.Promise,Xn=Km(bt,"queueMicrotask"),zr=Xn&&Xn.value,Ct,hr,fr,Bi,Zn;if(!zr){var Vi=new Jm,Fi=function(){var i,e;for(cr&&(i=Jn.domain)&&i.exit();e=Vi.get();)try{e()}catch(t){throw Vi.head&&Ct(),t}i&&i.enter()};!Xm&&!cr&&!ev&&Qn&&Kn?(hr=!0,fr=Kn.createTextNode(""),new Qn(Fi).observe(fr,{characterData:!0}),Ct=function(){fr.data=hr=!hr}):!Zm&&Mi&&Mi.resolve?(Bi=Mi.resolve(void 0),Bi.constructor=Mi,Zn=Wn(Bi.then,Bi),Ct=function(){Zn(Fi)}):cr?Ct=function(){Jn.nextTick(Fi)}:(dr=Wn(dr,bt),Ct=function(){dr(Fi)}),zr=function(i){Vi.head||Ct(),Vi.add(i)}}var tv=zr,iv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},$a=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},sv=le,Gt=sv.Promise,Vl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",rv=Vl,av=ys,nv=!rv&&!av&&typeof window=="object"&&typeof document=="object",ov=le,oi=Gt,lv=ne,uv=cl,dv=wl,cv=ce,hv=nv,fv=Vl,pr=Ko,eo=oi&&oi.prototype,pv=cv("species"),Wr=!1,Fl=lv(ov.PromiseRejectionEvent),mv=uv("Promise",function(){var i=dv(oi),e=i!==String(oi);if(!e&&pr===66||!(eo.catch&&eo.finally))return!0;if(!pr||pr<51||!/native code/.test(i)){var t=new oi(function(n){n(1)}),s=function(n){n(function(){},function(){})},r=t.constructor={};if(r[pv]=s,Wr=t.then(function(){})instanceof s,!Wr)return!0}return!e&&(hv||fv)&&!Fl}),gi={CONSTRUCTOR:mv,REJECTION_EVENT:Fl,SUBCLASSING:Wr},Yt={},to=yt,vv=TypeError,bv=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw vv("Bad Promise constructor");e=s,t=r}),this.resolve=to(e),this.reject=to(t)};Yt.f=function(i){return new bv(i)};var Sv=De,as=ys,at=le,yi=ge,gv=ba,yv=ga,Tv=om,Ev=yt,Qr=ne,$v=ze,kv=dm,Pv=Nl,Ul=Ol.set,ka=tv,Av=iv,_v=$a,wv=Bl,jl=rl,Kr=Gt,Pa=gi,Hl=Yt,Ts="Promise",Gl=Pa.CONSTRUCTOR,Rv=Pa.REJECTION_EVENT;Pa.SUBCLASSING;var mr=jl.getterFor(Ts),Cv=jl.set,Dv=Kr&&Kr.prototype,xt=Kr,vr=Dv,Yl=at.TypeError,Jr=at.document,Aa=at.process,Xr=Hl.f,Iv=Xr,Nv=!!(Jr&&Jr.createEvent&&at.dispatchEvent),ql="unhandledrejection",xv="rejectionhandled",io=0,zl=1,Lv=2,_a=1,Wl=2,Ui,so,Ov,Ql=function(i){var e;return $v(i)&&Qr(e=i.then)?e:!1},Kl=function(i,e){var t=e.value,s=e.state==zl,r=s?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{r?(s||(e.rejection===Wl&&Bv(e),e.rejection=_a),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===i.promise?o(Yl("Promise-chain cycle")):(u=Ql(d))?yi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Jl=function(i,e){i.notified||(i.notified=!0,ka(function(){for(var t=i.reactions,s;s=t.get();)Kl(s,i);i.notified=!1,e&&!i.rejection&&Mv(i)}))},Xl=function(i,e,t){var s,r;Nv?(s=Jr.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),at.dispatchEvent(s)):s={promise:e,reason:t},!Rv&&(r=at["on"+i])?r(s):i===ql&&Av("Unhandled promise rejection",t)},Mv=function(i){yi(Ul,at,function(){var e=i.facade,t=i.value,s=ro(i),r;if(s&&(r=_v(function(){as?Aa.emit("unhandledRejection",t,e):Xl(ql,e,t)}),i.rejection=as||ro(i)?Wl:_a,r.error))throw r.value})},ro=function(i){return i.rejection!==_a&&!i.parent},Bv=function(i){yi(Ul,at,function(){var e=i.facade;as?Aa.emit("rejectionHandled",e):Xl(xv,e,i.value)})},Lt=function(i,e,t){return function(s){i(e,s,t)}},Mt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Lv,Jl(i,!0))},Zr=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Yl("Promise can't be resolved itself");var s=Ql(e);s?ka(function(){var r={done:!1};try{yi(s,e,Lt(Zr,r,i),Lt(Mt,r,i))}catch(n){Mt(r,n,i)}}):(i.value=e,i.state=zl,Jl(i,!1))}catch(r){Mt({done:!1},r,i)}}};Gl&&(xt=function(e){kv(this,vr),Ev(e),yi(Ui,this);var t=mr(this);try{e(Lt(Zr,t),Lt(Mt,t))}catch(s){Mt(t,s)}},vr=xt.prototype,Ui=function(e){Cv(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new wv,rejection:!1,state:io,value:void 0})},Ui.prototype=gv(vr,"then",function(e,t){var s=mr(this),r=Xr(Pv(this,xt));return s.parent=!0,r.ok=Qr(e)?e:!0,r.fail=Qr(t)&&t,r.domain=as?Aa.domain:void 0,s.state==io?s.reactions.add(r):ka(function(){Kl(r,s)}),r.promise}),so=function(){var i=new Ui,e=mr(i);this.promise=i,this.resolve=Lt(Zr,e),this.reject=Lt(Mt,e)},Hl.f=Xr=function(i){return i===xt||i===Ov?new so(i):Iv(i)});Sv({global:!0,constructor:!0,wrap:!0,forced:Gl},{Promise:xt});yv(xt,Ts,!1,!0);Tv(Ts);var Vv=ce,Zl=Vv("iterator"),eu=!1;try{var Fv=0,ao={next:function(){return{done:!!Fv++}},return:function(){eu=!0}};ao[Zl]=function(){return this},Array.from(ao,function(){throw 2})}catch(i){}var Uv=function(i,e){if(!e&&!eu)return!1;var t=!1;try{var s={};s[Zl]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},jv=Gt,Hv=Uv,Gv=gi.CONSTRUCTOR,tu=Gv||!Hv(function(i){jv.all(i).then(void 0,function(){})}),Yv=De,qv=ge,zv=yt,Wv=Yt,Qv=$a,Kv=ya,Jv=tu;Yv({target:"Promise",stat:!0,forced:Jv},{all:function(e){var t=this,s=Wv.f(t),r=s.resolve,n=s.reject,o=Qv(function(){var l=zv(t.resolve),d=[],u=0,c=1;Kv(e,function(h){var f=u++,p=!1;c++,qv(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||r(d))},n)}),--c||r(d)});return o.error&&n(o.value),s.promise}});var Xv=De,Zv=gi.CONSTRUCTOR,no=Gt;no&&no.prototype;Xv({target:"Promise",proto:!0,forced:Zv,real:!0},{catch:function(i){return this.then(void 0,i)}});var eb=De,tb=ge,ib=yt,sb=Yt,rb=$a,ab=ya,nb=tu;eb({target:"Promise",stat:!0,forced:nb},{race:function(e){var t=this,s=sb.f(t),r=s.reject,n=rb(function(){var o=ib(t.resolve);ab(e,function(l){tb(o,t,l).then(s.resolve,r)})});return n.error&&r(n.value),s.promise}});var ob=De,lb=ge,ub=Yt,db=gi.CONSTRUCTOR;ob({target:"Promise",stat:!0,forced:db},{reject:function(e){var t=ub.f(this);return lb(t.reject,void 0,e),t.promise}});var cb=We,hb=ze,fb=Yt,iu=function(i,e){if(cb(i),hb(e)&&e.constructor===i)return e;var t=fb.f(i),s=t.resolve;return s(e),t.promise},pb=De,mb=gt,vb=qd,bb=Gt,Sb=gi.CONSTRUCTOR,gb=iu,yb=mb("Promise"),Tb=!Sb;pb({target:"Promise",stat:!0,forced:vb},{resolve:function(e){return gb(Tb&&this===yb?bb:this,e)}});var Eb=De,ea=Gt,$b=ke,kb=gt,Pb=ne,Ab=Nl,oo=iu,_b=ea&&ea.prototype,wb=!!ea&&$b(function(){_b.finally.call({then:function(){}},function(){})});Eb({target:"Promise",proto:!0,real:!0,forced:wb},{finally:function(i){var e=Ab(this,kb("Promise")),t=Pb(i);return this.then(t?function(s){return oo(e,i()).then(function(){return s})}:i,t?function(s){return oo(e,i()).then(function(){throw s})}:i)}});var Rb=gt,wa=Rb,Cb=wa,Db=Cb("Promise","finally"),Ib=Db,Nb=Ib,xb=Nb,Lb=xb,Es=cs(Lb),ae;(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"})(ae||(ae={}));var Re=(i,e=0,t=ae.OFFSET_P)=>{switch(t){case ae.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ae.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ae.DASH_CMAF_OFFSET_P:{if(e===0)return i;const s=new URL(i);return s.searchParams.set("offset_p",e.toFixed(0)),s.toString()}default:a.assertNever(t)}return i};const lo=(i,e)=>{var t;switch(e){case ae.OFFSET_P:return NaN;case ae.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ae.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var P=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.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,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||a.isNonNullable(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Ob=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.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 O;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(O||(O={}));const Mb=5,Bb=5,Vb=500,uo=7e3;class Fb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new X(O.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&s!==O.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case O.PLAYING:case O.PAUSED:case O.READY:break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case O.PLAYING:break;case O.PAUSED:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.READY:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case O.PLAYING:this.videoState.startTransitionTo(O.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case O.PAUSED:break;case O.READY:this.videoState.startTransitionTo(O.PAUSED),this.videoState.setState(O.PAUSED);break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}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(Ob(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(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(a.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new a.Subject;e.add(r.pipe(a.debounce(Vb)).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===B.Applying||Math.abs(l-n)>Mb)&&r.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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Bb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(O.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(O.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:B.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PAUSED||e===O.PLAYING)&&(this.videoState.setState(O.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PLAYING||e===O.PAUSED)&&(this.videoState.setState(O.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===O.READY&&this.videoState.setState(O.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==O.STOPPED&&this.videoState.setState(O.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=s[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=Re(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===B.Applying||s.state===B.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(uo).subscribe(()=>n(`timeout(${uo})`)))});Es(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Ub=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&s&&(e==null||e())}}},!0)},jb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,s=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,b;const g=Vt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),S=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=S!=null?S:v*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const E=(m=g["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(b={1:!0,0:!1}[g["x-reused"]])!==null&&b!==void 0?b:void 0;s.next(E),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...b){return d(this),p(...b)},f.progress=function(...b){return u(this),m(...b)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},Ft=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Hb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Ft}),!0),Gb=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,n]=s.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(s.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),s.request.url=o.toString(),s.request.range=void 0}t(s)}}},!0)};const Ce=(i,e,t,{equal:s=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=i.getState();s(c,h)&&i.setState(c)},n)),s(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},Tt=(i,e,t)=>Ce(e,()=>i.loop,s=>{a.isNonNullable(s)&&(i.loop=s)},{onError:t}),Qe=(i,e,t,s)=>Ce(e,()=>({muted:i.muted,volume:i.volume}),r=>{a.isNonNullable(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),ot=(i,e,t,s)=>Ce(e,()=>i.playbackRate,r=>{a.isNonNullable(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Yb=i=>["__",i.language,i.label].join("|"),qb=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class Fe{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,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Ce(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},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="internal"))),onError:r})),this.subscription.add(Ce(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:r})),this.subscription.add(Ce(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:r})),this.subscription.add(Ce(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 s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),a.filterChanged((s,r)=>s.length===r.length&&s.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),a.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),a.filterChanged()).subscribe(this.current$));const t=s=>{var r,n;return this.applyCueSettings((n=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(s=>{var r,n;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Fe.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:n}=e,o=e.id?e.id:Yb(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(s=this.internalTracks.get(o))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:n})=>!this.internalTracks.has(s)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}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)||!qb(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"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Ra=i=>{i.removeAttribute("src"),i.load()},zb=i=>{try{i.pause(),i.playbackRate=0,Ra(i),i.remove()}catch(e){console.error(e)}};class Wb{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 ta=window.WeakMap?new WeakMap:new Wb,Ke=i=>{let e=i.querySelector("video");const t=!!e;return e?Ra(e):(e=document.createElement("video"),i.appendChild(e)),ta.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Je=i=>{const e=ta.get(i);ta.delete(i),e?Ra(i):zb(i)};class $s{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 su=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},co=i=>{const e=su(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Qb=i=>{const e=su(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},ia=3;class Kb{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<ia&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||ia))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?s(t,n):l?s(r,e):r<e&&n>t?(s(t,n),s(r,e)):s(r,n))})}destroy(){this._buffer=[]}}var ru=(i,e,t=ia)=>{let s=0,r=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,r=l,!t)return{from:s,to:r};for(let d=n-1;d>=0;d--)i.end(d)+t>=s&&(s=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=r&&(r=i.end(d))}}return{from:s,to:r}};const Xe=i=>{const e=v=>a.fromEvent(i,v).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=a.merge(...t.map(v=>a.fromEvent(i,v))).pipe(a.map(v=>v.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>ru(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}))),d=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 v;const S=i.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=i.error)!==null&&v!==void 0?v:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(v=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(v)&&p>=i.duration-f&&v<=f&&h.next(p),p=v});const m=a.fromEvent(i,"enterpictureinpicture"),b=a.fromEvent(i,"leavepictureinpicture"),g=new a.ValueSubject(Qb(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));const E=new a.ValueSubject(co(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>co(i))).subscribe(E),{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$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:g,inFullscreen$:E}},Ca=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Jb=De,Xb=bs,Zb=va,eS=ma;Jb({target:"Array",proto:!0},{at:function(e){var t=Xb(this),s=Zb(t),r=eS(e),n=r>=0?r:s+r;return n<0||n>=s?void 0:t[n]}});var tS=wa,iS=tS("Array","at"),sS=iS,rS=sS,aS=rS,nS=aS,Le=cs(nS);let Da=!1,He={};const oS=i=>{Da=i},lS=()=>{He={}},uS=i=>{i(He)},ji=(i,e)=>{var t;Da&&(He.meta=(t=He.meta)!==null&&t!==void 0?t:{},He.meta[i]=e)};class Oe{constructor(e){this.name=e}next(e){var t,s;if(!Da)return;He.series=(t=He.series)!==null&&t!==void 0?t:{};const r=(s=He.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),He.series[this.name]=r}}var mt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(mt||(mt={}));const dS=new Oe("best_bitrate"),cS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class hS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const qt=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,b,g;const E=s.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*E*s.containerSizeFactor,height:e.height*E*s.containerSizeFactor},v=y&&a.videoSizeToQuality(y),S=s.considerPlaybackRate&&a.isNonNullable(l)?l:1,T=i.filter(I=>!a.isInvariantQuality(I.quality)).sort((I,A)=>a.isHigher(I.quality,A.quality)?-1:1),k=(p=Le(T,-1))===null||p===void 0?void 0:p.quality,L=(m=Le(T,0))===null||m===void 0?void 0:m.quality,j=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&a.isLower(r.max,r.min)||a.isNonNullable(r.min)&&L&&a.isHigher(r.min,L)||a.isNonNullable(r.max)&&k&&a.isLower(r.max,k),D=S*cS(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),x={},w=T.filter(I=>(v?a.isLower(I.quality,v):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(I.bitrate)?t-n>=I.bitrate*D:!0)?s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<s.minBufferToSwitchUp&&a.isHigher(I.quality,d.quality)?(x[I.quality]=mt.Buffer,!1):!!c&&a.isHigherOrEqual(I.quality,c)?(x[I.quality]=mt.DroppedFramesLimit,!1):j||(a.isNullable(r.max)||a.isLowerOrEqual(I.quality,r.max))&&(a.isNullable(r.min)||a.isHigherOrEqual(I.quality,r.min))?!0:(x[I.quality]=mt.FitsQualityLimits,!1):(x[I.quality]=mt.FitsThroughput,!1):(x[I.quality]=mt.FitsContainer,!1))[0];w&&w.bitrate&&dS.next(w.bitrate);const N=(b=w!=null?w:T[Math.ceil((T.length-1)/2)])!==null&&b!==void 0?b:i[0];N.quality!==((g=u==null?void 0:u.last)===null||g===void 0?void 0:g.quality)&&h({message:`
|
|
6
|
+
"use strict";var Fu=Object.create;var Ya=Object.defineProperty;var Uu=Object.getOwnPropertyDescriptor;var ju=Object.getOwnPropertyNames;var Hu=Object.getPrototypeOf,Gu=Object.prototype.hasOwnProperty;var Yu=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of ju(e))!Gu.call(i,r)&&r!==t&&Ya(i,r,{get:()=>e[r],enumerable:!(s=Uu(e,r))||s.enumerable});return i};var qa=(i,e,t)=>(t=i!=null?Fu(Hu(i)):{},Yu(e||!i||!i.__esModule?Ya(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),qu=require("lodash/debounce.js");const Fo="2.0.96";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_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 ue;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ue||(ue={}));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 B;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(B||(B={}));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 K(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(s.next(c))}catch(h){o(h)}}function d(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(l,d)}u((s=s.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function be(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){s[f]&&(r[f]=function(p){return new Promise(function(m,b){n.push([f,p,m,b])>1||l(f,p)})})}function l(f,p){try{d(s[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var zu=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Wu{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 s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||zu("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 s,r,n;(n=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.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),s=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([s.getCastState()])).pipe(a.filterChanged(),a.map(Qu),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=s.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Qu=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 Ms=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function cs(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ke=function(i){try{return!!i()}catch(e){return!0}},Ku=ke,hs=!Ku(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Uo=hs,jo=Function.prototype,Lr=jo.call,Ju=Uo&&jo.bind.bind(Lr,Lr),Pe=Uo?Ju:function(i){return function(){return Lr.apply(i,arguments)}},Ho=Pe,Xu=Ho({}.toString),Zu=Ho("".slice),fi=function(i){return Zu(Xu(i),8,-1)},ed=Pe,td=ke,id=fi,Bs=Object,sd=ed("".split),rd=td(function(){return!Bs("z").propertyIsEnumerable(0)})?function(i){return id(i)=="String"?sd(i,""):Bs(i)}:Bs,pi=function(i){return i==null},ad=pi,nd=TypeError,na=function(i){if(ad(i))throw nd("Can't call method on "+i);return i},od=rd,ld=na,mi=function(i){return od(ld(i))},Ht={},Ri=function(i){return i&&i.Math==Math&&i},le=Ri(typeof globalThis=="object"&&globalThis)||Ri(typeof window=="object"&&window)||Ri(typeof self=="object"&&self)||Ri(typeof Ms=="object"&&Ms)||function(){return this}()||Ms||Function("return this")(),Or=typeof document=="object"&&document.all,ud=typeof Or=="undefined"&&Or!==void 0,Go={all:Or,IS_HTMLDDA:ud},Yo=Go,dd=Yo.all,ne=Yo.IS_HTMLDDA?function(i){return typeof i=="function"||i===dd}:function(i){return typeof i=="function"},cd=le,hd=ne,za=cd.WeakMap,fd=hd(za)&&/native code/.test(String(za)),Wa=ne,qo=Go,pd=qo.all,ze=qo.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Wa(i)||i===pd}:function(i){return typeof i=="object"?i!==null:Wa(i)},md=ke,nt=!md(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),St={},vd=le,Qa=ze,Mr=vd.document,bd=Qa(Mr)&&Qa(Mr.createElement),oa=function(i){return bd?Mr.createElement(i):{}},Sd=nt,gd=ke,yd=oa,zo=!Sd&&!gd(function(){return Object.defineProperty(yd("div"),"a",{get:function(){return 7}}).a!=7}),Td=nt,Ed=ke,Wo=Td&&Ed(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),$d=ze,kd=String,Pd=TypeError,We=function(i){if($d(i))return i;throw Pd(kd(i)+" is not an object")},Ad=hs,Ci=Function.prototype.call,ge=Ad?Ci.bind(Ci):function(){return Ci.apply(Ci,arguments)},la={},Vs=la,Fs=le,_d=ne,Ka=function(i){return _d(i)?i:void 0},gt=function(i,e){return arguments.length<2?Ka(Vs[i])||Ka(Fs[i]):Vs[i]&&Vs[i][e]||Fs[i]&&Fs[i][e]},wd=Pe,fs=wd({}.isPrototypeOf),ps=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Qo=le,Us=ps,Ja=Qo.process,Xa=Qo.Deno,Za=Ja&&Ja.versions||Xa&&Xa.version,en=Za&&Za.v8,we,is;en&&(we=en.split("."),is=we[0]>0&&we[0]<4?1:+(we[0]+we[1]));!is&&Us&&(we=Us.match(/Edge\/(\d+)/),(!we||we[1]>=74)&&(we=Us.match(/Chrome\/(\d+)/),we&&(is=+we[1])));var Ko=is,tn=Ko,Rd=ke,Cd=le,Dd=Cd.String,Jo=!!Object.getOwnPropertySymbols&&!Rd(function(){var i=Symbol();return!Dd(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&tn&&tn<41}),Id=Jo,Xo=Id&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Nd=gt,xd=ne,Ld=fs,Od=Xo,Md=Object,Zo=Od?function(i){return typeof i=="symbol"}:function(i){var e=Nd("Symbol");return xd(e)&&Ld(e.prototype,Md(i))},Bd=String,ms=function(i){try{return Bd(i)}catch(e){return"Object"}},Vd=ne,Fd=ms,Ud=TypeError,yt=function(i){if(Vd(i))return i;throw Ud(Fd(i)+" is not a function")},jd=yt,Hd=pi,vs=function(i,e){var t=i[e];return Hd(t)?void 0:jd(t)},js=ge,Hs=ne,Gs=ze,Gd=TypeError,Yd=function(i,e){var t,s;if(e==="string"&&Hs(t=i.toString)&&!Gs(s=js(t,i))||Hs(t=i.valueOf)&&!Gs(s=js(t,i))||e!=="string"&&Hs(t=i.toString)&&!Gs(s=js(t,i)))return s;throw Gd("Can't convert object to primitive value")},el={exports:{}},qd=!0,sn=le,zd=Object.defineProperty,Wd=function(i,e){try{zd(sn,i,{value:e,configurable:!0,writable:!0})}catch(t){sn[i]=e}return e},Qd=le,Kd=Wd,rn="__core-js_shared__",Jd=Qd[rn]||Kd(rn,{}),ua=Jd,an=ua;(el.exports=function(i,e){return an[i]||(an[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 tl=el.exports,Xd=na,Zd=Object,bs=function(i){return Zd(Xd(i))},ec=Pe,tc=bs,ic=ec({}.hasOwnProperty),Ve=Object.hasOwn||function(e,t){return ic(tc(e),t)},sc=Pe,rc=0,ac=Math.random(),nc=sc(1 .toString),il=function(i){return"Symbol("+(i===void 0?"":i)+")_"+nc(++rc+ac,36)},oc=le,lc=tl,nn=Ve,uc=il,dc=Jo,cc=Xo,Nt=oc.Symbol,Ys=lc("wks"),hc=cc?Nt.for||Nt:Nt&&Nt.withoutSetter||uc,ce=function(i){return nn(Ys,i)||(Ys[i]=dc&&nn(Nt,i)?Nt[i]:hc("Symbol."+i)),Ys[i]},fc=ge,on=ze,ln=Zo,pc=vs,mc=Yd,vc=ce,bc=TypeError,Sc=vc("toPrimitive"),gc=function(i,e){if(!on(i)||ln(i))return i;var t=pc(i,Sc),s;if(t){if(e===void 0&&(e="default"),s=fc(t,i,e),!on(s)||ln(s))return s;throw bc("Can't convert object to primitive value")}return e===void 0&&(e="number"),mc(i,e)},yc=gc,Tc=Zo,da=function(i){var e=yc(i,"string");return Tc(e)?e:e+""},Ec=nt,$c=zo,kc=Wo,Di=We,un=da,Pc=TypeError,qs=Object.defineProperty,Ac=Object.getOwnPropertyDescriptor,zs="enumerable",Ws="configurable",Qs="writable";St.f=Ec?kc?function(e,t,s){if(Di(e),t=un(t),Di(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Qs in s&&!s[Qs]){var r=Ac(e,t);r&&r[Qs]&&(e[t]=s.value,s={configurable:Ws in s?s[Ws]:r[Ws],enumerable:zs in s?s[zs]:r[zs],writable:!1})}return qs(e,t,s)}:qs:function(e,t,s){if(Di(e),t=un(t),Di(s),$c)try{return qs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw Pc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var Ss=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},_c=nt,wc=St,Rc=Ss,vi=_c?function(i,e,t){return wc.f(i,e,Rc(1,t))}:function(i,e,t){return i[e]=t,i},Cc=tl,Dc=il,dn=Cc("keys"),ca=function(i){return dn[i]||(dn[i]=Dc(i))},ha={},Ic=fd,sl=le,Nc=ze,xc=vi,Ks=Ve,Js=ua,Lc=ca,Oc=ha,cn="Object already initialized",Br=sl.TypeError,Mc=sl.WeakMap,ss,ui,rs,Bc=function(i){return rs(i)?ui(i):ss(i,{})},Vc=function(i){return function(e){var t;if(!Nc(e)||(t=ui(e)).type!==i)throw Br("Incompatible receiver, "+i+" required");return t}};if(Ic||Js.state){var Ne=Js.state||(Js.state=new Mc);Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,ss=function(i,e){if(Ne.has(i))throw Br(cn);return e.facade=i,Ne.set(i,e),e},ui=function(i){return Ne.get(i)||{}},rs=function(i){return Ne.has(i)}}else{var _t=Lc("state");Oc[_t]=!0,ss=function(i,e){if(Ks(i,_t))throw Br(cn);return e.facade=i,xc(i,_t,e),e},ui=function(i){return Ks(i,_t)?i[_t]:{}},rs=function(i){return Ks(i,_t)}}var rl={set:ss,get:ui,has:rs,enforce:Bc,getterFor:Vc},Fc=hs,al=Function.prototype,hn=al.apply,fn=al.call,nl=typeof Reflect=="object"&&Reflect.apply||(Fc?fn.bind(hn):function(){return fn.apply(hn,arguments)}),Uc=fi,jc=Pe,ol=function(i){if(Uc(i)==="Function")return jc(i)},fa={},ll={},ul={}.propertyIsEnumerable,dl=Object.getOwnPropertyDescriptor,Hc=dl&&!ul.call({1:2},1);ll.f=Hc?function(e){var t=dl(this,e);return!!t&&t.enumerable}:ul;var Gc=nt,Yc=ge,qc=ll,zc=Ss,Wc=mi,Qc=da,Kc=Ve,Jc=zo,pn=Object.getOwnPropertyDescriptor;fa.f=Gc?pn:function(e,t){if(e=Wc(e),t=Qc(t),Jc)try{return pn(e,t)}catch(s){}if(Kc(e,t))return zc(!Yc(qc.f,e,t),e[t])};var Xc=ke,Zc=ne,eh=/#|\.prototype\./,bi=function(i,e){var t=ih[th(i)];return t==rh?!0:t==sh?!1:Zc(e)?Xc(e):!!e},th=bi.normalize=function(i){return String(i).replace(eh,".").toLowerCase()},ih=bi.data={},sh=bi.NATIVE="N",rh=bi.POLYFILL="P",cl=bi,mn=ol,ah=yt,nh=hs,oh=mn(mn.bind),gs=function(i,e){return ah(i),e===void 0?i:nh?oh(i,e):function(){return i.apply(e,arguments)}},Ii=le,lh=nl,uh=ol,dh=ne,ch=fa.f,hh=cl,wt=la,fh=gs,Rt=vi,vn=Ve,ph=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return lh(i,this,arguments)};return e.prototype=i.prototype,e},De=function(i,e){var t=i.target,s=i.global,r=i.stat,n=i.proto,o=s?Ii:r?Ii[t]:(Ii[t]||{}).prototype,l=s?wt:wt[t]||Rt(wt,t,{})[t],d=l.prototype,u,c,h,f,p,m,b,g,E;for(f in e)u=hh(s?f:t+(r?".":"#")+f,i.forced),c=!u&&o&&vn(o,f),m=l[f],c&&(i.dontCallGetSet?(E=ch(o,f),b=E&&E.value):b=o[f]),p=c&&b?b:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?g=fh(p,Ii):i.wrap&&c?g=ph(p):n&&dh(p)?g=uh(p):g=p,(i.sham||p&&p.sham||m&&m.sham)&&Rt(g,"sham",!0),Rt(l,f,g),n&&(h=t+"Prototype",vn(wt,h)||Rt(wt,h,{}),Rt(wt[h],f,p),i.real&&d&&(u||!d[f])&&Rt(d,f,p)))},Vr=nt,mh=Ve,hl=Function.prototype,vh=Vr&&Object.getOwnPropertyDescriptor,pa=mh(hl,"name"),bh=pa&&function(){}.name==="something",Sh=pa&&(!Vr||Vr&&vh(hl,"name").configurable),gh={EXISTS:pa,PROPER:bh,CONFIGURABLE:Sh},fl={},yh=Math.ceil,Th=Math.floor,Eh=Math.trunc||function(e){var t=+e;return(t>0?Th:yh)(t)},$h=Eh,ma=function(i){var e=+i;return e!==e||e===0?0:$h(e)},kh=ma,Ph=Math.max,Ah=Math.min,_h=function(i,e){var t=kh(i);return t<0?Ph(t+e,0):Ah(t,e)},wh=ma,Rh=Math.min,Ch=function(i){return i>0?Rh(wh(i),9007199254740991):0},Dh=Ch,va=function(i){return Dh(i.length)},Ih=mi,Nh=_h,xh=va,bn=function(i){return function(e,t,s){var r=Ih(e),n=xh(r),o=Nh(s,n),l;if(i&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in r)&&r[o]===t)return i||o||0;return!i&&-1}},Lh={includes:bn(!0),indexOf:bn(!1)},Oh=Pe,Xs=Ve,Mh=mi,Bh=Lh.indexOf,Vh=ha,Sn=Oh([].push),Fh=function(i,e){var t=Mh(i),s=0,r=[],n;for(n in t)!Xs(Vh,n)&&Xs(t,n)&&Sn(r,n);for(;e.length>s;)Xs(t,n=e[s++])&&(~Bh(r,n)||Sn(r,n));return r},pl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Uh=Fh,jh=pl,Hh=Object.keys||function(e){return Uh(e,jh)},Gh=nt,Yh=Wo,qh=St,zh=We,Wh=mi,Qh=Hh;fl.f=Gh&&!Yh?Object.defineProperties:function(e,t){zh(e);for(var s=Wh(t),r=Qh(t),n=r.length,o=0,l;n>o;)qh.f(e,l=r[o++],s[l]);return e};var Kh=gt,ml=Kh("document","documentElement"),Jh=We,Xh=fl,gn=pl,Zh=ha,ef=ml,tf=oa,sf=ca,yn=">",Tn="<",Fr="prototype",Ur="script",vl=sf("IE_PROTO"),Zs=function(){},bl=function(i){return Tn+Ur+yn+i+Tn+"/"+Ur+yn},En=function(i){i.write(bl("")),i.close();var e=i.parentWindow.Object;return i=null,e},rf=function(){var i=tf("iframe"),e="java"+Ur+":",t;return i.style.display="none",ef.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(bl("document.F=Object")),t.close(),t.F},Ni,Xi=function(){try{Ni=new ActiveXObject("htmlfile")}catch(e){}Xi=typeof document!="undefined"?document.domain&&Ni?En(Ni):rf():En(Ni);for(var i=gn.length;i--;)delete Xi[Fr][gn[i]];return Xi()};Zh[vl]=!0;var Sl=Object.create||function(e,t){var s;return e!==null?(Zs[Fr]=Jh(e),s=new Zs,Zs[Fr]=null,s[vl]=e):s=Xi(),t===void 0?s:Xh.f(s,t)},af=ke,nf=!af(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),of=Ve,lf=ne,uf=bs,df=ca,cf=nf,$n=df("IE_PROTO"),jr=Object,hf=jr.prototype,gl=cf?jr.getPrototypeOf:function(i){var e=uf(i);if(of(e,$n))return e[$n];var t=e.constructor;return lf(t)&&e instanceof t?t.prototype:e instanceof jr?hf:null},ff=vi,ba=function(i,e,t,s){return s&&s.enumerable?i[e]=t:ff(i,e,t),i},pf=ke,mf=ne,vf=ze,bf=Sl,kn=gl,Sf=ba,gf=ce,Hr=gf("iterator"),yl=!1,Ge,er,tr;[].keys&&(tr=[].keys(),"next"in tr?(er=kn(kn(tr)),er!==Object.prototype&&(Ge=er)):yl=!0);var yf=!vf(Ge)||pf(function(){var i={};return Ge[Hr].call(i)!==i});yf?Ge={}:Ge=bf(Ge);mf(Ge[Hr])||Sf(Ge,Hr,function(){return this});var Tl={IteratorPrototype:Ge,BUGGY_SAFARI_ITERATORS:yl},Tf=ce,Ef=Tf("toStringTag"),El={};El[Ef]="z";var Sa=String(El)==="[object z]",$f=Sa,kf=ne,Zi=fi,Pf=ce,Af=Pf("toStringTag"),_f=Object,wf=Zi(function(){return arguments}())=="Arguments",Rf=function(i,e){try{return i[e]}catch(t){}},Si=$f?Zi:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Rf(e=_f(i),Af))=="string"?t:wf?Zi(e):(s=Zi(e))=="Object"&&kf(e.callee)?"Arguments":s},Cf=Sa,Df=Si,If=Cf?{}.toString:function(){return"[object "+Df(this)+"]"},Nf=Sa,xf=St.f,Lf=vi,Of=Ve,Mf=If,Bf=ce,Pn=Bf("toStringTag"),ga=function(i,e,t,s){if(i){var r=t?i:i.prototype;Of(r,Pn)||xf(r,Pn,{configurable:!0,value:e}),s&&!Nf&&Lf(r,"toString",Mf)}},Vf=Tl.IteratorPrototype,Ff=Sl,Uf=Ss,jf=ga,Hf=Ht,Gf=function(){return this},Yf=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Ff(Vf,{next:Uf(+!s,t)}),jf(i,r,!1,!0),Hf[r]=Gf,i},qf=De,zf=ge,$l=gh,Wf=Yf,Qf=gl,Kf=ga,An=ba,Jf=ce,_n=Ht,kl=Tl,Xf=$l.PROPER;$l.CONFIGURABLE;kl.IteratorPrototype;var xi=kl.BUGGY_SAFARI_ITERATORS,ir=Jf("iterator"),wn="keys",Li="values",Rn="entries",Zf=function(){return this},ep=function(i,e,t,s,r,n,o){Wf(t,e,s);var l=function(E){if(E===r&&f)return f;if(!xi&&E in c)return c[E];switch(E){case wn:return function(){return new t(this,E)};case Li:return function(){return new t(this,E)};case Rn:return function(){return new t(this,E)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[ir]||c["@@iterator"]||r&&c[r],f=!xi&&h||l(r),p=e=="Array"&&c.entries||h,m,b,g;if(p&&(m=Qf(p.call(new i)),m!==Object.prototype&&m.next&&(Kf(m,d,!0,!0),_n[d]=Zf)),Xf&&r==Li&&h&&h.name!==Li&&(u=!0,f=function(){return zf(h,this)}),r)if(b={values:l(Li),keys:n?f:l(wn),entries:l(Rn)},o)for(g in b)(xi||u||!(g in c))&&An(c,g,b[g]);else qf({target:e,proto:!0,forced:xi||u},b);return o&&c[ir]!==f&&An(c,ir,f,{name:r}),_n[e]=f,b},tp=function(i,e){return{value:i,done:e}},ip=mi,Cn=Ht,Pl=rl;St.f;var sp=ep,Oi=tp,Al="Array Iterator",rp=Pl.set,ap=Pl.getterFor(Al);sp(Array,"Array",function(i,e){rp(this,{type:Al,target:ip(i),index:0,kind:e})},function(){var i=ap(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Oi(void 0,!0)):t=="keys"?Oi(s,!1):t=="values"?Oi(e[s],!1):Oi([s,e[s]],!1)},"values");Cn.Arguments=Cn.Array;var np=ce,op=Ht,lp=np("iterator"),up=Array.prototype,dp=function(i){return i!==void 0&&(op.Array===i||up[lp]===i)},cp=Si,Dn=vs,hp=pi,fp=Ht,pp=ce,mp=pp("iterator"),_l=function(i){if(!hp(i))return Dn(i,mp)||Dn(i,"@@iterator")||fp[cp(i)]},vp=ge,bp=yt,Sp=We,gp=ms,yp=_l,Tp=TypeError,Ep=function(i,e){var t=arguments.length<2?yp(i):e;if(bp(t))return Sp(vp(t,i));throw Tp(gp(i)+" is not iterable")},$p=ge,In=We,kp=vs,Pp=function(i,e,t){var s,r;In(i);try{if(s=kp(i,"return"),!s){if(e==="throw")throw t;return t}s=$p(s,i)}catch(n){r=!0,s=n}if(e==="throw")throw t;if(r)throw s;return In(s),t},Ap=gs,_p=ge,wp=We,Rp=ms,Cp=dp,Dp=va,Nn=fs,Ip=Ep,Np=_l,xn=Pp,xp=TypeError,es=function(i,e){this.stopped=i,this.result=e},Ln=es.prototype,ya=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=Ap(e,s),u,c,h,f,p,m,b,g=function(y){return u&&xn(u,"normal",y),new es(!0,y)},E=function(y){return r?(wp(y),l?d(y[0],y[1],g):d(y[0],y[1])):l?d(y,g):d(y)};if(n)u=i.iterator;else if(o)u=i;else{if(c=Np(i),!c)throw xp(Rp(i)+" is not iterable");if(Cp(c)){for(h=0,f=Dp(i);f>h;h++)if(p=E(i[h]),p&&Nn(Ln,p))return p;return new es(!1)}u=Ip(i,c)}for(m=n?i.next:u.next;!(b=_p(m,u)).done;){try{p=E(b.value)}catch(y){xn(u,"throw",y)}if(typeof p=="object"&&p&&Nn(Ln,p))return p}return new es(!1)},Lp=da,Op=St,Mp=Ss,Bp=function(i,e,t){var s=Lp(e);s in i?Op.f(i,s,Mp(0,t)):i[s]=t},Vp=De,Fp=ya,Up=Bp;Vp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Fp(e,function(s,r){Up(t,s,r)},{AS_ENTRIES:!0}),t}});var jp=la,Hp=jp.Object.fromEntries,Gp={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},Yp=Gp,qp=le,zp=Si,Wp=vi,On=Ht,Qp=ce,Mn=Qp("toStringTag");for(var sr in Yp){var Bn=qp[sr],rr=Bn&&Bn.prototype;rr&&zp(rr)!==Mn&&Wp(rr,Mn,sr),On[sr]=On.Array}var Kp=Hp,Jp=Kp,Xp=Jp,Zp=Xp,Vt=cs(Zp),em=fi,ys=typeof process!="undefined"&&em(process)=="process",tm=St,im=function(i,e,t){return tm.f(i,e,t)},sm=gt,rm=im,am=ce,nm=nt,Vn=am("species"),om=function(i){var e=sm(i);nm&&e&&!e[Vn]&&rm(e,Vn,{configurable:!0,get:function(){return this}})},lm=fs,um=TypeError,dm=function(i,e){if(lm(e,i))return i;throw um("Incorrect invocation")},cm=Pe,hm=ne,Gr=ua,fm=cm(Function.toString);hm(Gr.inspectSource)||(Gr.inspectSource=function(i){return fm(i)});var wl=Gr.inspectSource,pm=Pe,mm=ke,Rl=ne,vm=Si,bm=gt,Sm=wl,Cl=function(){},gm=[],Dl=bm("Reflect","construct"),Ta=/^\s*(?:class|function)\b/,ym=pm(Ta.exec),Tm=!Ta.exec(Cl),ei=function(e){if(!Rl(e))return!1;try{return Dl(Cl,gm,e),!0}catch(t){return!1}},Il=function(e){if(!Rl(e))return!1;switch(vm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Tm||!!ym(Ta,Sm(e))}catch(t){return!0}};Il.sham=!0;var Em=!Dl||mm(function(){var i;return ei(ei.call)||!ei(Object)||!ei(function(){i=!0})||i})?Il:ei,$m=Em,km=ms,Pm=TypeError,Am=function(i){if($m(i))return i;throw Pm(km(i)+" is not a constructor")},Fn=We,_m=Am,wm=pi,Rm=ce,Cm=Rm("species"),Nl=function(i,e){var t=Fn(i).constructor,s;return t===void 0||wm(s=Fn(t)[Cm])?e:_m(s)},Dm=Pe,Im=Dm([].slice),Nm=TypeError,xm=function(i,e){if(i<e)throw Nm("Not enough arguments");return i},Lm=ps,xl=/(?:ipad|iphone|ipod).*applewebkit/i.test(Lm),Se=le,Om=nl,Mm=gs,Un=ne,Bm=Ve,Ll=ke,jn=ml,Vm=Im,Hn=oa,Fm=xm,Um=xl,jm=ys,Yr=Se.setImmediate,qr=Se.clearImmediate,Hm=Se.process,ar=Se.Dispatch,Gm=Se.Function,Gn=Se.MessageChannel,Ym=Se.String,nr=0,ni={},Yn="onreadystatechange",di,ft,or,lr;Ll(function(){di=Se.location});var Ea=function(i){if(Bm(ni,i)){var e=ni[i];delete ni[i],e()}},ur=function(i){return function(){Ea(i)}},qn=function(i){Ea(i.data)},zn=function(i){Se.postMessage(Ym(i),di.protocol+"//"+di.host)};(!Yr||!qr)&&(Yr=function(e){Fm(arguments.length,1);var t=Un(e)?e:Gm(e),s=Vm(arguments,1);return ni[++nr]=function(){Om(t,void 0,s)},ft(nr),nr},qr=function(e){delete ni[e]},jm?ft=function(i){Hm.nextTick(ur(i))}:ar&&ar.now?ft=function(i){ar.now(ur(i))}:Gn&&!Um?(or=new Gn,lr=or.port2,or.port1.onmessage=qn,ft=Mm(lr.postMessage,lr)):Se.addEventListener&&Un(Se.postMessage)&&!Se.importScripts&&di&&di.protocol!=="file:"&&!Ll(zn)?(ft=zn,Se.addEventListener("message",qn,!1)):Yn in Hn("script")?ft=function(i){jn.appendChild(Hn("script"))[Yn]=function(){jn.removeChild(this),Ea(i)}}:ft=function(i){setTimeout(ur(i),0)});var Ol={set:Yr,clear:qr},Ml=function(){this.head=null,this.tail=null};Ml.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 Bl=Ml,qm=ps,zm=/ipad|iphone|ipod/i.test(qm)&&typeof Pebble!="undefined",Wm=ps,Qm=/web0s(?!.*chrome)/i.test(Wm),bt=le,Wn=gs,Km=fa.f,dr=Ol.set,Jm=Bl,Xm=xl,Zm=zm,ev=Qm,cr=ys,Qn=bt.MutationObserver||bt.WebKitMutationObserver,Kn=bt.document,Jn=bt.process,Mi=bt.Promise,Xn=Km(bt,"queueMicrotask"),zr=Xn&&Xn.value,Ct,hr,fr,Bi,Zn;if(!zr){var Vi=new Jm,Fi=function(){var i,e;for(cr&&(i=Jn.domain)&&i.exit();e=Vi.get();)try{e()}catch(t){throw Vi.head&&Ct(),t}i&&i.enter()};!Xm&&!cr&&!ev&&Qn&&Kn?(hr=!0,fr=Kn.createTextNode(""),new Qn(Fi).observe(fr,{characterData:!0}),Ct=function(){fr.data=hr=!hr}):!Zm&&Mi&&Mi.resolve?(Bi=Mi.resolve(void 0),Bi.constructor=Mi,Zn=Wn(Bi.then,Bi),Ct=function(){Zn(Fi)}):cr?Ct=function(){Jn.nextTick(Fi)}:(dr=Wn(dr,bt),Ct=function(){dr(Fi)}),zr=function(i){Vi.head||Ct(),Vi.add(i)}}var tv=zr,iv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},$a=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},sv=le,Gt=sv.Promise,Vl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",rv=Vl,av=ys,nv=!rv&&!av&&typeof window=="object"&&typeof document=="object",ov=le,oi=Gt,lv=ne,uv=cl,dv=wl,cv=ce,hv=nv,fv=Vl,pr=Ko,eo=oi&&oi.prototype,pv=cv("species"),Wr=!1,Fl=lv(ov.PromiseRejectionEvent),mv=uv("Promise",function(){var i=dv(oi),e=i!==String(oi);if(!e&&pr===66||!(eo.catch&&eo.finally))return!0;if(!pr||pr<51||!/native code/.test(i)){var t=new oi(function(n){n(1)}),s=function(n){n(function(){},function(){})},r=t.constructor={};if(r[pv]=s,Wr=t.then(function(){})instanceof s,!Wr)return!0}return!e&&(hv||fv)&&!Fl}),gi={CONSTRUCTOR:mv,REJECTION_EVENT:Fl,SUBCLASSING:Wr},Yt={},to=yt,vv=TypeError,bv=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw vv("Bad Promise constructor");e=s,t=r}),this.resolve=to(e),this.reject=to(t)};Yt.f=function(i){return new bv(i)};var Sv=De,as=ys,at=le,yi=ge,gv=ba,yv=ga,Tv=om,Ev=yt,Qr=ne,$v=ze,kv=dm,Pv=Nl,Ul=Ol.set,ka=tv,Av=iv,_v=$a,wv=Bl,jl=rl,Kr=Gt,Pa=gi,Hl=Yt,Ts="Promise",Gl=Pa.CONSTRUCTOR,Rv=Pa.REJECTION_EVENT;Pa.SUBCLASSING;var mr=jl.getterFor(Ts),Cv=jl.set,Dv=Kr&&Kr.prototype,xt=Kr,vr=Dv,Yl=at.TypeError,Jr=at.document,Aa=at.process,Xr=Hl.f,Iv=Xr,Nv=!!(Jr&&Jr.createEvent&&at.dispatchEvent),ql="unhandledrejection",xv="rejectionhandled",io=0,zl=1,Lv=2,_a=1,Wl=2,Ui,so,Ov,Ql=function(i){var e;return $v(i)&&Qr(e=i.then)?e:!1},Kl=function(i,e){var t=e.value,s=e.state==zl,r=s?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{r?(s||(e.rejection===Wl&&Bv(e),e.rejection=_a),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===i.promise?o(Yl("Promise-chain cycle")):(u=Ql(d))?yi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Jl=function(i,e){i.notified||(i.notified=!0,ka(function(){for(var t=i.reactions,s;s=t.get();)Kl(s,i);i.notified=!1,e&&!i.rejection&&Mv(i)}))},Xl=function(i,e,t){var s,r;Nv?(s=Jr.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),at.dispatchEvent(s)):s={promise:e,reason:t},!Rv&&(r=at["on"+i])?r(s):i===ql&&Av("Unhandled promise rejection",t)},Mv=function(i){yi(Ul,at,function(){var e=i.facade,t=i.value,s=ro(i),r;if(s&&(r=_v(function(){as?Aa.emit("unhandledRejection",t,e):Xl(ql,e,t)}),i.rejection=as||ro(i)?Wl:_a,r.error))throw r.value})},ro=function(i){return i.rejection!==_a&&!i.parent},Bv=function(i){yi(Ul,at,function(){var e=i.facade;as?Aa.emit("rejectionHandled",e):Xl(xv,e,i.value)})},Lt=function(i,e,t){return function(s){i(e,s,t)}},Mt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Lv,Jl(i,!0))},Zr=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Yl("Promise can't be resolved itself");var s=Ql(e);s?ka(function(){var r={done:!1};try{yi(s,e,Lt(Zr,r,i),Lt(Mt,r,i))}catch(n){Mt(r,n,i)}}):(i.value=e,i.state=zl,Jl(i,!1))}catch(r){Mt({done:!1},r,i)}}};Gl&&(xt=function(e){kv(this,vr),Ev(e),yi(Ui,this);var t=mr(this);try{e(Lt(Zr,t),Lt(Mt,t))}catch(s){Mt(t,s)}},vr=xt.prototype,Ui=function(e){Cv(this,{type:Ts,done:!1,notified:!1,parent:!1,reactions:new wv,rejection:!1,state:io,value:void 0})},Ui.prototype=gv(vr,"then",function(e,t){var s=mr(this),r=Xr(Pv(this,xt));return s.parent=!0,r.ok=Qr(e)?e:!0,r.fail=Qr(t)&&t,r.domain=as?Aa.domain:void 0,s.state==io?s.reactions.add(r):ka(function(){Kl(r,s)}),r.promise}),so=function(){var i=new Ui,e=mr(i);this.promise=i,this.resolve=Lt(Zr,e),this.reject=Lt(Mt,e)},Hl.f=Xr=function(i){return i===xt||i===Ov?new so(i):Iv(i)});Sv({global:!0,constructor:!0,wrap:!0,forced:Gl},{Promise:xt});yv(xt,Ts,!1,!0);Tv(Ts);var Vv=ce,Zl=Vv("iterator"),eu=!1;try{var Fv=0,ao={next:function(){return{done:!!Fv++}},return:function(){eu=!0}};ao[Zl]=function(){return this},Array.from(ao,function(){throw 2})}catch(i){}var Uv=function(i,e){if(!e&&!eu)return!1;var t=!1;try{var s={};s[Zl]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},jv=Gt,Hv=Uv,Gv=gi.CONSTRUCTOR,tu=Gv||!Hv(function(i){jv.all(i).then(void 0,function(){})}),Yv=De,qv=ge,zv=yt,Wv=Yt,Qv=$a,Kv=ya,Jv=tu;Yv({target:"Promise",stat:!0,forced:Jv},{all:function(e){var t=this,s=Wv.f(t),r=s.resolve,n=s.reject,o=Qv(function(){var l=zv(t.resolve),d=[],u=0,c=1;Kv(e,function(h){var f=u++,p=!1;c++,qv(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||r(d))},n)}),--c||r(d)});return o.error&&n(o.value),s.promise}});var Xv=De,Zv=gi.CONSTRUCTOR,no=Gt;no&&no.prototype;Xv({target:"Promise",proto:!0,forced:Zv,real:!0},{catch:function(i){return this.then(void 0,i)}});var eb=De,tb=ge,ib=yt,sb=Yt,rb=$a,ab=ya,nb=tu;eb({target:"Promise",stat:!0,forced:nb},{race:function(e){var t=this,s=sb.f(t),r=s.reject,n=rb(function(){var o=ib(t.resolve);ab(e,function(l){tb(o,t,l).then(s.resolve,r)})});return n.error&&r(n.value),s.promise}});var ob=De,lb=ge,ub=Yt,db=gi.CONSTRUCTOR;ob({target:"Promise",stat:!0,forced:db},{reject:function(e){var t=ub.f(this);return lb(t.reject,void 0,e),t.promise}});var cb=We,hb=ze,fb=Yt,iu=function(i,e){if(cb(i),hb(e)&&e.constructor===i)return e;var t=fb.f(i),s=t.resolve;return s(e),t.promise},pb=De,mb=gt,vb=qd,bb=Gt,Sb=gi.CONSTRUCTOR,gb=iu,yb=mb("Promise"),Tb=!Sb;pb({target:"Promise",stat:!0,forced:vb},{resolve:function(e){return gb(Tb&&this===yb?bb:this,e)}});var Eb=De,ea=Gt,$b=ke,kb=gt,Pb=ne,Ab=Nl,oo=iu,_b=ea&&ea.prototype,wb=!!ea&&$b(function(){_b.finally.call({then:function(){}},function(){})});Eb({target:"Promise",proto:!0,real:!0,forced:wb},{finally:function(i){var e=Ab(this,kb("Promise")),t=Pb(i);return this.then(t?function(s){return oo(e,i()).then(function(){return s})}:i,t?function(s){return oo(e,i()).then(function(){throw s})}:i)}});var Rb=gt,wa=Rb,Cb=wa,Db=Cb("Promise","finally"),Ib=Db,Nb=Ib,xb=Nb,Lb=xb,Es=cs(Lb),ae;(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"})(ae||(ae={}));var Re=(i,e=0,t=ae.OFFSET_P)=>{switch(t){case ae.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ae.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ae.DASH_CMAF_OFFSET_P:{if(e===0)return i;const s=new URL(i);return s.searchParams.set("offset_p",e.toFixed(0)),s.toString()}default:a.assertNever(t)}return i};const lo=(i,e)=>{var t;switch(e){case ae.OFFSET_P:return NaN;case ae.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ae.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var P=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.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,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||a.isNonNullable(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Ob=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.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 O;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(O||(O={}));const Mb=5,Bb=5,Vb=500,uo=7e3;class Fb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new X(O.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&s!==O.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case O.PLAYING:case O.PAUSED:case O.READY:break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case O.PLAYING:break;case O.PAUSED:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.READY:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case O.PLAYING:this.videoState.startTransitionTo(O.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case O.PAUSED:break;case O.READY:this.videoState.startTransitionTo(O.PAUSED),this.videoState.setState(O.PAUSED);break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}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(Ob(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(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(a.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new a.Subject;e.add(r.pipe(a.debounce(Vb)).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===B.Applying||Math.abs(l-n)>Mb)&&r.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),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Bb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(O.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(O.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:B.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PAUSED||e===O.PLAYING)&&(this.videoState.setState(O.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PLAYING||e===O.PAUSED)&&(this.videoState.setState(O.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===O.READY&&this.videoState.setState(O.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==O.STOPPED&&this.videoState.setState(O.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=s[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=Re(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===B.Applying||s.state===B.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(uo).subscribe(()=>n(`timeout(${uo})`)))});Es(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Ub=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&s&&(e==null||e())}}},!0)},jb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,s=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,b;const g=Vt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),S=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=S!=null?S:v*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const E=(m=g["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(b={1:!0,0:!1}[g["x-reused"]])!==null&&b!==void 0?b:void 0;s.next(E),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...b){return d(this),p(...b)},f.progress=function(...b){return u(this),m(...b)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},Ft=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Hb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Ft}),!0),Gb=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,n]=s.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(s.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),s.request.url=o.toString(),s.request.range=void 0}t(s)}}},!0)};const Ce=(i,e,t,{equal:s=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=i.getState();s(c,h)&&i.setState(c)},n)),s(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},Tt=(i,e,t)=>Ce(e,()=>i.loop,s=>{a.isNonNullable(s)&&(i.loop=s)},{onError:t}),Qe=(i,e,t,s)=>Ce(e,()=>({muted:i.muted,volume:i.volume}),r=>{a.isNonNullable(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),ot=(i,e,t,s)=>Ce(e,()=>i.playbackRate,r=>{a.isNonNullable(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Yb=i=>["__",i.language,i.label].join("|"),qb=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class Fe{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,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Ce(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},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="internal"))),onError:r})),this.subscription.add(Ce(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:r})),this.subscription.add(Ce(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:r})),this.subscription.add(Ce(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 s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),a.filterChanged((s,r)=>s.length===r.length&&s.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),a.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),a.filterChanged()).subscribe(this.current$));const t=s=>{var r,n;return this.applyCueSettings((n=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(s=>{var r,n;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Fe.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:n}=e,o=e.id?e.id:Yb(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(s=this.internalTracks.get(o))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:n})=>!this.internalTracks.has(s)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}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)||!qb(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"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Ra=i=>{i.removeAttribute("src"),i.load()},zb=i=>{try{i.pause(),i.playbackRate=0,Ra(i),i.remove()}catch(e){console.error(e)}};class Wb{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 ta=window.WeakMap?new WeakMap:new Wb,Ke=i=>{let e=i.querySelector("video");const t=!!e;return e?Ra(e):(e=document.createElement("video"),i.appendChild(e)),ta.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Je=i=>{const e=ta.get(i);ta.delete(i),e?Ra(i):zb(i)};class $s{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 su=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},co=i=>{const e=su(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Qb=i=>{const e=su(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},ia=3;class Kb{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<ia&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||ia))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?s(t,n):l?s(r,e):r<e&&n>t?(s(t,n),s(r,e)):s(r,n))})}destroy(){this._buffer=[]}}var ru=(i,e,t=ia)=>{let s=0,r=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,r=l,!t)return{from:s,to:r};for(let d=n-1;d>=0;d--)i.end(d)+t>=s&&(s=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=r&&(r=i.end(d))}}return{from:s,to:r}};const Xe=i=>{const e=v=>a.fromEvent(i,v).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=a.merge(...t.map(v=>a.fromEvent(i,v))).pipe(a.map(v=>v.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>ru(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}))),d=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 v;const S=i.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=i.error)!==null&&v!==void 0?v:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(v=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(v)&&p>=i.duration-f&&v<=f&&h.next(p),p=v});const m=a.fromEvent(i,"enterpictureinpicture"),b=a.fromEvent(i,"leavepictureinpicture"),g=new a.ValueSubject(Qb(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));const E=new a.ValueSubject(co(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>co(i))).subscribe(E),{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$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:g,inFullscreen$:E}},Ca=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Jb=De,Xb=bs,Zb=va,eS=ma;Jb({target:"Array",proto:!0},{at:function(e){var t=Xb(this),s=Zb(t),r=eS(e),n=r>=0?r:s+r;return n<0||n>=s?void 0:t[n]}});var tS=wa,iS=tS("Array","at"),sS=iS,rS=sS,aS=rS,nS=aS,Le=cs(nS);let Da=!1,He={};const oS=i=>{Da=i},lS=()=>{He={}},uS=i=>{i(He)},ji=(i,e)=>{var t;Da&&(He.meta=(t=He.meta)!==null&&t!==void 0?t:{},He.meta[i]=e)};class Oe{constructor(e){this.name=e}next(e){var t,s;if(!Da)return;He.series=(t=He.series)!==null&&t!==void 0?t:{};const r=(s=He.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),He.series[this.name]=r}}var mt;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(mt||(mt={}));const dS=new Oe("best_bitrate"),cS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class hS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const qt=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,b,g;const E=s.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*E*s.containerSizeFactor,height:e.height*E*s.containerSizeFactor},v=y&&a.videoSizeToQuality(y),S=s.considerPlaybackRate&&a.isNonNullable(l)?l:1,T=i.filter(I=>!a.isInvariantQuality(I.quality)).sort((I,A)=>a.isHigher(I.quality,A.quality)?-1:1),k=(p=Le(T,-1))===null||p===void 0?void 0:p.quality,L=(m=Le(T,0))===null||m===void 0?void 0:m.quality,j=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&a.isLower(r.max,r.min)||a.isNonNullable(r.min)&&L&&a.isHigher(r.min,L)||a.isNonNullable(r.max)&&k&&a.isLower(r.max,k),D=S*cS(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),x={},w=T.filter(I=>(v?a.isLower(I.quality,v):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(I.bitrate)?t-n>=I.bitrate*D:!0)?s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<s.minBufferToSwitchUp&&a.isHigher(I.quality,d.quality)?(x[I.quality]=mt.Buffer,!1):!!c&&a.isHigherOrEqual(I.quality,c)?(x[I.quality]=mt.DroppedFramesLimit,!1):j||(a.isNullable(r.max)||a.isLowerOrEqual(I.quality,r.max))&&(a.isNullable(r.min)||a.isHigherOrEqual(I.quality,r.min))?!0:(x[I.quality]=mt.FitsQualityLimits,!1):(x[I.quality]=mt.FitsThroughput,!1):(x[I.quality]=mt.FitsContainer,!1))[0];w&&w.bitrate&&dS.next(w.bitrate);const N=(b=w!=null?w:T[Math.ceil((T.length-1)/2)])!==null&&b!==void 0?b:i[0];N.quality!==((g=u==null?void 0:u.last)===null||g===void 0?void 0:g.quality)&&h({message:`
|
|
7
7
|
[available tracks] ${i.map(I=>I.quality).join(", ")}
|
|
8
8
|
|
|
9
9
|
[limit params]
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
[selected track] ${N.quality}
|
|
27
27
|
`});const z=N&&u&&u.history[N.id]&&a.now()-u.history[N.id]<=s.trackCooldown&&(!u.last||N.id!==u.last.id);if(N!=null&&N.id&&u&&!z&&u.recordSelection(N),z&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),h({message:`
|
|
28
28
|
[last selected] ${I.quality}
|
|
29
|
-
`}),I}return u==null||u.recordSwitch(N),N};var fe=i=>new URL(i).hostname;const fS=300,ns=(i,e=fS)=>new a.Observable(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(qu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()});class ks{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:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(r-n)/r;!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,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),s=a.merge(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(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||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const ti={};var V;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const re=(i,e)=>new a.Observable(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class ho{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(V.DOWNLOADING_LIB),this.textTracksManager=new Fe,this.droppedFramesManager=new ks,this.videoTracks$=new a.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new $s,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===V.DOWNLOADING_LIB||t===V.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&t!==V.STOPPED&&s!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),s){case exports.PlaybackState.STOPPED:{switch(t){case V.STOPPED:break;case V.PLAYING:case V.PAUSED:case V.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case V.STOPPED:this.prepare();break;case V.PLAYING:case V.PAUSED:case V.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case V.PLAYING:break;case V.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case V.READY:this.play();break;case V.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case V.PLAYING:this.pause(),this.liveOffset.pause();break;case V.PAUSED:break;case V.READY:this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(s)}},this.video=Ke(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Es(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ti.MediaPlayer=r.MediaPlayer,ti.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(ti.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(ti.Debug,"dashjs not loaded"),this.player=ti.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?Ca(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Gb(this.player),Ub(this.player),this.params.tuning.requestQuick&&Hb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,S)=>this.subscription.add(v.subscribe(S,s));r(ns(this.video),this.elementSize$),r(re(this.player,"error").pipe(a.map(v=>{const S=typeof v.error=="object"?v.error.code:v.error,T=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${S}`,message:T}})),e.error$),r(re(this.player,"playbackError").pipe(a.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({newQuality:v})=>{var S;return(S=this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===v))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:v})=>v===V.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ce(t.videoTrack,()=>{var v,S;const T=this.player.getQualityFor("video");return(S=(v=this.videoTracks$.getValue().find(({bitrateInfo:k})=>k.qualityIndex===T))===null||v===void 0?void 0:v.track)===null||S===void 0?void 0:S.id},v=>{var S;if(a.isNullable(v))return;const T=(S=this.videoTracks$.getValue().find(({track:k})=>k.id===v))===null||S===void 0?void 0:S.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:s}))},s)),this.subscription.add(Ce(t.autoVideoTrackSwitching,()=>{var v,S,T;return(T=(S=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||T===void 0?void 0:T.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:s})),r(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(re(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:S}})=>{var T,k;const L=this.player.getDashMetrics(),j=L.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),D=(T=L.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&T!==void 0?T:exports.HttpConnectionType.HTTP1,x=(k={1:!0,0:!1}[j])!==null&&k!==void 0?k:void 0;this.params.output.httpConnectionType$.next(D),this.params.output.httpConnectionReused$.next(x),e.hostname$.next(fe(S))}),r(re(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:S,availableFrom:T}}})=>{this.isLive$.next(S),this.availableFrom$.next(T.getTime()),S||e.duration$.next(v);const k=[],L=this.player.getQualityFor("video");let j;for(const D of this.player.getBitrateInfoListFor("video")){const x=D.qualityIndex.toString(10),F=a.videoSizeToQuality(D),w=D.bitrate/1e3,N={width:D.width,height:D.height},z=this.frameRatesByFrameHeight[D.height];if(F){const I={id:x,quality:F,bitrate:w,size:N,fps:z};k.push({track:I,bitrateInfo:D}),D.qualityIndex===L&&(j=I)}}this.videoTracks$.next(k),e.availableVideoTracks$.next(k.map(({track:D})=>D)),j&&e.currentVideoTrack$.next(j),this.videoState.setState(V.STREAM_INITIALIZED),this.videoState.startTransitionTo(V.READY)}),r(re(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const S=v.requestEndDate.getTime()-v.firstByteDate.getTime(),T=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(T,S)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=qt(this.videoTracks$.getValue().map(({track:L})=>L),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to);const k=this.videoTracks$.getValue().find(({track:L})=>L===S);k!=null&&k.bitrateInfo&&this.player.setQualityFor("video",k==null?void 0:k.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:v})=>v),a.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:v})=>v!=null?v:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:S})=>this.params.output.liveTime$.next(v+S*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(re(this.player,"playbackEnded"),e.endedEvent$),r(re(this.player,"playbackProgress").pipe(a.map(()=>ru(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(V.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),r(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(re(this.player,"playbackPaused"),()=>{this.videoState.setState(V.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),r(re(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===V.READY&&this.videoState.setState(V.READY)}),r(this.isLive$,e.isLive$),r(ns(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=jb(this.player);r(c,this.params.output.httpConnectionType$),r(h,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(a.once()),e.firstBytesEvent$),r(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(v=>v<60))}),({isLive:v,isShort:S})=>{const T=!v&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:T}}})}),r(o.pipe(a.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),r(re(this.player,"manifestLoaded"),v=>{var S,T,k,L,j,D,x;if(!((T=(S=v.data)===null||S===void 0?void 0:S.Period)===null||T===void 0)&&T.AdaptationSet){const F=[];for(const w of(L=(k=v.data)===null||k===void 0?void 0:k.Period)===null||L===void 0?void 0:L.AdaptationSet)if(w.contentType==="text"){const N=(j=w.Representation)===null||j===void 0?void 0:j.id,z=new URL((D=w.Representation)===null||D===void 0?void 0:D.BaseURL,(x=v.data)===null||x===void 0?void 0:x.baseUri).toString(),I="internal",A=w.lang;F.push({id:N,url:z,type:I,language:A})}t.internalTextTracks.startTransitionTo(F)}}),this.subscription.add(Tt(this.video,t.isLooped,s));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:b,inFullscreen$:g,pause$:E,playing$:y}=Xe(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:y,pause$:E,tracks$:this.videoTracks$.pipe(a.map(v=>v.map(({track:S})=>S)))}),this.subscription.add(Qe(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(ot(this.video,t.playbackRate,m,s)),this.subscription.add(b.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(V.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(V.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Re(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ae.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(V.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(V.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}Je(this.video),this.params.output.element$.next(void 0)}}var Ti=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}};const fo=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 lt=i=>K(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!fo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return fo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function de(){return a.now()}function au(i){return de()-i}function po(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=o=>s.test(o);return{resolve:(o,l,d=!1)=>{r(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function pS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function ts(i,e,t,s){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(d)return;a.assertNonNullable(c);const w=au(c);let N;if(w<b){N=b-w,setTimeout(g,N);return}b*=2,b>m&&(b=m),o&&o.abort(),o=new r,k()};const E=w=>(n=w,F),y=w=>(h=w,F),v=()=>(p="json",F),S=()=>{if(!d){if(--u>=0){g(),s&&s();return}d=!0,h&&h(),t&&t()}},T=w=>(f=w,F),k=()=>{c=de(),o=new r,o.open("get",i);let w=0,N,z=0;const I=()=>(a.assertNonNullable(c),Math.max(c,Math.max(N||0,z||0)));if(n&&o.addEventListener("progress",A=>{const C=de();n.updateChunk&&A.loaded>w&&(n.updateChunk(I(),A.loaded-w),w=A.loaded,N=C)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>S())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const A=o.status;if(A>=200&&A<300){if(o.response.byteLength&&n){const C=o.response.byteLength-w;C&&n.updateChunk&&n.updateChunk(I(),C)}h&&h(),o&&e(o.response)}else S()}),o.addEventListener("error",()=>{S()}),f){const A=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=de(),o.removeEventListener("readystatechange",A))};o.addEventListener("readystatechange",A)}return o.responseType=p,o.send(),F},F={withBitrateReporting:E,withParallel:T,withJSONResponse:v,withRetryCount:w=>(u=w,F),withRetryInterval:(w,N)=>(a.isNonNullable(w)&&(b=w),a.isNonNullable(N)&&(m=N),F),withTimeout:w=>(l=w,F),withFinally:y,send:k,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return F}const mS=100,vS=2e3,bS=500;let SS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-bS;if(t-e>vS){let s=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&s>0){const n=r*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>mS&&(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 gS{constructor(e,t,s,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=de(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=de()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ts(t,n,()=>r("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=de()}_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=de();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=r,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 Hi=1e4,Gi=3,yS=300,TS=2e3,ES=6e4,$S=10,kS=1,PS=500;class AS{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 SS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=po(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=po(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,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)?(!r||n.bitrate>r.bitrate)&&(r=n):(!s||s.bitrate>n.bitrate)&&(s=n));return r||s}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:s,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{pS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 gS(Gi,Hi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const S=n&&(!c||c===this.rep);return S||t("Not running!"),S},f=(S,T,k)=>{d&&d.abort(),d=ts(this.urlResolver.resolve(S,!1),T,k,()=>this._retryCallback()).withTimeout(Hi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Gi).withFinally(()=>{d=null}).send()},p=(S,T,k)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),T,k,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=S=>{const T=s.playbackRate;s.playbackRate!==S&&(t(`Playback rate switch: ${T}=>${S}`),s.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const k=de()-1e4;let L=0;for(let D=0;D<this.bufferStates.length;D++){const x=this.bufferStates[D];S=Math.min(S,x.buf),x.ts<k&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${S} drop=${L} jitter=${this.sourceJitter}`);let j=S-kS;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?m(1.15):j>1?m(1.1):j>.3?m(1.05):m(1)}},E=S=>{let T;const k=()=>T&&T.start?T.start.length:0,L=A=>T.start[A]/1e3,j=A=>T.dur[A]/1e3,D=A=>T.fragIndex+A,x=(A,C)=>({chunkIdx:D(A),startTS:L(A),dur:j(A),discontinuity:C}),F=()=>{let A=0;if(T&&T.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=C;this.sourceJitter>1&&(te+=this.sourceJitter-1);let ie=T.dur.length-1;for(;ie>=0&&(te-=T.dur[ie],!(te<=0));--ie);A=Math.min(ie,T.dur.length-1-H),A=Math.max(A,0)}return x(A,!0)},w=A=>{const C=k();if(!(C<=0)){if(a.isNonNullable(A)){for(let H=0;H<C;H++)if(L(H)>A)return x(H)}return F()}},N=A=>{const C=k(),H=A?A.chunkIdx+1:0,te=H-T.fragIndex;if(!(C<=0)){if(!A||te<0||te-C>$S)return t(`Resync: offset=${te} bChunks=${C} chunk=`+JSON.stringify(A)),F();if(!(te>=C))return x(H-T.fragIndex,!1)}},z=(A,C,H)=>{u&&u.abort(),u=ts(this.urlResolver.resolve(A,!0,this.lowLatency),C,H,()=>this._retryCallback()).withTimeout(Hi).withRetryCount(Gi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,C)=>{z(S,H=>{if(!h())return;T=H;const te=!!T.lowLatency;te!==this.lowLatency&&b(te);let ie=0;for(let pe=0;pe<T.dur.length;++pe)ie+=T.dur[pe];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(w(C))},()=>this._handleNetworkError())},nextChunk:N}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:S=>{const{videoElement:T,logger:k}=this.params;let L=E(e.jidxUrl),j,D,x,F,w=0,N,z,I;const A=()=>{N&&(clearTimeout(N),N=void 0);const G=Math.max(PS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=w+G,ye=de(),me=Math.min(1e4,he-ye);w=ye;const Te=()=>{u||h()&&L.seek(()=>{h()&&(w=de(),C(),A())})};me>0?N=window.setTimeout(()=>{this.paused?A():Te()},me):Te()},C=()=>{let G;for(;G=L.nextChunk(F);)F=G,Ie(G);const he=L.nextChunk(x);if(he){if(x&&he.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?A():(y(),this._initPlayerWith(e));return}pe(he)}else A()},H=(G,he)=>{if(!h()||!this.sourceBuffer)return;let ye,me,Te;const Et=ut=>{window.setTimeout(()=>{h()&&H(G,he)},ut)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),Et(100);else{const ut=de(),$t=T.currentTime;!this.paused&&T.buffered.length>1&&z===$t&&ut-I>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),z!==$t&&(z=$t,I=ut);const kt=this._getBufferSizeSec();if(kt>30)k(`Buffered ${kt} seconds; delaying appendBuffer`),Et(2e3);else try{this.sourceBuffer.appendBuffer(G),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:kt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch($i){if($i.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(ye=this.sourceBuffer.buffered.start(0),me=$t,me-ye>4&&this.sourceBuffer.remove(ye,me-3)),Et(1e3);else throw $i}}},te=()=>{D&&j&&(k([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(x)]),H(D,function(){D=null,C()}))},ie=G=>e.fragUrlTemplate.replace("%%id%%",G.chunkIdx),pe=G=>{h()&&p(ie(G),(he,ye)=>{if(h()){if(ye/=1e3,D=he,x=G,o=G.startTS,ye){const me=Math.min(10,G.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}te()}},()=>this._handleNetworkError())},Ie=G=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(G),!1)))},Ze=G=>{h()&&(e.cachedHeader=G,H(G,()=>{j=!0,te()}))};n=!0,L.seek(G=>{if(h()){if(w=de(),!G){A();return}F=G,!a.isNullable(S)||G.startTS>S?pe(G):(x=G,C())}},S),e.cachedHeader?Ze(e.cachedHeader):f(e.headerUrl,Ze,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.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 m=de();if(this.chunkRateEstimator.addInterval(f,m,p)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:g}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&au(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=de();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=ts(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Hi).withRetryCount(Gi).withRetryInterval(yS,TS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;lt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ES))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var M;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const _S=[M.PAUSED,M.PLAYING,M.READY],wS=[M.PAUSED,M.PLAYING,M.READY];class RS{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(M.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Fe,this.droppedFramesManager=new ks,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new $s,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Ti(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,b=Object.assign({},h.video);if(!p)continue;const g={id:f,quality:p,bitrate:m,size:b};c.push({track:g,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.MANIFEST_READY&&this.videoState.setState(M.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){r!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(M.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(wS.includes(r)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===B.Requested&&_S.includes(r)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(r){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_READY),this.dash.attachSource(Re(this.params.source.url));return;case M.MANIFEST_READY:this.videoState.startTransitionTo(M.READY),this.prepare();break;case M.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(M.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(M.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(M.PAUSED)})}return;case M.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(M.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case M.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(M.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(M.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(Re(this.params.source.url,h))}return;default:return a.assertNever(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=Ke(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(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Xe(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(a.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===M.READY&&this.videoState.setState(M.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(M.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(Tt(this.video,this.params.desiredState.isLooped,t)).add(Qe(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(ot(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const n=r&&a.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var n;switch(r.to){case M.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case M.MANIFEST_READY:case M.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 M.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case M.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.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),Je(this.video)}createLiveDashPlayer(){const e=new AS({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=qt(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}))===null||n===void 0?void 0:n.id,h=this.params.desiredState.videoTrack.getTransition(),f=this.params.desiredState.videoTrack.getState(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((h&&c||c!==f)&&this.setVideoTrack(c),p&&this.setAutoQuality(u),h||p||c!==f){const m=(o=l.find(({track:b})=>b.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===M.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Re(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}}var nu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},st=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,n=i.end(s)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const CS=i=>{const e=document.createElement("a");return e.href=i,e.origin},DS=i=>{const e=document.createElement("a");return e.href=i,e.host};class ou{constructor(e,t=[],s,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,n,o,l,d,u;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=Vt(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(DS(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class os{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=b=>{r(os._str2ua(b.substr(d))),d=b.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=Ft(m)),this._lastXhr=new ou(m,e.failoverHosts,b=>{this._lastXhr=void 0,p(b);const g=Date.now()-u;this._params.onBandwidthChange({size:b.length,duration:g,speed:8*b.length/(g/1e3)}),this._onDashCallback("loading",{size:b.length,done:!0}),n==null||n()},b=>{if(b.length-d>l&&p(b),h===0){h=Date.now();return}f=b.length-c;const g=Date.now()-h;f>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:f,duration:g,speed:8*f/(g/1e3)}),f=0,c=b.length,h=Date.now()),this._onDashCallback("loading",{size:b.length,done:!1})},o,(b,g,E)=>this._params.onError(b,g,E))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=os._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class IS{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},r=t.exec(e),n=(r==null?void 0:r[1])==="-"?-1:1,o={years:s(r==null?void 0:r[2],n),months:s(r==null?void 0:r[3],n),weeks:s(r==null?void 0:r[4],n),days:s(r==null?void 0:r[5],n),hours:s(r==null?void 0:r[6],n),minutes:s(r==null?void 0:r[7],n),seconds:s(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Ft(s)),new ou(s,t,r=>{this.attachManifest(r,t,CS(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,m,b,g,E,y,v,S,T,k,L,j,D,x,F,w;const N=u.getElementsByTagName("SegmentBase")[0],z=N&&o(N,"indexRange").split("-"),I=N&&N.getElementsByTagName("Initialization")[0],A=I&&o(I,"range").split("-");if(!A||!z){const Ie=u.parentElement;if((Ie==null?void 0:Ie.getAttribute("contentType"))==="text"){const Ze=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,G=(s?s+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),he=(b=Ie.getAttribute("lang"))!==null&&b!==void 0?b:void 0;G&&d.push({id:Ze,url:G,language:he})}return}const C=.1,H=Number((g=u.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),te=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const pe=(y=(E=u.attributes.getNamedItem("frameRate"))===null||E===void 0?void 0:E.value)!==null&&y!==void 0?y:void 0;ie=pe?Ca(pe):void 0,l.push({width:Number((v=u.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((S=u.attributes.getNamedItem("height"))===null||S===void 0?void 0:S.value),bandwidth:H,baseURL:te,failoverHosts:t,indexFrom:Number(z[0]),indexTo:Number(z[1]),initFrom:Number(A[0]),initTo:Number(A[1]),codecs:(k=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&k!==void 0?k:void 0,mimeType:(j=(L=u.attributes.getNamedItem("mimeType"))===null||L===void 0?void 0:L.value)!==null&&j!==void 0?j:void 0,fps:ie,bufferSize:C*H/8,bufferLength:C,name:(x=(D=u.attributes.getNamedItem("okQuality"))===null||D===void 0?void 0:D.value)!==null&&x!==void 0?x:void 0,id:(w=(F=u.attributes.getNamedItem("id"))===null||F===void 0?void 0:F.value)!==null&&w!==void 0?w:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),m=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,d=m}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new os({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||l(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<s.to+n){const o=this._findRef(r.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<s.length;n++){const o=s[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=s[s.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var U;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const NS=[U.PAUSED,U.PLAYING];class xS{constructor(e){this.videoState=new X(U.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Fe,this.droppedFramesManager=new ks,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,n,o;const l=[];for(const d of t){const u=(n=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Ti(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(s==null?void 0:s.length)>0){const d=[];for(const u of s){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(U.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:n})=>n===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),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(U.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!s)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===B.Requested&&NS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_LOADED),this.prepare();return;case U.MANIFEST_LOADED:this.videoState.startTransitionTo(U.INITIAL_REPRESENTATION_SELECTED);return;case U.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(U.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case U.METADATA_LOADED:this.videoState.startTransitionTo(U.READY),this.dash.updateRefsForCurrentTime();return;case U.READY:r===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed());return;case U.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(U.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Kb(this.video),this.dash=new IS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Xe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===U.PLAYING||this.videoState.getState()===U.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Tt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ot(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(a.map(l=>l.map(({track:d})=>d)))}),o(ns(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===U.READY&&this.videoState.setState(U.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(U.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),g=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let E;if(!g&&a.isNonNullable(p))E=p;else{const y=st(this.video.buffered,this.video.currentTime*1e3),v=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,S=Math.min(y/v,1);E=(d=qt(h.map(({track:k})=>k),{container:b,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:S,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:k})=>k===c))===null||l===void 0?void 0:l.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||d===void 0?void 0:d.id;const T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to)}return a.isNonNullable(E)?(u=h.find(({track:y})=>y.id===E))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,s)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===U.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(U.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?l.height<=d.height:l===d)).subscribe(l=>{const d=st(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(fe(l.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=nu(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Je(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){lt(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}var oe;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(oe||(oe={}));var ls;(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"})(ls||(ls={}));var $e;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})($e||($e={}));var Y;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(Y||(Y={}));var Ut;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ut||(Ut={}));var us;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(us||(us={}));var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class mo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,n=s.length;r<n;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,n=s.length;r<n;r++){const o=s[r];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 lu extends mo{constructor(){super(),this.listeners||mo.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 uu=class{constructor(){Object.defineProperty(this,"signal",{value:new lu,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(uu.prototype[Symbol.toStringTag]="AbortController",lu.prototype[Symbol.toStringTag]="AbortSignal");function du(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 LS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!du({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ps=du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cu=Ps?LS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ci=Ps?cu.fetch:window.fetch;Ps?cu.Request:window.Request;const Bt=Ps?uu:window.AbortController;var sa=(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 OS=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},MS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",vo=MS?OS:window.requestIdleCallback;var br,Sr;let hu=!1;try{hu=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Sr=(br=navigator.userAgent.match(/Version\/(\d+)/))===null||br===void 0?void 0:br[1])!==null&&Sr!==void 0?Sr:"",10)<16}catch(i){console.error(i)}class BS{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 s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return K(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return K(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return K(this,void 0,void 0,function*(){return new Promise(t=>{let s;hu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category: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 bo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ue{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class fu extends Ue{}class VS extends Ue{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class FS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class US extends Ue{constructor(e){super(e),this.data=this.content}}class Ei extends Ue{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class jS extends Ei{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class HS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class GS extends Ue{parseChildrenBoxes(){return zt(this.content)}}var vt;(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"})(vt||(vt={}));class YS extends Ei{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=vt.MONOSCOPIC;break;case 1:this.stereoMode=vt.TOP_BOTTOM;break;case 2:this.stereoMode=vt.LEFT_RIGHT;break;case 3:this.stereoMode=vt.STEREO_CUSTOM;break;case 4:this.stereoMode=vt.RIGHT_LEFT;break}this.cursor+=1}}class qS extends Ei{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class zS extends Ei{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class WS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class QS extends Ei{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 KS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class JS extends Ue{parseChildrenBoxes(){return zt(this.content)}}const XS={ftyp:VS,moov:FS,mdat:US,sidx:jS,trak:HS,mdia:WS,tkhd:QS,minf:KS,sv3d:GS,st3d:YS,prhd:qS,proj:JS,equi:zS,unknown:fu};class ZS{createBox(e,t){const s=XS[e];return s?new s(t):new fu(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return As.createBox(s,new DataView(e.buffer,e.byteOffset))}}const As=new ZS;function ai(i,e){const t=new TextDecoder("ascii");let s=i.byteOffset,r=[];for(;s<i.byteLength;){const n=t.decode(new DataView(i.buffer,s,1));if(n===e[r.length]?r.push(n):r=[],r.length===4&&r.join("")===e){const l=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+l>i.byteLength?null:As.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function eg(i,e){const t=[];let s=0;for(;s<i.byteLength;){const r=ai(new DataView(i.buffer,i.byteOffset+s,i.byteLength-s),e);if(r)t.push(r),s+=r.size+r.source.byteOffset;else break}return t}function zt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=As.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const tg=new TextDecoder("ascii"),ig=i=>tg.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",sg=i=>{const e=As.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:Y.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},rg=i=>{const e=eg(i,"mdat");if(e.length){const t=e.reduce((s,r)=>s+r.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},ag=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ai(i,"sv3d")){e.is3dVideo=!0;const s=ai(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=ai(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=ai(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},ng={validateData:ig,parseInit:ag,getIndexRange:()=>{},parseSegments:sg,parseFeedableSegmentChunk:rg};var $;(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"})($||($={}));var _;(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"})(_||(_={}));const So={[$.EBML]:{type:_.Master},[$.EBMLVersion]:{type:_.UnsignedInteger},[$.EBMLReadVersion]:{type:_.UnsignedInteger},[$.EBMLMaxIDLength]:{type:_.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[$.DocType]:{type:_.String},[$.DocTypeVersion]:{type:_.UnsignedInteger},[$.DocTypeReadVersion]:{type:_.UnsignedInteger},[$.Void]:{type:_.Binary},[$.Segment]:{type:_.Master},[$.SeekHead]:{type:_.Master},[$.Seek]:{type:_.Master},[$.SeekID]:{type:_.Binary},[$.SeekPosition]:{type:_.UnsignedInteger},[$.Info]:{type:_.Master},[$.TimestampScale]:{type:_.UnsignedInteger},[$.Duration]:{type:_.Float},[$.Tracks]:{type:_.Master},[$.TrackEntry]:{type:_.Master},[$.Video]:{type:_.Master},[$.Projection]:{type:_.Master},[$.ProjectionType]:{type:_.UnsignedInteger},[$.ProjectionPrivate]:{type:_.Master},[$.Chapters]:{type:_.Master},[$.Cluster]:{type:_.Master},[$.Timestamp]:{type:_.UnsignedInteger},[$.SilentTracks]:{type:_.Master},[$.SilentTrackNumber]:{type:_.UnsignedInteger},[$.Position]:{type:_.UnsignedInteger},[$.PrevSize]:{type:_.UnsignedInteger},[$.SimpleBlock]:{type:_.Binary},[$.BlockGroup]:{type:_.Master},[$.EncryptedBlock]:{type:_.Binary},[$.Attachments]:{type:_.Master},[$.Tags]:{type:_.Master},[$.Cues]:{type:_.Master},[$.CuePoint]:{type:_.Master},[$.CueTime]:{type:_.UnsignedInteger},[$.CueTrackPositions]:{type:_.Master},[$.CueTrack]:{type:_.UnsignedInteger},[$.CueClusterPosition]:{type:_.UnsignedInteger},[$.CueRelativePosition]:{type:_.UnsignedInteger},[$.CueDuration]:{type:_.UnsignedInteger},[$.CueBlockNumber]:{type:_.UnsignedInteger},[$.CueCodecState]:{type:_.UnsignedInteger},[$.CueReference]:{type:_.Master},[$.CueRefTime]:{type:_.UnsignedInteger}},pu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=ds(i,t),r=s in So,n=r?So[s].type:_.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=ds(d),h=u*Math.pow(2,(l-1)*8)+c,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:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},ds=(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},Me=(i,e)=>{switch(e){case _.SignedInteger:return i.getInt8(0);case _.UnsignedInteger:return ds(i);case _.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(i);case _.UTF8:return new TextDecoder("utf-8").decode(i);case _.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case _.Master:return i;case _.Binary:return i;default:a.assertNever(e)}},jt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=pu(s);if(!e(r))return;r.type===_.Master&&jt(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},og=i=>{if(i.getUint32(0)!==$.EBML)return!1;let e,t,s;const r=pu(i);return jt(r.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=Me(l,o):n===$.DocType?t=Me(l,o):n===$.DocTypeReadVersion&&(s=Me(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},mu=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],lg=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],ug=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return jt(i,({tag:f,type:p,value:m,valueSize:b})=>{if(f===$.SeekID){const g=Me(m,p);u=ds(g)}else f!==$.SeekPosition&&(u=void 0);return f===$.Segment?(e=m.byteOffset,t=m.byteOffset+b):f===$.Info?n=!0:f===$.SeekHead?o=!0:f===$.TimestampScale?s=Me(m,p):f===$.Duration?r=Me(m,p):f===$.SeekPosition&&u===$.Cues?d=Me(m,p):f===$.Tracks?jt(m,({tag:g,type:E,value:y})=>g===$.ProjectionType?(c=Me(y,E)===1,!1):!0):n&&o&&mu.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(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},dg=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cg=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return jt(i,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&r(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=Me(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=Me(u,d));break;default:t&&mu.includes(l)&&(s=!0)}return!(t&&s)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:Y.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},hg=i=>{let e=0,t=!1;try{jt(i,s=>s.tag===$.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):lg.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},fg={validateData:og,parseInit:ug,getIndexRange:dg,parseSegments:cg,parseFeedableSegmentChunk:hg},vu=1e4,pg=3e4,mg=5e3,vg=vu,bg=({id:i,width:e,height:t,bitrate:s,fps:r,quality:n})=>{var o;const l=(o=n?Ti(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},Sg=({id:i,bitrate:e})=>({id:i,bitrate:e}),gg=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Le(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Le(i,-1)},yg=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Yi=i=>{const e=[];let t=0,s=i.length-1;for(;t<vu&&s>=0;)e.unshift(i[s]),t+=i[s].time.to-i[s].time.from,s--;return e};class go{constructor(e,t,s,r,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1,manifest:u}){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.isSeekingLive=!1,this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Bt,this.destroyAbortController=new Bt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){const h=this.representations.get(c);a.assertNonNullable(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new BS(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 g=Math.min(this.bufferLimit,bo(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield R(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(a.assertNonNullable(f,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield R(void 0);this.searchGaps(p,h),yield yield R(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);a.assertNonNullable(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(a.isNullable(p)||a.isNullable(f)?yield yield R(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield R(p)),f=this.segments.get(c),a.assertNonNullable(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.searchGaps(f,h),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield R(void 0);for(const g of this.representations.keys()){const E=c.find(S=>S.id===g);E&&this.representations.set(g,E);const y=this.representations.get(g);if(!y)return yield R(void 0);const v=Yi(y.segmentReference.segments);this.segments.set(y.id,v)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,f=this.representations.get(h);a.assertNonNullable(f);const p=Yi(f.segmentReference.segments),m=this.initData.get(f.id);if(a.assertNonNullable(m,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(m instanceof ArrayBuffer))return yield R(void 0);const b=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),b&&(yield yield R(this.sourceBufferTaskQueue.remove(b.from*1e3,b.to*1e3,this.destroyAbortController.signal))),this.searchGaps(p,f),yield yield R(this.sourceBufferTaskQueue.append(m,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isLive=!!(u!=null&&u.dynamic),this.container=s,s){case Ut.MP4:this.containerParser=ng;break;case Ut.WEBM:this.containerParser=fg;break;default:a.assertNever(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Bt,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),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=st(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&bo(this.sourceBuffer.buffered)>=this.bufferLimit){const u=st(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=Le(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Y.FED&&!l.length&&st(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Le(s,-1);d&&d.status===Y.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let s=0;for(const r of e)r.time.from-s>0&&this.gaps.push({representation:t.id,from:s,to:r.time.from}),s=r.time.to;a.isNonNullable(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o)return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:Y.NONE,size:void 0})),d=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(r=Le(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.round(u)>=Math.round(h.time.from)&&Math.round(u)<=Math.round(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=Yi(l);this.segments.set(o.id,[...h])}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const b=f<=s&&p>=s,g=f>s||b||m===0&&s===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+E||p<=s+E;return(h===Y.NONE||h===Y.PARTIALLY_EJECTED&&g&&y&&this.sourceBuffer&&!sa(this.sourceBuffer.buffered,s))&&g&&y});if(r===-1)return[];if(t!==$e.BYTE_RANGE)return e.slice(r,r+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=r;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===Y.NONE||f.status===Y.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,s="auto"){return K(this,void 0,void 0,function*(){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case $e.BYTE_RANGE:{r=t.segmentReference.url,n={from:Le(e,0).byte.from,to:Le(e,-1).byte.to};break}case $e.TEMPLATE:{const u=Le(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=Y.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return be(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,u=>{if(u.name!=="AbortError"){for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)}})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=st((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=Y.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const m of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])m.status===Y.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=Y.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===$e.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const g=p?f.byte.from-s:0,E=p?f.byte.to-s:e.byteLength,y=g<r,v=E<=r;if(f.status===Y.DOWNLOADING&&y&&v){f.status=Y.DOWNLOADED,this.activeSegments.delete(h);const S=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(S,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(m,r-g),h.loadedBytes>h.feedingBytes)){const S=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?S:this.containerParser.parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(f.status=Y.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(k=>{if(n.aborted)o();else if(k)h.fedBytes+=T.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Y.PARTIALLY_FED||e.status===Y.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Y.NONE),e.status=Y.PARTIALLY_EJECTED):e.status=Y.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=vo(()=>Es(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return K(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return be(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>K(this,void 0,void 0,function*(){if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,this.isLive?Yi(c):c),d&&this.parsedInitData.set(e.id,d)})).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&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,s=!1){return K(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let r=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;r+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===Y.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){r=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status===Y.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===Y.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===Y.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=vo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:n})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:n}=r;if(n!==Y.FED&&n!==Y.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),l=Math.ceil(r.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?r.status=Y.PARTIALLY_EJECTED:r.status=Y.NONE)}}}var Ot;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Ot||(Ot={}));class Tg{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!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 Bt,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(r){return be(this,arguments,function*(){let n=r;this.requestQuic&&(n=Ft(n));const o=yield yield R(ci(n,{signal:this.abortAllController.signal}).catch(ii));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(r,{rangeMethod:n=this.compatibilityMode?Ot.HEADER:Ot.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return be(this,arguments,function*(){let b=r;const g=new Headers;if(o)switch(n){case Ot.HEADER:{g.append("Range",`bytes=${o.from}-${o.to}`);break}case Ot.PARAM:{const C=new URL(b,location.href);C.searchParams.append("bytes",`${o.from}-${o.to}`),b=C.toString();break}default:a.assertNever(n)}this.requestQuic&&(b=Ft(b));let E=this.abortAllController.signal,y;if(u){const C=new Bt;if(y=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{C.abort()}catch(H){ii(H)}}),this.abortAllController.signal.aborted||u.aborted)try{C.abort()}catch(H){ii(H)}E=C.signal}const v=a.now(),S=yield yield R(ci(b,{priority:d,headers:g,signal:E}).catch(ii)),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-v),!S)return y==null||y.unsubscribe(),yield R(null);if(!S.ok||!S.body)return y==null||y.unsubscribe(),yield R(Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`)));this.onHeadersReceived(S.headers);const k=parseInt((f=S.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!k){const C=yield yield R(S.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(C.byteLength,a.now()-T),l==null||l(new DataView(C),C.byteLength),y==null||y.unsubscribe(),yield R(C)}if(!l&&!c)return y==null||y.unsubscribe(),yield R(S.arrayBuffer());const[L,j]=S.body.tee(),D=L.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(j));let x=0;const F=new ArrayBuffer(k),w=new Uint8Array(F),N=new DataView(F);let z=!1;const I=C=>{y==null||y.unsubscribe(),z=!0,ii(C)},A=a.abortable(E,function({done:C,value:H}){return be(this,arguments,function*(){if(x===0&&this.lastRequestFirstBytes$.next(a.now()-v),E.aborted)return y==null||y.unsubscribe(),yield R(void 0);!C&&H&&(w.set(H,x),x+=H.byteLength,l==null||l(N,x),yield yield R(D==null?void 0:D.read().then(A,I)))})}.bind(this));return yield yield R(D==null?void 0:D.read().then(A,I)),y==null||y.unsubscribe(),yield R(z?null:F)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return be(this,arguments,function*(){if(r.type!==$e.BYTE_RANGE)return yield R(null);const{from:d,to:u}=r.initRange;let c=d,h=u,f=!1,p,m;r.indexRange&&(p=r.indexRange.from,m=r.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(m,u))),c=Math.min(c,0);const b=yield yield R(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!b)return yield R(null);const g=new DataView(b,d-c,u-c+1);if(!n.validateData(g))throw new Error("Invalid media file");const E=n.parseInit(g),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(E);if(!y)throw new ReferenceError("No way to load representation index");let v;if(f)v=new DataView(b,y.from-c,y.to-y.from+1);else{const T=yield yield R(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!T)return yield R(null);v=new DataView(T)}const S=n.parseSegments(v,E,y);return yield R({init:E,dataView:new DataView(b),segments:S})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return be(this,arguments,function*(){if(r.type!==$e.TEMPLATE)return yield R(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:Y.NONE,size:void 0}));return yield R({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=nu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,n;return K(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case $e.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case $e.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ii=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var Eg=ze,$g=fi,kg=ce,Pg=kg("match"),Ag=function(i){var e;return Eg(i)&&((e=i[Pg])!==void 0?!!e:$g(i)=="RegExp")},_g=Si,wg=String,Rg=function(i){if(_g(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return wg(i)},Cg=We,Dg=function(){var i=Cg(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},Ig=ge,Ng=Ve,xg=fs,Lg=Dg,yo=RegExp.prototype,Og=function(i){var e=i.flags;return e===void 0&&!("flags"in yo)&&!Ng(i,"flags")&&xg(yo,i)?Ig(Lg,i):e},Ia=Pe,Mg=bs,Bg=Math.floor,gr=Ia("".charAt),Vg=Ia("".replace),yr=Ia("".slice),Fg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ug=/\$([$&'`]|\d{1,2})/g,jg=function(i,e,t,s,r,n){var o=t+i.length,l=s.length,d=Ug;return r!==void 0&&(r=Mg(r),d=Fg),Vg(n,d,function(u,c){var h;switch(gr(c,0)){case"$":return"$";case"&":return i;case"`":return yr(e,0,t);case"'":return yr(e,o);case"<":h=r[yr(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Bg(f/10);return p===0?u:p<=l?s[p-1]===void 0?gr(c,1):s[p-1]+gr(c,1):u}h=s[f-1]}return h===void 0?"":h})},Hg=De,Gg=ge,Na=Pe,To=na,Yg=ne,qg=pi,zg=Ag,Dt=Rg,Wg=vs,Qg=Og,Kg=jg,Jg=ce,Xg=Jg("replace"),Zg=TypeError,bu=Na("".indexOf),ey=Na("".replace),Eo=Na("".slice),ty=Math.max,$o=function(i,e,t){return t>i.length?-1:e===""?t:bu(i,e,t)};Hg({target:"String",proto:!0},{replaceAll:function(e,t){var s=To(this),r,n,o,l,d,u,c,h,f,p=0,m=0,b="";if(!qg(e)){if(r=zg(e),r&&(n=Dt(To(Qg(e))),!~bu(n,"g")))throw Zg("`.replaceAll` does not allow non-global regexes");if(o=Wg(e,Xg),o)return Gg(o,e,s,t);if(r)return ey(Dt(s),e,t)}for(l=Dt(s),d=Dt(e),u=Yg(t),u||(t=Dt(t)),c=d.length,h=ty(1,c),p=$o(l,d,0);p!==-1;)f=u?Dt(t(d,p,l)):Kg(d,l,p,[],void 0,t),b+=Eo(l,m,p)+f,m=p+c,p=$o(l,d,p+h);return m<l.length&&(b+=Eo(l,m)),b}});var iy=wa,sy=iy("String","replaceAll"),ry=sy,ay=ry,ny=ay,oy=ny,ko=cs(oy);const Po=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Tr=(i,e)=>{let t=i;t=ko(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(s)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=ko(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},ly=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,p,m,b,g,E,y,v,S,T,k,L,j,D,x,F,w,N,z,I,A,C,H,te,ie,pe,Ie,Ze,G;const ye=new DOMParser().parseFromString(i,"application/xml"),me={video:[],audio:[],text:[]},Te=ye.children[0],Et=Te.getElementsByTagName("Period")[0],ut=Et.children,$t=Te.getAttribute("type")==="dynamic",kt=Te.getAttribute("availabilityStartTime"),$i=kt?new Date(kt).getTime():void 0;let dt;const xa=Te.getAttribute("mediaPresentationDuration"),La=Et.getAttribute("duration"),_s=Te.getElementsByTagName("vk:Attrs")[0],Oa=_s==null?void 0:_s.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(xa)dt=Po(xa);else if(La){const Ae=Po(La);a.isNonNullable(Ae)&&(dt=Ae)}else Oa&&(dt=parseInt(Oa,10));let Pu=0;const ws=(s=(t=Te.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Au=ws.includes(ls.WEBM_AS_IN_FFMPEG)||ws.includes(ls.WEBM_AS_IN_SPEC)?Ut.WEBM:Ut.MP4;for(const Ae of ut){const ki=Ae.getAttribute("mimeType"),_u=Ae.getAttribute("codecs"),Ma=(r=Ae.getAttribute("contentType"))!==null&&r!==void 0?r:ki==null?void 0:ki.split("/")[0],wu=(o=(n=Ae.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Ba=Ae.querySelectorAll("Representation"),Ru=Ae.querySelector("SegmentTemplate");if(Ma===oe.TEXT){for(const se of Ba){const et=se.getAttribute("id")||"",Pi=Ae.getAttribute("lang"),Pt=(u=(d=(l=se.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Rs=new URL(Pt,e).toString(),Cs=et.includes("_auto");me[oe.TEXT].push({id:et,lang:Pi,isAuto:Cs,kind:oe.TEXT,url:Rs})}continue}for(const se of Ba){const et=(c=se.getAttribute("mimeType"))!==null&&c!==void 0?c:ki,Pi=(f=(h=se.getAttribute("codecs"))!==null&&h!==void 0?h:_u)!==null&&f!==void 0?f:"",Pt=(m=(p=se.getAttribute("contentType"))!==null&&p!==void 0?p:et==null?void 0:et.split("/")[0])!==null&&m!==void 0?m:Ma,Rs=(g=(b=Ae.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&g!==void 0?g:[],Cs=parseInt((E=se.getAttribute("width"))!==null&&E!==void 0?E:"",10),Va=parseInt((y=se.getAttribute("height"))!==null&&y!==void 0?y:"",10),Fa=parseInt((v=se.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,Ua=(S=se.getAttribute("frameRate"))!==null&&S!==void 0?S:"",Cu=(T=se.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Du=Ua?Ca(Ua):void 0,Iu=(k=se.getAttribute("id"))!==null&&k!==void 0?k:(Pu++).toString(10),Nu=Pt==="video"?`${Va}p`:Pt==="audio"?`${Fa}Kbps`:Pi,xu=`${Iu}@${Nu}`,Lu=(D=(j=(L=se.querySelector("BaseURL"))===null||L===void 0?void 0:L.textContent)===null||j===void 0?void 0:j.trim())!==null&&D!==void 0?D:"",ja=new URL(Lu,e).toString(),Ou=[...ws,...wu,...Rs];let Ds;const Mu=se.querySelector("SegmentBase"),ct=(x=se.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:Ru;if(Mu){const Wt=(w=(F=se.querySelector("SegmentBase Initialization"))===null||F===void 0?void 0:F.getAttribute("range"))!==null&&w!==void 0?w:"",[Qt,Ns]=Wt.split("-").map(At=>parseInt(At,10)),Kt={from:Qt,to:Ns},Jt=(N=se.querySelector("SegmentBase"))===null||N===void 0?void 0:N.getAttribute("indexRange"),[xs,Ai]=Jt?Jt.split("-").map(At=>parseInt(At,10)):[],Xt=Jt?{from:xs,to:Ai}:void 0;Ds={type:$e.BYTE_RANGE,url:ja,initRange:Kt,indexRange:Xt}}else if(ct){const Wt={representationId:(z=se.getAttribute("id"))!==null&&z!==void 0?z:void 0,bandwidth:(I=se.getAttribute("bandwidth"))!==null&&I!==void 0?I:void 0},Qt=parseInt((A=ct.getAttribute("timescale"))!==null&&A!==void 0?A:"",10),Ns=(C=ct.getAttribute("initialization"))!==null&&C!==void 0?C:"",Kt=ct.getAttribute("media"),Jt=(te=parseInt((H=ct.getAttribute("startNumber"))!==null&&H!==void 0?H:"",10))!==null&&te!==void 0?te:1,xs=Tr(Ns,Wt);if(!Kt)throw new ReferenceError("No media attribute in SegmentTemplate");const Ai=(ie=ct.querySelectorAll("SegmentTimeline S"))!==null&&ie!==void 0?ie:[],Xt=[];let At=0;if(Ai.length){let Ls=Jt,je=0;for(const Zt of Ai){const tt=parseInt((pe=Zt.getAttribute("d"))!==null&&pe!==void 0?pe:"",10),ht=parseInt((Ie=Zt.getAttribute("r"))!==null&&Ie!==void 0?Ie:"",10)||0,_i=parseInt((Ze=Zt.getAttribute("t"))!==null&&Ze!==void 0?Ze:"",10);je=Number.isFinite(_i)?_i:je;const Os=tt/Qt*1e3,Ha=je/Qt*1e3;for(let wi=0;wi<ht+1;wi++){const Bu=Tr(Kt,Object.assign(Object.assign({},Wt),{segmentNumber:Ls.toString(10),segmentTime:(je+wi*tt).toString(10)})),Ga=(Ha||0)+wi*Os,Vu=Ga+Os;Ls++,Xt.push({time:{from:Ga,to:Vu},url:Bu})}je+=(ht+1)*tt,At+=(ht+1)*Os}}else if(a.isNonNullable(dt)){const je=parseInt((G=ct.getAttribute("duration"))!==null&&G!==void 0?G:"",10)/Qt*1e3,Zt=Math.ceil(dt/je);let tt=0;for(let ht=1;ht<Zt;ht++){const _i=Tr(Kt,Object.assign(Object.assign({},Wt),{segmentNumber:ht.toString(10),segmentTime:tt.toString(10)}));Xt.push({time:{from:tt,to:tt+je},url:_i}),tt+=je}}Ds={type:$e.TEMPLATE,baseUrl:ja,initUrl:xs,totalSegmentsDurationMs:At,segments:Xt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!et)continue;const Is={video:oe.VIDEO,audio:oe.AUDIO,text:oe.TEXT}[Pt];Is&&me[Is].push({id:xu,kind:Is,segmentReference:Ds,profiles:Ou,duration:dt,bitrate:Fa,mime:et,codecs:Pi,width:Cs,height:Va,fps:Du,quality:Cu})}}return{dynamic:$t,liveAvailabilityStartTime:$i,duration:dt,container:Au,representations:me}},ra=1e3,Ao=["timeupdate","progress","play","seeked","stalled","waiting"];var Ee;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Ee||(Ee={}));let uy=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(Ee.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.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Bt,this.initManifest=a.abortable(this.destroyController.signal,function(t,s,r){var n;return be(this,arguments,function*(){this.element=t,this.manifestUrlString=Re(s,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ee.MANIFEST_READY),this.manifest=yield yield R(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Ee.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 be(this,arguments,function*(){const s=yield yield R(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(!s)return yield R(this.manifest);let r;try{r=ly(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return yield R(null);const n=({kind:o,mime:l,codecs:d})=>{var u,c,h,f;return!!(!((c=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||c===void 0)&&c.call(u,l)&&(!((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${d}"`))||o===oe.TEXT)};return this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield R(Object.assign(Object.assign({},r),{representations:Vt(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,s){return be(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ee.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new go(oe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new go(oe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),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(ra).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=lo(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P);this.manifestUrlString=Re(this.manifestUrlString,u+1e3,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Ao.map(l=>a.fromEvent(this.element,l))).pipe(a.throttle(ra),a.map(l=>this.element?st(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(d=>{var u,c;let h=0;if(d){const f=((c=(u=this.element)===null||u===void 0?void 0:u.currentTime)!==null&&c!==void 0?c:0)*1e3;h=Math.min(...this.bufferManagers.map(m=>{var b,g;return(g=(b=m.getLiveSegmentsToLoadState(this.manifest))===null||b===void 0?void 0:b.to)!==null&&g!==void 0?g:0}))-f}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(d=>K(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const u=this.element.playbackRate,c=lo(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P),h=pg*u,f=vg*u,p=mg*u;l=d>l?d:l;const m=c===0&&d<p,b=c!==0&&d<h+p&&d>=h,g=c!==0&&d<h;if(g||b){const E=l-(h+f),y=Math.trunc(c+E/u);let v;d?y>0?v=y:v=0:v=c,this.manifestUrlString=Re(this.manifestUrlString,v,ae.DASH_CMAF_OFFSET_P)}(m||g||b)&&(yield this.updateLive(),l=0)})))}const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(a.merge(...this.bufferManagers.map(l=>l.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 R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(Ee.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=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 Tg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,s,r,n;return K(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.manifestUrlString=Re(this.manifestUrlString,e,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Ee.RUNNING),this.subscription.add(a.merge(...Ao.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&&sa(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return K(this,void 0,void 0,function*(){const s={[oe.VIDEO]:this.videoBufferManager,[oe.AUDIO]:this.audioBufferManager,[oe.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),sa(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ee.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(),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}updateLive(){var e;return K(this,void 0,void 0,function*(){this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class dy{constructor(e,t){this.fov=e,this.orientation=t}}class cy{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,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=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,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var hy=`#define GLSLIFY 1
|
|
29
|
+
`}),I}return u==null||u.recordSwitch(N),N};var fe=i=>new URL(i).hostname;const fS=300,ns=(i,e=fS)=>new a.Observable(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(qu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()});class ks{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:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(r-n)/r;!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,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),s=a.merge(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(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||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const ti={};var V;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const re=(i,e)=>new a.Observable(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class ho{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(V.DOWNLOADING_LIB),this.textTracksManager=new Fe,this.droppedFramesManager=new ks,this.videoTracks$=new a.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new $s,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===V.DOWNLOADING_LIB||t===V.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&t!==V.STOPPED&&s!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),s){case exports.PlaybackState.STOPPED:{switch(t){case V.STOPPED:break;case V.PLAYING:case V.PAUSED:case V.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case V.STOPPED:this.prepare();break;case V.PLAYING:case V.PAUSED:case V.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case V.PLAYING:break;case V.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case V.READY:this.play();break;case V.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case V.PLAYING:this.pause(),this.liveOffset.pause();break;case V.PAUSED:break;case V.READY:this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(s)}},this.video=Ke(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Es(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ti.MediaPlayer=r.MediaPlayer,ti.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(ti.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(ti.Debug,"dashjs not loaded"),this.player=ti.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?Ca(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Gb(this.player),Ub(this.player),this.params.tuning.requestQuick&&Hb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,S)=>this.subscription.add(v.subscribe(S,s));r(ns(this.video),this.elementSize$),r(re(this.player,"error").pipe(a.map(v=>{const S=typeof v.error=="object"?v.error.code:v.error,T=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${S}`,message:T}})),e.error$),r(re(this.player,"playbackError").pipe(a.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({newQuality:v})=>{var S;return(S=this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===v))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:v})=>v===V.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ce(t.videoTrack,()=>{var v,S;const T=this.player.getQualityFor("video");return(S=(v=this.videoTracks$.getValue().find(({bitrateInfo:k})=>k.qualityIndex===T))===null||v===void 0?void 0:v.track)===null||S===void 0?void 0:S.id},v=>{var S;if(a.isNullable(v))return;const T=(S=this.videoTracks$.getValue().find(({track:k})=>k.id===v))===null||S===void 0?void 0:S.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:s}))},s)),this.subscription.add(Ce(t.autoVideoTrackSwitching,()=>{var v,S,T;return(T=(S=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||T===void 0?void 0:T.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:s})),r(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(re(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:S}})=>{var T,k;const L=this.player.getDashMetrics(),j=L.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),D=(T=L.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&T!==void 0?T:exports.HttpConnectionType.HTTP1,x=(k={1:!0,0:!1}[j])!==null&&k!==void 0?k:void 0;this.params.output.httpConnectionType$.next(D),this.params.output.httpConnectionReused$.next(x),e.hostname$.next(fe(S))}),r(re(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:S,availableFrom:T}}})=>{this.isLive$.next(S),this.availableFrom$.next(T.getTime()),S||e.duration$.next(v);const k=[],L=this.player.getQualityFor("video");let j;for(const D of this.player.getBitrateInfoListFor("video")){const x=D.qualityIndex.toString(10),F=a.videoSizeToQuality(D),w=D.bitrate/1e3,N={width:D.width,height:D.height},z=this.frameRatesByFrameHeight[D.height];if(F){const I={id:x,quality:F,bitrate:w,size:N,fps:z};k.push({track:I,bitrateInfo:D}),D.qualityIndex===L&&(j=I)}}this.videoTracks$.next(k),e.availableVideoTracks$.next(k.map(({track:D})=>D)),j&&e.currentVideoTrack$.next(j),this.videoState.setState(V.STREAM_INITIALIZED),this.videoState.startTransitionTo(V.READY)}),r(re(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const S=v.requestEndDate.getTime()-v.firstByteDate.getTime(),T=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(T,S)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=qt(this.videoTracks$.getValue().map(({track:L})=>L),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to);const k=this.videoTracks$.getValue().find(({track:L})=>L===S);k!=null&&k.bitrateInfo&&this.player.setQualityFor("video",k==null?void 0:k.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:v})=>v),a.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:v})=>v!=null?v:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:S})=>this.params.output.liveTime$.next(v+S*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(re(this.player,"playbackEnded"),e.endedEvent$),r(re(this.player,"playbackProgress").pipe(a.map(()=>ru(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(V.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),r(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(re(this.player,"playbackPaused"),()=>{this.videoState.setState(V.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),r(re(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===V.READY&&this.videoState.setState(V.READY)}),r(this.isLive$,e.isLive$),r(ns(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=jb(this.player);r(c,this.params.output.httpConnectionType$),r(h,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(a.once()),e.firstBytesEvent$),r(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(v=>v<60))}),({isLive:v,isShort:S})=>{const T=!v&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:T}}})}),r(o.pipe(a.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),r(re(this.player,"manifestLoaded"),v=>{var S,T,k,L,j,D,x;if(!((T=(S=v.data)===null||S===void 0?void 0:S.Period)===null||T===void 0)&&T.AdaptationSet){const F=[];for(const w of(L=(k=v.data)===null||k===void 0?void 0:k.Period)===null||L===void 0?void 0:L.AdaptationSet)if(w.contentType==="text"){const N=(j=w.Representation)===null||j===void 0?void 0:j.id,z=new URL((D=w.Representation)===null||D===void 0?void 0:D.BaseURL,(x=v.data)===null||x===void 0?void 0:x.baseUri).toString(),I="internal",A=w.lang;F.push({id:N,url:z,type:I,language:A})}t.internalTextTracks.startTransitionTo(F)}}),this.subscription.add(Tt(this.video,t.isLooped,s));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:b,inFullscreen$:g,pause$:E,playing$:y}=Xe(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:y,pause$:E,tracks$:this.videoTracks$.pipe(a.map(v=>v.map(({track:S})=>S)))}),this.subscription.add(Qe(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(ot(this.video,t.playbackRate,m,s)),this.subscription.add(b.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(V.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(V.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Re(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ae.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(V.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(V.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}Je(this.video),this.params.output.element$.next(void 0)}}var Ti=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}};const fo=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 lt=i=>K(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!fo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return fo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function de(){return a.now()}function au(i){return de()-i}function po(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=o=>s.test(o);return{resolve:(o,l,d=!1)=>{r(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function pS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function ts(i,e,t,s){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(d)return;a.assertNonNullable(c);const w=au(c);let N;if(w<b){N=b-w,setTimeout(g,N);return}b*=2,b>m&&(b=m),o&&o.abort(),o=new r,k()};const E=w=>(n=w,F),y=w=>(h=w,F),v=()=>(p="json",F),S=()=>{if(!d){if(--u>=0){g(),s&&s();return}d=!0,h&&h(),t&&t()}},T=w=>(f=w,F),k=()=>{c=de(),o=new r,o.open("get",i);let w=0,N,z=0;const I=()=>(a.assertNonNullable(c),Math.max(c,Math.max(N||0,z||0)));if(n&&o.addEventListener("progress",A=>{const C=de();n.updateChunk&&A.loaded>w&&(n.updateChunk(I(),A.loaded-w),w=A.loaded,N=C)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>S())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const A=o.status;if(A>=200&&A<300){if(o.response.byteLength&&n){const C=o.response.byteLength-w;C&&n.updateChunk&&n.updateChunk(I(),C)}h&&h(),o&&e(o.response)}else S()}),o.addEventListener("error",()=>{S()}),f){const A=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(z=de(),o.removeEventListener("readystatechange",A))};o.addEventListener("readystatechange",A)}return o.responseType=p,o.send(),F},F={withBitrateReporting:E,withParallel:T,withJSONResponse:v,withRetryCount:w=>(u=w,F),withRetryInterval:(w,N)=>(a.isNonNullable(w)&&(b=w),a.isNonNullable(N)&&(m=N),F),withTimeout:w=>(l=w,F),withFinally:y,send:k,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return F}const mS=100,vS=2e3,bS=500;let SS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-bS;if(t-e>vS){let s=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&s>0){const n=r*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>mS&&(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 gS{constructor(e,t,s,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=de(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=de()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ts(t,n,()=>r("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=de()}_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=de();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=r,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 Hi=1e4,Gi=3,yS=300,TS=2e3,ES=6e4,$S=10,kS=1,PS=500;class AS{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 SS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=po(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=po(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,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)?(!r||n.bitrate>r.bitrate)&&(r=n):(!s||s.bitrate>n.bitrate)&&(s=n));return r||s}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:s,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{pS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.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 gS(Gi,Hi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const S=n&&(!c||c===this.rep);return S||t("Not running!"),S},f=(S,T,k)=>{d&&d.abort(),d=ts(this.urlResolver.resolve(S,!1),T,k,()=>this._retryCallback()).withTimeout(Hi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Gi).withFinally(()=>{d=null}).send()},p=(S,T,k)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),T,k,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=S=>{const T=s.playbackRate;s.playbackRate!==S&&(t(`Playback rate switch: ${T}=>${S}`),s.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const k=de()-1e4;let L=0;for(let D=0;D<this.bufferStates.length;D++){const x=this.bufferStates[D];S=Math.min(S,x.buf),x.ts<k&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${S} drop=${L} jitter=${this.sourceJitter}`);let j=S-kS;this.sourceJitter>=0?j-=this.sourceJitter/2:this.sourceJitter-=1,j>3?m(1.15):j>1?m(1.1):j>.3?m(1.05):m(1)}},E=S=>{let T;const k=()=>T&&T.start?T.start.length:0,L=A=>T.start[A]/1e3,j=A=>T.dur[A]/1e3,D=A=>T.fragIndex+A,x=(A,C)=>({chunkIdx:D(A),startTS:L(A),dur:j(A),discontinuity:C}),F=()=>{let A=0;if(T&&T.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=C;this.sourceJitter>1&&(te+=this.sourceJitter-1);let ie=T.dur.length-1;for(;ie>=0&&(te-=T.dur[ie],!(te<=0));--ie);A=Math.min(ie,T.dur.length-1-H),A=Math.max(A,0)}return x(A,!0)},w=A=>{const C=k();if(!(C<=0)){if(a.isNonNullable(A)){for(let H=0;H<C;H++)if(L(H)>A)return x(H)}return F()}},N=A=>{const C=k(),H=A?A.chunkIdx+1:0,te=H-T.fragIndex;if(!(C<=0)){if(!A||te<0||te-C>$S)return t(`Resync: offset=${te} bChunks=${C} chunk=`+JSON.stringify(A)),F();if(!(te>=C))return x(H-T.fragIndex,!1)}},z=(A,C,H)=>{u&&u.abort(),u=ts(this.urlResolver.resolve(A,!0,this.lowLatency),C,H,()=>this._retryCallback()).withTimeout(Hi).withRetryCount(Gi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,C)=>{z(S,H=>{if(!h())return;T=H;const te=!!T.lowLatency;te!==this.lowLatency&&b(te);let ie=0;for(let pe=0;pe<T.dur.length;++pe)ie+=T.dur[pe];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(w(C))},()=>this._handleNetworkError())},nextChunk:N}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:S=>{const{videoElement:T,logger:k}=this.params;let L=E(e.jidxUrl),j,D,x,F,w=0,N,z,I;const A=()=>{N&&(clearTimeout(N),N=void 0);const G=Math.max(PS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=w+G,ye=de(),me=Math.min(1e4,he-ye);w=ye;const Te=()=>{u||h()&&L.seek(()=>{h()&&(w=de(),C(),A())})};me>0?N=window.setTimeout(()=>{this.paused?A():Te()},me):Te()},C=()=>{let G;for(;G=L.nextChunk(F);)F=G,Ie(G);const he=L.nextChunk(x);if(he){if(x&&he.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?A():(y(),this._initPlayerWith(e));return}pe(he)}else A()},H=(G,he)=>{if(!h()||!this.sourceBuffer)return;let ye,me,Te;const Et=ut=>{window.setTimeout(()=>{h()&&H(G,he)},ut)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),Et(100);else{const ut=de(),$t=T.currentTime;!this.paused&&T.buffered.length>1&&z===$t&&ut-I>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),z!==$t&&(z=$t,I=ut);const kt=this._getBufferSizeSec();if(kt>30)k(`Buffered ${kt} seconds; delaying appendBuffer`),Et(2e3);else try{this.sourceBuffer.appendBuffer(G),this.videoPlayStarted?(this.bufferStates.push({ts:ut,buf:kt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch($i){if($i.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(ye=this.sourceBuffer.buffered.start(0),me=$t,me-ye>4&&this.sourceBuffer.remove(ye,me-3)),Et(1e3);else throw $i}}},te=()=>{D&&j&&(k([`Appending chunk, sz=${D.byteLength}:`,JSON.stringify(x)]),H(D,function(){D=null,C()}))},ie=G=>e.fragUrlTemplate.replace("%%id%%",G.chunkIdx),pe=G=>{h()&&p(ie(G),(he,ye)=>{if(h()){if(ye/=1e3,D=he,x=G,o=G.startTS,ye){const me=Math.min(10,G.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}te()}},()=>this._handleNetworkError())},Ie=G=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(G),!1)))},Ze=G=>{h()&&(e.cachedHeader=G,H(G,()=>{j=!0,te()}))};n=!0,L.seek(G=>{if(h()){if(w=de(),!G){A();return}F=G,!a.isNullable(S)||G.startTS>S?pe(G):(x=G,C())}},S),e.cachedHeader?Ze(e.cachedHeader):f(e.headerUrl,Ze,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.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 m=de();if(this.chunkRateEstimator.addInterval(f,m,p)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:g}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&au(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=de();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=ts(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Hi).withRetryCount(Gi).withRetryInterval(yS,TS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;lt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},ES))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var M;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const _S=[M.PAUSED,M.PLAYING,M.READY],wS=[M.PAUSED,M.PLAYING,M.READY];class RS{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(M.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Fe,this.droppedFramesManager=new ks,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new $s,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Ti(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,b=Object.assign({},h.video);if(!p)continue;const g={id:f,quality:p,bitrate:m,size:b};c.push({track:g,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.MANIFEST_READY&&this.videoState.setState(M.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){r!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(M.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(wS.includes(r)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===B.Requested&&_S.includes(r)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(r){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_READY),this.dash.attachSource(Re(this.params.source.url));return;case M.MANIFEST_READY:this.videoState.startTransitionTo(M.READY),this.prepare();break;case M.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(M.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(M.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(M.PAUSED)})}return;case M.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(M.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case M.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(M.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(M.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(Re(this.params.source.url,h))}return;default:return a.assertNever(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=Ke(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(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=Xe(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(a.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===M.READY&&this.videoState.setState(M.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(M.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(Tt(this.video,this.params.desiredState.isLooped,t)).add(Qe(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(ot(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const n=r&&a.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var n;switch(r.to){case M.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case M.MANIFEST_READY:case M.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 M.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case M.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.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),Je(this.video)}createLiveDashPlayer(){const e=new AS({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=qt(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}))===null||n===void 0?void 0:n.id,h=this.params.desiredState.videoTrack.getTransition(),f=this.params.desiredState.videoTrack.getState(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((h&&c||c!==f)&&this.setVideoTrack(c),p&&this.setAutoQuality(u),h||p||c!==f){const m=(o=l.find(({track:b})=>b.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===M.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Re(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}}var nu=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},st=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,n=i.end(s)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const CS=i=>{const e=document.createElement("a");return e.href=i,e.origin},DS=i=>{const e=document.createElement("a");return e.href=i,e.host};class ou{constructor(e,t=[],s,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,n,o,l,d,u;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=Vt(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(DS(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class os{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=b=>{r(os._str2ua(b.substr(d))),d=b.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=Ft(m)),this._lastXhr=new ou(m,e.failoverHosts,b=>{this._lastXhr=void 0,p(b);const g=Date.now()-u;this._params.onBandwidthChange({size:b.length,duration:g,speed:8*b.length/(g/1e3)}),this._onDashCallback("loading",{size:b.length,done:!0}),n==null||n()},b=>{if(b.length-d>l&&p(b),h===0){h=Date.now();return}f=b.length-c;const g=Date.now()-h;f>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:f,duration:g,speed:8*f/(g/1e3)}),f=0,c=b.length,h=Date.now()),this._onDashCallback("loading",{size:b.length,done:!1})},o,(b,g,E)=>this._params.onError(b,g,E))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=os._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class IS{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},r=t.exec(e),n=(r==null?void 0:r[1])==="-"?-1:1,o={years:s(r==null?void 0:r[2],n),months:s(r==null?void 0:r[3],n),weeks:s(r==null?void 0:r[4],n),days:s(r==null?void 0:r[5],n),hours:s(r==null?void 0:r[6],n),minutes:s(r==null?void 0:r[7],n),seconds:s(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Ft(s)),new ou(s,t,r=>{this.attachManifest(r,t,CS(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,m,b,g,E,y,v,S,T,k,L,j,D,x,F,w;const N=u.getElementsByTagName("SegmentBase")[0],z=N&&o(N,"indexRange").split("-"),I=N&&N.getElementsByTagName("Initialization")[0],A=I&&o(I,"range").split("-");if(!A||!z){const Ie=u.parentElement;if((Ie==null?void 0:Ie.getAttribute("contentType"))==="text"){const Ze=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,G=(s?s+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),he=(b=Ie.getAttribute("lang"))!==null&&b!==void 0?b:void 0;G&&d.push({id:Ze,url:G,language:he})}return}const C=.1,H=Number((g=u.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),te=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const pe=(y=(E=u.attributes.getNamedItem("frameRate"))===null||E===void 0?void 0:E.value)!==null&&y!==void 0?y:void 0;ie=pe?Ca(pe):void 0,l.push({width:Number((v=u.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((S=u.attributes.getNamedItem("height"))===null||S===void 0?void 0:S.value),bandwidth:H,baseURL:te,failoverHosts:t,indexFrom:Number(z[0]),indexTo:Number(z[1]),initFrom:Number(A[0]),initTo:Number(A[1]),codecs:(k=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&k!==void 0?k:void 0,mimeType:(j=(L=u.attributes.getNamedItem("mimeType"))===null||L===void 0?void 0:L.value)!==null&&j!==void 0?j:void 0,fps:ie,bufferSize:C*H/8,bufferLength:C,name:(x=(D=u.attributes.getNamedItem("okQuality"))===null||D===void 0?void 0:D.value)!==null&&x!==void 0?x:void 0,id:(w=(F=u.attributes.getNamedItem("id"))===null||F===void 0?void 0:F.value)!==null&&w!==void 0?w:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),m=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,d=m}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new os({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||l(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<s.to+n){const o=this._findRef(r.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<s.length;n++){const o=s[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=s[s.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var U;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(U||(U={}));const NS=[U.PAUSED,U.PLAYING];class xS{constructor(e){this.videoState=new X(U.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Fe,this.droppedFramesManager=new ks,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,n,o;const l=[];for(const d of t){const u=(n=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Ti(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(s==null?void 0:s.length)>0){const d=[];for(const u of s){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(U.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:n})=>n===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.dash.destroy(),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(U.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!s)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===B.Requested&&NS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case U.STOPPED:this.videoState.startTransitionTo(U.MANIFEST_LOADED),this.prepare();return;case U.MANIFEST_LOADED:this.videoState.startTransitionTo(U.INITIAL_REPRESENTATION_SELECTED);return;case U.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(U.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case U.METADATA_LOADED:this.videoState.startTransitionTo(U.READY),this.dash.updateRefsForCurrentTime();return;case U.READY:r===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed());return;case U.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(U.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case U.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(U.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Kb(this.video),this.dash=new IS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Xe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===U.PLAYING||this.videoState.getState()===U.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Tt(this.video,t.isLooped,s)),this.subscription.add(Qe(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ot(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(a.map(l=>l.map(({track:d})=>d)))}),o(ns(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===U.READY&&this.videoState.setState(U.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(U.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(U.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),g=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let E;if(!g&&a.isNonNullable(p))E=p;else{const y=st(this.video.buffered,this.video.currentTime*1e3),v=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,S=Math.min(y/v,1);E=(d=qt(h.map(({track:k})=>k),{container:b,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:S,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:k})=>k===c))===null||l===void 0?void 0:l.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||d===void 0?void 0:d.id;const T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to)}return a.isNonNullable(E)?(u=h.find(({track:y})=>y.id===E))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,s)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===U.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(U.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?l.height<=d.height:l===d)).subscribe(l=>{const d=st(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(fe(l.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=nu(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Je(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){lt(this.video).then(e=>{e||(this.videoState.setState(U.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}var oe;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(oe||(oe={}));var ls;(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"})(ls||(ls={}));var $e;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})($e||($e={}));var Y;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(Y||(Y={}));var Ut;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ut||(Ut={}));var us;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(us||(us={}));var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class mo{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,n=s.length;r<n;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,n=s.length;r<n;r++){const o=s[r];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 lu extends mo{constructor(){super(),this.listeners||mo.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 uu=class{constructor(){Object.defineProperty(this,"signal",{value:new lu,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(uu.prototype[Symbol.toStringTag]="AbortController",lu.prototype[Symbol.toStringTag]="AbortSignal");function du(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 LS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!du({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ps=du({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),cu=Ps?LS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ci=Ps?cu.fetch:window.fetch;Ps?cu.Request:window.Request;const Bt=Ps?uu:window.AbortController;var sa=(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 OS=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},MS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",vo=MS?OS:window.requestIdleCallback;var br,Sr;let hu=!1;try{hu=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Sr=(br=navigator.userAgent.match(/Version\/(\d+)/))===null||br===void 0?void 0:br[1])!==null&&Sr!==void 0?Sr:"",10)<16}catch(i){console.error(i)}class BS{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 s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return K(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return K(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return K(this,void 0,void 0,function*(){return new Promise(t=>{let s;hu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category: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 bo=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ue{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class fu extends Ue{}class VS extends Ue{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class FS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class US extends Ue{constructor(e){super(e),this.data=this.content}}class Ei extends Ue{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class jS extends Ei{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class HS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class GS extends Ue{parseChildrenBoxes(){return zt(this.content)}}var vt;(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"})(vt||(vt={}));class YS extends Ei{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=vt.MONOSCOPIC;break;case 1:this.stereoMode=vt.TOP_BOTTOM;break;case 2:this.stereoMode=vt.LEFT_RIGHT;break;case 3:this.stereoMode=vt.STEREO_CUSTOM;break;case 4:this.stereoMode=vt.RIGHT_LEFT;break}this.cursor+=1}}class qS extends Ei{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class zS extends Ei{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class WS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class QS extends Ei{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 KS extends Ue{parseChildrenBoxes(){return zt(this.content)}}class JS extends Ue{parseChildrenBoxes(){return zt(this.content)}}const XS={ftyp:VS,moov:FS,mdat:US,sidx:jS,trak:HS,mdia:WS,tkhd:QS,minf:KS,sv3d:GS,st3d:YS,prhd:qS,proj:JS,equi:zS,unknown:fu};class ZS{createBox(e,t){const s=XS[e];return s?new s(t):new fu(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return As.createBox(s,new DataView(e.buffer,e.byteOffset))}}const As=new ZS;function ai(i,e){const t=new TextDecoder("ascii");let s=i.byteOffset,r=[];for(;s<i.byteLength;){const n=t.decode(new DataView(i.buffer,s,1));if(n===e[r.length]?r.push(n):r=[],r.length===4&&r.join("")===e){const l=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+l>i.byteLength?null:As.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function eg(i,e){const t=[];let s=0;for(;s<i.byteLength;){const r=ai(new DataView(i.buffer,i.byteOffset+s,i.byteLength-s),e);if(r)t.push(r),s+=r.size+r.source.byteOffset;else break}return t}function zt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=As.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const tg=new TextDecoder("ascii"),ig=i=>tg.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",sg=i=>{const e=As.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:Y.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},rg=i=>{const e=eg(i,"mdat");if(e.length){const t=e.reduce((s,r)=>s+r.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},ag=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ai(i,"sv3d")){e.is3dVideo=!0;const s=ai(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=ai(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=ai(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},ng={validateData:ig,parseInit:ag,getIndexRange:()=>{},parseSegments:sg,parseFeedableSegmentChunk:rg};var $;(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"})($||($={}));var _;(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"})(_||(_={}));const So={[$.EBML]:{type:_.Master},[$.EBMLVersion]:{type:_.UnsignedInteger},[$.EBMLReadVersion]:{type:_.UnsignedInteger},[$.EBMLMaxIDLength]:{type:_.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:_.UnsignedInteger},[$.DocType]:{type:_.String},[$.DocTypeVersion]:{type:_.UnsignedInteger},[$.DocTypeReadVersion]:{type:_.UnsignedInteger},[$.Void]:{type:_.Binary},[$.Segment]:{type:_.Master},[$.SeekHead]:{type:_.Master},[$.Seek]:{type:_.Master},[$.SeekID]:{type:_.Binary},[$.SeekPosition]:{type:_.UnsignedInteger},[$.Info]:{type:_.Master},[$.TimestampScale]:{type:_.UnsignedInteger},[$.Duration]:{type:_.Float},[$.Tracks]:{type:_.Master},[$.TrackEntry]:{type:_.Master},[$.Video]:{type:_.Master},[$.Projection]:{type:_.Master},[$.ProjectionType]:{type:_.UnsignedInteger},[$.ProjectionPrivate]:{type:_.Master},[$.Chapters]:{type:_.Master},[$.Cluster]:{type:_.Master},[$.Timestamp]:{type:_.UnsignedInteger},[$.SilentTracks]:{type:_.Master},[$.SilentTrackNumber]:{type:_.UnsignedInteger},[$.Position]:{type:_.UnsignedInteger},[$.PrevSize]:{type:_.UnsignedInteger},[$.SimpleBlock]:{type:_.Binary},[$.BlockGroup]:{type:_.Master},[$.EncryptedBlock]:{type:_.Binary},[$.Attachments]:{type:_.Master},[$.Tags]:{type:_.Master},[$.Cues]:{type:_.Master},[$.CuePoint]:{type:_.Master},[$.CueTime]:{type:_.UnsignedInteger},[$.CueTrackPositions]:{type:_.Master},[$.CueTrack]:{type:_.UnsignedInteger},[$.CueClusterPosition]:{type:_.UnsignedInteger},[$.CueRelativePosition]:{type:_.UnsignedInteger},[$.CueDuration]:{type:_.UnsignedInteger},[$.CueBlockNumber]:{type:_.UnsignedInteger},[$.CueCodecState]:{type:_.UnsignedInteger},[$.CueReference]:{type:_.Master},[$.CueRefTime]:{type:_.UnsignedInteger}},pu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=ds(i,t),r=s in So,n=r?So[s].type:_.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=ds(d),h=u*Math.pow(2,(l-1)*8)+c,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:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},ds=(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},Me=(i,e)=>{switch(e){case _.SignedInteger:return i.getInt8(0);case _.UnsignedInteger:return ds(i);case _.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case _.String:return new TextDecoder("ascii").decode(i);case _.UTF8:return new TextDecoder("utf-8").decode(i);case _.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case _.Master:return i;case _.Binary:return i;default:a.assertNever(e)}},jt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=pu(s);if(!e(r))return;r.type===_.Master&&jt(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},og=i=>{if(i.getUint32(0)!==$.EBML)return!1;let e,t,s;const r=pu(i);return jt(r.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=Me(l,o):n===$.DocType?t=Me(l,o):n===$.DocTypeReadVersion&&(s=Me(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},mu=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],lg=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],ug=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return jt(i,({tag:f,type:p,value:m,valueSize:b})=>{if(f===$.SeekID){const g=Me(m,p);u=ds(g)}else f!==$.SeekPosition&&(u=void 0);return f===$.Segment?(e=m.byteOffset,t=m.byteOffset+b):f===$.Info?n=!0:f===$.SeekHead?o=!0:f===$.TimestampScale?s=Me(m,p):f===$.Duration?r=Me(m,p):f===$.SeekPosition&&u===$.Cues?d=Me(m,p):f===$.Tracks?jt(m,({tag:g,type:E,value:y})=>g===$.ProjectionType?(c=Me(y,E)===1,!1):!0):n&&o&&mu.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(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},dg=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},cg=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return jt(i,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&r(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=Me(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=Me(u,d));break;default:t&&mu.includes(l)&&(s=!0)}return!(t&&s)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:Y.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},hg=i=>{let e=0,t=!1;try{jt(i,s=>s.tag===$.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):lg.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},fg={validateData:og,parseInit:ug,getIndexRange:dg,parseSegments:cg,parseFeedableSegmentChunk:hg},vu=1e4,pg=3e4,mg=5e3,vg=vu,bg=({id:i,width:e,height:t,bitrate:s,fps:r,quality:n})=>{var o;const l=(o=n?Ti(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},Sg=({id:i,bitrate:e})=>({id:i,bitrate:e}),gg=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Le(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Le(i,-1)},yg=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Yi=i=>{const e=[];let t=0,s=i.length-1;for(;t<vu&&s>=0;)e.unshift(i[s]),t+=i[s].time.to-i[s].time.from,s--;return e};class go{constructor(e,t,s,r,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1,manifest:u}){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.isSeekingLive=!1,this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Bt,this.destroyAbortController=new Bt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){const h=this.representations.get(c);a.assertNonNullable(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new BS(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 g=Math.min(this.bufferLimit,bo(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield R(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(a.assertNonNullable(f,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield R(void 0);this.searchGaps(p,h),yield yield R(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);a.assertNonNullable(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(a.isNullable(p)||a.isNullable(f)?yield yield R(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield R(p)),f=this.segments.get(c),a.assertNonNullable(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.searchGaps(f,h),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield R(void 0);for(const g of this.representations.keys()){const E=c.find(S=>S.id===g);E&&this.representations.set(g,E);const y=this.representations.get(g);if(!y)return yield R(void 0);const v=Yi(y.segmentReference.segments);this.segments.set(y.id,v)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,f=this.representations.get(h);a.assertNonNullable(f);const p=Yi(f.segmentReference.segments),m=this.initData.get(f.id);if(a.assertNonNullable(m,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(m instanceof ArrayBuffer))return yield R(void 0);const b=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),b&&(yield yield R(this.sourceBufferTaskQueue.remove(b.from*1e3,b.to*1e3,this.destroyAbortController.signal))),this.searchGaps(p,f),yield yield R(this.sourceBufferTaskQueue.append(m,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isLive=!!(u!=null&&u.dynamic),this.container=s,s){case Ut.MP4:this.containerParser=ng;break;case Ut.WEBM:this.containerParser=fg;break;default:a.assertNever(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Bt,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),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=st(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&bo(this.sourceBuffer.buffered)>=this.bufferLimit){const u=st(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=Le(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===Y.FED&&!l.length&&st(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Le(s,-1);d&&d.status===Y.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let s=0;for(const r of e)r.time.from-s>0&&this.gaps.push({representation:t.id,from:s,to:r.time.from}),s=r.time.to;a.isNonNullable(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o)return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:Y.NONE,size:void 0})),d=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(r=Le(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.round(u)>=Math.round(h.time.from)&&Math.round(u)<=Math.round(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=Yi(l);this.segments.set(o.id,[...h])}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const b=f<=s&&p>=s,g=f>s||b||m===0&&s===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+E||p<=s+E;return(h===Y.NONE||h===Y.PARTIALLY_EJECTED&&g&&y&&this.sourceBuffer&&!sa(this.sourceBuffer.buffered,s))&&g&&y});if(r===-1)return[];if(t!==$e.BYTE_RANGE)return e.slice(r,r+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=r;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===Y.NONE||f.status===Y.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,s="auto"){return K(this,void 0,void 0,function*(){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case $e.BYTE_RANGE:{r=t.segmentReference.url,n={from:Le(e,0).byte.from,to:Le(e,-1).byte.to};break}case $e.TEMPLATE:{const u=Le(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=Y.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return be(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,u=>{if(u.name!=="AbortError"){for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)}})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=st((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=Y.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const m of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])m.status===Y.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=Y.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===$e.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const g=p?f.byte.from-s:0,E=p?f.byte.to-s:e.byteLength,y=g<r,v=E<=r;if(f.status===Y.DOWNLOADING&&y&&v){f.status=Y.DOWNLOADED,this.activeSegments.delete(h);const S=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(S,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(m,r-g),h.loadedBytes>h.feedingBytes)){const S=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?S:this.containerParser.parseFeedableSegmentChunk(S);T!=null&&T.byteLength&&(f.status=Y.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(k=>{if(n.aborted)o();else if(k)h.fedBytes+=T.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Y.PARTIALLY_FED||e.status===Y.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Y.NONE),e.status=Y.PARTIALLY_EJECTED):e.status=Y.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=vo(()=>Es(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return K(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return be(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>K(this,void 0,void 0,function*(){if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,this.isLive?Yi(c):c),d&&this.parsedInitData.set(e.id,d)})).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&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,s=!1){return K(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let r=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;r+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===Y.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){r=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status===Y.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===Y.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===Y.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=vo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:n})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:n}=r;if(n!==Y.FED&&n!==Y.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),l=Math.ceil(r.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?r.status=Y.PARTIALLY_EJECTED:r.status=Y.NONE)}}}var Ot;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Ot||(Ot={}));class Tg{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!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 Bt,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(r){return be(this,arguments,function*(){let n=r;this.requestQuic&&(n=Ft(n));const o=yield yield R(ci(n,{signal:this.abortAllController.signal}).catch(ii));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(r,{rangeMethod:n=this.compatibilityMode?Ot.HEADER:Ot.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return be(this,arguments,function*(){let b=r;const g=new Headers;if(o)switch(n){case Ot.HEADER:{g.append("Range",`bytes=${o.from}-${o.to}`);break}case Ot.PARAM:{const C=new URL(b,location.href);C.searchParams.append("bytes",`${o.from}-${o.to}`),b=C.toString();break}default:a.assertNever(n)}this.requestQuic&&(b=Ft(b));let E=this.abortAllController.signal,y;if(u){const C=new Bt;if(y=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{C.abort()}catch(H){ii(H)}}),this.abortAllController.signal.aborted||u.aborted)try{C.abort()}catch(H){ii(H)}E=C.signal}const v=a.now(),S=yield yield R(ci(b,{priority:d,headers:g,signal:E}).catch(ii)),T=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-v),!S)return y==null||y.unsubscribe(),yield R(null);if(!S.ok||!S.body)return y==null||y.unsubscribe(),yield R(Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`)));this.onHeadersReceived(S.headers);const k=parseInt((f=S.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!k){const C=yield yield R(S.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(C.byteLength,a.now()-T),l==null||l(new DataView(C),C.byteLength),y==null||y.unsubscribe(),yield R(C)}if(!l&&!c)return y==null||y.unsubscribe(),yield R(S.arrayBuffer());const[L,j]=S.body.tee(),D=L.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(j));let x=0;const F=new ArrayBuffer(k),w=new Uint8Array(F),N=new DataView(F);let z=!1;const I=C=>{y==null||y.unsubscribe(),z=!0,ii(C)},A=a.abortable(E,function({done:C,value:H}){return be(this,arguments,function*(){if(x===0&&this.lastRequestFirstBytes$.next(a.now()-v),E.aborted)return y==null||y.unsubscribe(),yield R(void 0);!C&&H&&(w.set(H,x),x+=H.byteLength,l==null||l(N,x),yield yield R(D==null?void 0:D.read().then(A,I)))})}.bind(this));return yield yield R(D==null?void 0:D.read().then(A,I)),y==null||y.unsubscribe(),yield R(z?null:F)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return be(this,arguments,function*(){if(r.type!==$e.BYTE_RANGE)return yield R(null);const{from:d,to:u}=r.initRange;let c=d,h=u,f=!1,p,m;r.indexRange&&(p=r.indexRange.from,m=r.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(m,u))),c=Math.min(c,0);const b=yield yield R(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!b)return yield R(null);const g=new DataView(b,d-c,u-c+1);if(!n.validateData(g))throw new Error("Invalid media file");const E=n.parseInit(g),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(E);if(!y)throw new ReferenceError("No way to load representation index");let v;if(f)v=new DataView(b,y.from-c,y.to-y.from+1);else{const T=yield yield R(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!T)return yield R(null);v=new DataView(T)}const S=n.parseSegments(v,E,y);return yield R({init:E,dataView:new DataView(b),segments:S})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return be(this,arguments,function*(){if(r.type!==$e.TEMPLATE)return yield R(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:Y.NONE,size:void 0}));return yield R({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=nu(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,n;return K(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case $e.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case $e.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ii=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var Eg=ze,$g=fi,kg=ce,Pg=kg("match"),Ag=function(i){var e;return Eg(i)&&((e=i[Pg])!==void 0?!!e:$g(i)=="RegExp")},_g=Si,wg=String,Rg=function(i){if(_g(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return wg(i)},Cg=We,Dg=function(){var i=Cg(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},Ig=ge,Ng=Ve,xg=fs,Lg=Dg,yo=RegExp.prototype,Og=function(i){var e=i.flags;return e===void 0&&!("flags"in yo)&&!Ng(i,"flags")&&xg(yo,i)?Ig(Lg,i):e},Ia=Pe,Mg=bs,Bg=Math.floor,gr=Ia("".charAt),Vg=Ia("".replace),yr=Ia("".slice),Fg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ug=/\$([$&'`]|\d{1,2})/g,jg=function(i,e,t,s,r,n){var o=t+i.length,l=s.length,d=Ug;return r!==void 0&&(r=Mg(r),d=Fg),Vg(n,d,function(u,c){var h;switch(gr(c,0)){case"$":return"$";case"&":return i;case"`":return yr(e,0,t);case"'":return yr(e,o);case"<":h=r[yr(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Bg(f/10);return p===0?u:p<=l?s[p-1]===void 0?gr(c,1):s[p-1]+gr(c,1):u}h=s[f-1]}return h===void 0?"":h})},Hg=De,Gg=ge,Na=Pe,To=na,Yg=ne,qg=pi,zg=Ag,Dt=Rg,Wg=vs,Qg=Og,Kg=jg,Jg=ce,Xg=Jg("replace"),Zg=TypeError,bu=Na("".indexOf),ey=Na("".replace),Eo=Na("".slice),ty=Math.max,$o=function(i,e,t){return t>i.length?-1:e===""?t:bu(i,e,t)};Hg({target:"String",proto:!0},{replaceAll:function(e,t){var s=To(this),r,n,o,l,d,u,c,h,f,p=0,m=0,b="";if(!qg(e)){if(r=zg(e),r&&(n=Dt(To(Qg(e))),!~bu(n,"g")))throw Zg("`.replaceAll` does not allow non-global regexes");if(o=Wg(e,Xg),o)return Gg(o,e,s,t);if(r)return ey(Dt(s),e,t)}for(l=Dt(s),d=Dt(e),u=Yg(t),u||(t=Dt(t)),c=d.length,h=ty(1,c),p=$o(l,d,0);p!==-1;)f=u?Dt(t(d,p,l)):Kg(d,l,p,[],void 0,t),b+=Eo(l,m,p)+f,m=p+c,p=$o(l,d,p+h);return m<l.length&&(b+=Eo(l,m)),b}});var iy=wa,sy=iy("String","replaceAll"),ry=sy,ay=ry,ny=ay,oy=ny,ko=cs(oy);const Po=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Tr=(i,e)=>{let t=i;t=ko(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(s)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=ko(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},ly=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,p,m,b,g,E,y,v,S,T,k,L,j,D,x,F,w,N,z,I,A,C,H,te,ie,pe,Ie,Ze,G;const ye=new DOMParser().parseFromString(i,"application/xml"),me={video:[],audio:[],text:[]},Te=ye.children[0],Et=Te.getElementsByTagName("Period")[0],ut=Et.children,$t=Te.getAttribute("type")==="dynamic",kt=Te.getAttribute("availabilityStartTime"),$i=kt?new Date(kt).getTime():void 0;let dt;const xa=Te.getAttribute("mediaPresentationDuration"),La=Et.getAttribute("duration"),_s=Te.getElementsByTagName("vk:Attrs")[0],Oa=_s==null?void 0:_s.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(xa)dt=Po(xa);else if(La){const Ae=Po(La);a.isNonNullable(Ae)&&(dt=Ae)}else Oa&&(dt=parseInt(Oa,10));let Pu=0;const ws=(s=(t=Te.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Au=ws.includes(ls.WEBM_AS_IN_FFMPEG)||ws.includes(ls.WEBM_AS_IN_SPEC)?Ut.WEBM:Ut.MP4;for(const Ae of ut){const ki=Ae.getAttribute("mimeType"),_u=Ae.getAttribute("codecs"),Ma=(r=Ae.getAttribute("contentType"))!==null&&r!==void 0?r:ki==null?void 0:ki.split("/")[0],wu=(o=(n=Ae.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Ba=Ae.querySelectorAll("Representation"),Ru=Ae.querySelector("SegmentTemplate");if(Ma===oe.TEXT){for(const se of Ba){const et=se.getAttribute("id")||"",Pi=Ae.getAttribute("lang"),Pt=(u=(d=(l=se.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Rs=new URL(Pt,e).toString(),Cs=et.includes("_auto");me[oe.TEXT].push({id:et,lang:Pi,isAuto:Cs,kind:oe.TEXT,url:Rs})}continue}for(const se of Ba){const et=(c=se.getAttribute("mimeType"))!==null&&c!==void 0?c:ki,Pi=(f=(h=se.getAttribute("codecs"))!==null&&h!==void 0?h:_u)!==null&&f!==void 0?f:"",Pt=(m=(p=se.getAttribute("contentType"))!==null&&p!==void 0?p:et==null?void 0:et.split("/")[0])!==null&&m!==void 0?m:Ma,Rs=(g=(b=Ae.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&g!==void 0?g:[],Cs=parseInt((E=se.getAttribute("width"))!==null&&E!==void 0?E:"",10),Va=parseInt((y=se.getAttribute("height"))!==null&&y!==void 0?y:"",10),Fa=parseInt((v=se.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,Ua=(S=se.getAttribute("frameRate"))!==null&&S!==void 0?S:"",Cu=(T=se.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Du=Ua?Ca(Ua):void 0,Iu=(k=se.getAttribute("id"))!==null&&k!==void 0?k:(Pu++).toString(10),Nu=Pt==="video"?`${Va}p`:Pt==="audio"?`${Fa}Kbps`:Pi,xu=`${Iu}@${Nu}`,Lu=(D=(j=(L=se.querySelector("BaseURL"))===null||L===void 0?void 0:L.textContent)===null||j===void 0?void 0:j.trim())!==null&&D!==void 0?D:"",ja=new URL(Lu,e).toString(),Ou=[...ws,...wu,...Rs];let Ds;const Mu=se.querySelector("SegmentBase"),ct=(x=se.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:Ru;if(Mu){const Wt=(w=(F=se.querySelector("SegmentBase Initialization"))===null||F===void 0?void 0:F.getAttribute("range"))!==null&&w!==void 0?w:"",[Qt,Ns]=Wt.split("-").map(At=>parseInt(At,10)),Kt={from:Qt,to:Ns},Jt=(N=se.querySelector("SegmentBase"))===null||N===void 0?void 0:N.getAttribute("indexRange"),[xs,Ai]=Jt?Jt.split("-").map(At=>parseInt(At,10)):[],Xt=Jt?{from:xs,to:Ai}:void 0;Ds={type:$e.BYTE_RANGE,url:ja,initRange:Kt,indexRange:Xt}}else if(ct){const Wt={representationId:(z=se.getAttribute("id"))!==null&&z!==void 0?z:void 0,bandwidth:(I=se.getAttribute("bandwidth"))!==null&&I!==void 0?I:void 0},Qt=parseInt((A=ct.getAttribute("timescale"))!==null&&A!==void 0?A:"",10),Ns=(C=ct.getAttribute("initialization"))!==null&&C!==void 0?C:"",Kt=ct.getAttribute("media"),Jt=(te=parseInt((H=ct.getAttribute("startNumber"))!==null&&H!==void 0?H:"",10))!==null&&te!==void 0?te:1,xs=Tr(Ns,Wt);if(!Kt)throw new ReferenceError("No media attribute in SegmentTemplate");const Ai=(ie=ct.querySelectorAll("SegmentTimeline S"))!==null&&ie!==void 0?ie:[],Xt=[];let At=0;if(Ai.length){let Ls=Jt,je=0;for(const Zt of Ai){const tt=parseInt((pe=Zt.getAttribute("d"))!==null&&pe!==void 0?pe:"",10),ht=parseInt((Ie=Zt.getAttribute("r"))!==null&&Ie!==void 0?Ie:"",10)||0,_i=parseInt((Ze=Zt.getAttribute("t"))!==null&&Ze!==void 0?Ze:"",10);je=Number.isFinite(_i)?_i:je;const Os=tt/Qt*1e3,Ha=je/Qt*1e3;for(let wi=0;wi<ht+1;wi++){const Bu=Tr(Kt,Object.assign(Object.assign({},Wt),{segmentNumber:Ls.toString(10),segmentTime:(je+wi*tt).toString(10)})),Ga=(Ha||0)+wi*Os,Vu=Ga+Os;Ls++,Xt.push({time:{from:Ga,to:Vu},url:Bu})}je+=(ht+1)*tt,At+=(ht+1)*Os}}else if(a.isNonNullable(dt)){const je=parseInt((G=ct.getAttribute("duration"))!==null&&G!==void 0?G:"",10)/Qt*1e3,Zt=Math.ceil(dt/je);let tt=0;for(let ht=1;ht<Zt;ht++){const _i=Tr(Kt,Object.assign(Object.assign({},Wt),{segmentNumber:ht.toString(10),segmentTime:tt.toString(10)}));Xt.push({time:{from:tt,to:tt+je},url:_i}),tt+=je}}Ds={type:$e.TEMPLATE,baseUrl:ja,initUrl:xs,totalSegmentsDurationMs:At,segments:Xt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pt||!et)continue;const Is={video:oe.VIDEO,audio:oe.AUDIO,text:oe.TEXT}[Pt];Is&&me[Is].push({id:xu,kind:Is,segmentReference:Ds,profiles:Ou,duration:dt,bitrate:Fa,mime:et,codecs:Pi,width:Cs,height:Va,fps:Du,quality:Cu})}}return{dynamic:$t,liveAvailabilityStartTime:$i,duration:dt,container:Au,representations:me}},ra=1e3,Ao=["timeupdate","progress","play","seeked","stalled","waiting"];var Ee;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Ee||(Ee={}));let uy=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(Ee.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.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Bt,this.initManifest=a.abortable(this.destroyController.signal,function(t,s,r){var n;return be(this,arguments,function*(){this.element=t,this.manifestUrlString=Re(s,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ee.MANIFEST_READY),this.manifest=yield yield R(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Ee.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 be(this,arguments,function*(){const s=yield yield R(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(!s)return yield R(this.manifest);let r;try{r=ly(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return yield R(null);const n=({kind:o,mime:l,codecs:d})=>{var u,c,h,f;return!!(!((c=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||c===void 0)&&c.call(u,l)&&(!((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${d}"`))||o===oe.TEXT)};return this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield R(Object.assign(Object.assign({},r),{representations:Vt(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,s){return be(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ee.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new go(oe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new go(oe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),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(ra).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=lo(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P);this.manifestUrlString=Re(this.manifestUrlString,u+1e3,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Ao.map(l=>a.fromEvent(this.element,l))).pipe(a.throttle(ra),a.map(l=>this.element?st(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(d=>{var u,c;let h=0;if(d){const f=((c=(u=this.element)===null||u===void 0?void 0:u.currentTime)!==null&&c!==void 0?c:0)*1e3;h=Math.min(...this.bufferManagers.map(m=>{var b,g;return(g=(b=m.getLiveSegmentsToLoadState(this.manifest))===null||b===void 0?void 0:b.to)!==null&&g!==void 0?g:0}))-f}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(d=>K(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const u=this.element.playbackRate,c=lo(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P),h=pg*u,f=vg*u,p=mg*u;l=d>l?d:l;const m=c===0&&d<p,b=c!==0&&d<h+p&&d>=h,g=c!==0&&d<h;if(g||b){const E=l-(h+f),y=Math.trunc(c+E/u);let v;d?y>0?v=y:v=0:v=c,this.manifestUrlString=Re(this.manifestUrlString,v,ae.DASH_CMAF_OFFSET_P)}(m||g||b)&&(yield this.updateLive(),l=0)})))}const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(a.merge(...this.bufferManagers.map(l=>l.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 R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(Ee.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=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 Tg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,s,r,n;return K(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.manifestUrlString=Re(this.manifestUrlString,e,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Ee.RUNNING),this.subscription.add(a.merge(...Ao.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&&sa(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return K(this,void 0,void 0,function*(){const s={[oe.VIDEO]:this.videoBufferManager,[oe.AUDIO]:this.audioBufferManager,[oe.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),sa(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ee.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(),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}updateLive(){var e;return K(this,void 0,void 0,function*(){this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class dy{constructor(e,t){this.fov=e,this.orientation=t}}class cy{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,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=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,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var hy=`#define GLSLIFY 1
|
|
30
30
|
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;}`,fy=`#ifdef GL_ES
|
|
31
31
|
precision highp float;precision highp int;
|
|
32
32
|
#else
|