@vkontakte/videoplayer-core 2.0.87-dev.dd7051a.0 → 2.0.88
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 +6 -6
- package/es2015.esm.js +6 -6
- package/es2018.cjs.js +6 -6
- package/es2018.esm.js +6 -6
- package/esnext.cjs.js +6 -6
- package/esnext.esm.js +6 -6
- package/evergreen.esm.js +6 -6
- package/index.d.ts +10 -25
- package/package.json +2 -2
package/es2015.cjs.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
* Mon,
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.88
|
|
3
|
+
* Mon, 03 Jul 2023 18:19:16 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-88/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var _u=Object.create;var Da=Object.defineProperty;var Ru=Object.getOwnPropertyDescriptor;var Iu=Object.getOwnPropertyNames;var Nu=Object.getPrototypeOf,Du=Object.prototype.hasOwnProperty;var Cu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Iu(e))!Du.call(i,s)&&s!==t&&Da(i,s,{get:()=>e[s],enumerable:!(r=Ru(e,s))||r.enumerable});return i};var Ca=(i,e,t)=>(t=i!=null?_u(Nu(i)):{},Cu(e||!i||!i.__esModule?Da(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Ou=require("lodash/debounce.js");const _o="2.0.87-dev.dd7051a.0";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 ve;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ve||(ve={}));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 Q(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(d){try{u(r.next(d))}catch(h){o(h)}}function c(d){try{u(r.throw(d))}catch(h){o(h)}}function u(d){d.done?n(d.value):s(d.value).then(l,c)}u((r=r.apply(i,e||[])).next())})}function D(i){return this instanceof D?(this.v=i,this):new D(i)}function we(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(m,b){n.push([f,p,m,b])>1||l(f,p)})})}function l(f,p){try{c(r[f](p))}catch(m){h(n[0][3],m)}}function c(f){f.value instanceof D?Promise.resolve(f.value.v).then(u,d):h(n[0][2],f)}function u(f){l("next",f)}function d(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var Lu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class xu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Lu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(Bu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const c=r.getCurrentSession();a.assertNonNullable(c);const u=c.getCastDevice(),d=(n=c.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(d)||d===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:c,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Bu=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 Oa=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},ye=function(i){try{return!!i()}catch(e){return!0}},Mu=ye,lr=!Mu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Ro=lr,Io=Function.prototype,As=Io.call,Vu=Ro&&Io.bind.bind(As,As),Ee=Ro?Vu:function(i){return function(){return As.apply(i,arguments)}},No=Ee,Fu=No({}.toString),Uu=No("".slice),ui=function(i){return Uu(Fu(i),8,-1)},ju=Ee,Hu=ye,Gu=ui,_r=Object,qu=ju("".split),Yu=Hu(function(){return!_r("z").propertyIsEnumerable(0)})?function(i){return Gu(i)=="String"?qu(i,""):_r(i)}:_r,di=function(i){return i==null},zu=di,Wu=TypeError,Qs=function(i){if(zu(i))throw Wu("Can't call method on "+i);return i},Qu=Yu,Ju=Qs,ci=function(i){return Qu(Ju(i))},Ku=function(){},Vt={},Pi=function(i){return i&&i.Math==Math&&i},ue=Pi(typeof globalThis=="object"&&globalThis)||Pi(typeof window=="object"&&window)||Pi(typeof self=="object"&&self)||Pi(typeof Oa=="object"&&Oa)||function(){return this}()||Function("return this")(),ws=typeof document=="object"&&document.all,Xu=typeof ws=="undefined"&&ws!==void 0,Do={all:ws,IS_HTMLDDA:Xu},Co=Do,Zu=Co.all,ae=Co.IS_HTMLDDA?function(i){return typeof i=="function"||i===Zu}:function(i){return typeof i=="function"},ed=ue,td=ae,La=ed.WeakMap,id=td(La)&&/native code/.test(String(La)),xa=ae,Oo=Do,rd=Oo.all,ze=Oo.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:xa(i)||i===rd}:function(i){return typeof i=="object"?i!==null:xa(i)},sd=ye,We=!sd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),vt={},ad=ue,Ba=ze,_s=ad.document,nd=Ba(_s)&&Ba(_s.createElement),Js=function(i){return nd?_s.createElement(i):{}},od=We,ld=ye,ud=Js,Lo=!od&&!ld(function(){return Object.defineProperty(ud("div"),"a",{get:function(){return 7}}).a!=7}),dd=We,cd=ye,xo=dd&&cd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),hd=ze,fd=String,pd=TypeError,Qe=function(i){if(hd(i))return i;throw pd(fd(i)+" is not an object")},vd=lr,ki=Function.prototype.call,be=vd?ki.bind(ki):function(){return ki.apply(ki,arguments)},Ks={},Rr=Ks,Ir=ue,md=ae,Ma=function(i){return md(i)?i:void 0},mt=function(i,e){return arguments.length<2?Ma(Rr[i])||Ma(Ir[i]):Rr[i]&&Rr[i][e]||Ir[i]&&Ir[i][e]},bd=Ee,ur=bd({}.isPrototypeOf),dr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Bo=ue,Nr=dr,Va=Bo.process,Fa=Bo.Deno,Ua=Va&&Va.versions||Fa&&Fa.version,ja=Ua&&Ua.v8,Ae,Ki;ja&&(Ae=ja.split("."),Ki=Ae[0]>0&&Ae[0]<4?1:+(Ae[0]+Ae[1]));!Ki&&Nr&&(Ae=Nr.match(/Edge\/(\d+)/),(!Ae||Ae[1]>=74)&&(Ae=Nr.match(/Chrome\/(\d+)/),Ae&&(Ki=+Ae[1])));var Mo=Ki,Ha=Mo,Sd=ye,Vo=!!Object.getOwnPropertySymbols&&!Sd(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Ha&&Ha<41}),gd=Vo,Fo=gd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",yd=mt,Ed=ae,Td=ur,$d=Fo,Pd=Object,Uo=$d?function(i){return typeof i=="symbol"}:function(i){var e=yd("Symbol");return Ed(e)&&Td(e.prototype,Pd(i))},kd=String,cr=function(i){try{return kd(i)}catch(e){return"Object"}},Ad=ae,wd=cr,_d=TypeError,bt=function(i){if(Ad(i))return i;throw _d(wd(i)+" is not a function")},Rd=bt,Id=di,hr=function(i,e){var t=i[e];return Id(t)?void 0:Rd(t)},Dr=be,Cr=ae,Or=ze,Nd=TypeError,Dd=function(i,e){var t,r;if(e==="string"&&Cr(t=i.toString)&&!Or(r=Dr(t,i))||Cr(t=i.valueOf)&&!Or(r=Dr(t,i))||e!=="string"&&Cr(t=i.toString)&&!Or(r=Dr(t,i)))return r;throw Nd("Can't convert object to primitive value")},Xi={},Cd={get exports(){return Xi},set exports(i){Xi=i}},jo=!0,Ga=ue,Od=Object.defineProperty,Ld=function(i,e){try{Od(Ga,i,{value:e,configurable:!0,writable:!0})}catch(t){Ga[i]=e}return e},xd=ue,Bd=Ld,qa="__core-js_shared__",Md=xd[qa]||Bd(qa,{}),Xs=Md,Ya=Xs;(Cd.exports=function(i,e){return Ya[i]||(Ya[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var Vd=Qs,Fd=Object,fr=function(i){return Fd(Vd(i))},Ud=Ee,jd=fr,Hd=Ud({}.hasOwnProperty),Me=Object.hasOwn||function(e,t){return Hd(jd(e),t)},Gd=Ee,qd=0,Yd=Math.random(),zd=Gd(1 .toString),Ho=function(i){return"Symbol("+(i===void 0?"":i)+")_"+zd(++qd+Yd,36)},Wd=ue,Qd=Xi,za=Me,Jd=Ho,Kd=Vo,Xd=Fo,Rt=Wd.Symbol,Lr=Qd("wks"),Zd=Xd?Rt.for||Rt:Rt&&Rt.withoutSetter||Jd,de=function(i){return za(Lr,i)||(Lr[i]=Kd&&za(Rt,i)?Rt[i]:Zd("Symbol."+i)),Lr[i]},ec=be,Wa=ze,Qa=Uo,tc=hr,ic=Dd,rc=de,sc=TypeError,ac=rc("toPrimitive"),nc=function(i,e){if(!Wa(i)||Qa(i))return i;var t=tc(i,ac),r;if(t){if(e===void 0&&(e="default"),r=ec(t,i,e),!Wa(r)||Qa(r))return r;throw sc("Can't convert object to primitive value")}return e===void 0&&(e="number"),ic(i,e)},oc=nc,lc=Uo,Zs=function(i){var e=oc(i,"string");return lc(e)?e:e+""},uc=We,dc=Lo,cc=xo,Ai=Qe,Ja=Zs,hc=TypeError,xr=Object.defineProperty,fc=Object.getOwnPropertyDescriptor,Br="enumerable",Mr="configurable",Vr="writable";vt.f=uc?cc?function(e,t,r){if(Ai(e),t=Ja(t),Ai(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Vr in r&&!r[Vr]){var s=fc(e,t);s&&s[Vr]&&(e[t]=r.value,r={configurable:Mr in r?r[Mr]:s[Mr],enumerable:Br in r?r[Br]:s[Br],writable:!1})}return xr(e,t,r)}:xr:function(e,t,r){if(Ai(e),t=Ja(t),Ai(r),dc)try{return xr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw hc("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var pr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},pc=We,vc=vt,mc=pr,hi=pc?function(i,e,t){return vc.f(i,e,mc(1,t))}:function(i,e,t){return i[e]=t,i},bc=Xi,Sc=Ho,Ka=bc("keys"),ea=function(i){return Ka[i]||(Ka[i]=Sc(i))},ta={},gc=id,Go=ue,yc=ze,Ec=hi,Fr=Me,Ur=Xs,Tc=ea,$c=ta,Xa="Object already initialized",Rs=Go.TypeError,Pc=Go.WeakMap,Zi,oi,er,kc=function(i){return er(i)?oi(i):Zi(i,{})},Ac=function(i){return function(e){var t;if(!yc(e)||(t=oi(e)).type!==i)throw Rs("Incompatible receiver, "+i+" required");return t}};if(gc||Ur.state){var Ce=Ur.state||(Ur.state=new Pc);Ce.get=Ce.get,Ce.has=Ce.has,Ce.set=Ce.set,Zi=function(i,e){if(Ce.has(i))throw Rs(Xa);return e.facade=i,Ce.set(i,e),e},oi=function(i){return Ce.get(i)||{}},er=function(i){return Ce.has(i)}}else{var $t=Tc("state");$c[$t]=!0,Zi=function(i,e){if(Fr(i,$t))throw Rs(Xa);return e.facade=i,Ec(i,$t,e),e},oi=function(i){return Fr(i,$t)?i[$t]:{}},er=function(i){return Fr(i,$t)}}var qo={set:Zi,get:oi,has:er,enforce:kc,getterFor:Ac},wc=lr,Yo=Function.prototype,Za=Yo.apply,en=Yo.call,zo=typeof Reflect=="object"&&Reflect.apply||(wc?en.bind(Za):function(){return en.apply(Za,arguments)}),_c=ui,Rc=Ee,Wo=function(i){if(_c(i)==="Function")return Rc(i)},ia={},Qo={},Jo={}.propertyIsEnumerable,Ko=Object.getOwnPropertyDescriptor,Ic=Ko&&!Jo.call({1:2},1);Qo.f=Ic?function(e){var t=Ko(this,e);return!!t&&t.enumerable}:Jo;var Nc=We,Dc=be,Cc=Qo,Oc=pr,Lc=ci,xc=Zs,Bc=Me,Mc=Lo,tn=Object.getOwnPropertyDescriptor;ia.f=Nc?tn:function(e,t){if(e=Lc(e),t=xc(t),Mc)try{return tn(e,t)}catch(r){}if(Bc(e,t))return Oc(!Dc(Cc.f,e,t),e[t])};var Vc=ye,Fc=ae,Uc=/#|\.prototype\./,fi=function(i,e){var t=Hc[jc(i)];return t==qc?!0:t==Gc?!1:Fc(e)?Vc(e):!!e},jc=fi.normalize=function(i){return String(i).replace(Uc,".").toLowerCase()},Hc=fi.data={},Gc=fi.NATIVE="N",qc=fi.POLYFILL="P",Xo=fi,rn=Wo,Yc=bt,zc=lr,Wc=rn(rn.bind),vr=function(i,e){return Yc(i),e===void 0?i:zc?Wc(i,e):function(){return i.apply(e,arguments)}},wi=ue,Qc=zo,Jc=Wo,Kc=ae,Xc=ia.f,Zc=Xo,Pt=Ks,eh=vr,kt=hi,sn=Me,th=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return Qc(i,this,arguments)};return e.prototype=i.prototype,e},Re=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?wi:s?wi[t]:(wi[t]||{}).prototype,l=r?Pt:Pt[t]||kt(Pt,t,{})[t],c=l.prototype,u,d,h,f,p,m,b,g,v;for(f in e)u=Zc(r?f:t+(s?".":"#")+f,i.forced),d=!u&&o&&sn(o,f),m=l[f],d&&(i.dontCallGetSet?(v=Xc(o,f),b=v&&v.value):b=o[f]),p=d&&b?b:e[f],!(d&&typeof m==typeof p)&&(i.bind&&d?g=eh(p,wi):i.wrap&&d?g=th(p):n&&Kc(p)?g=Jc(p):g=p,(i.sham||p&&p.sham||m&&m.sham)&&kt(g,"sham",!0),kt(l,f,g),n&&(h=t+"Prototype",sn(Pt,h)||kt(Pt,h,{}),kt(Pt[h],f,p),i.real&&c&&(u||!c[f])&&kt(c,f,p)))},Is=We,ih=Me,Zo=Function.prototype,rh=Is&&Object.getOwnPropertyDescriptor,ra=ih(Zo,"name"),sh=ra&&function(){}.name==="something",ah=ra&&(!Is||Is&&rh(Zo,"name").configurable),nh={EXISTS:ra,PROPER:sh,CONFIGURABLE:ah},el={},oh=Math.ceil,lh=Math.floor,uh=Math.trunc||function(e){var t=+e;return(t>0?lh:oh)(t)},dh=uh,sa=function(i){var e=+i;return e!==e||e===0?0:dh(e)},ch=sa,hh=Math.max,fh=Math.min,ph=function(i,e){var t=ch(i);return t<0?hh(t+e,0):fh(t,e)},vh=sa,mh=Math.min,bh=function(i){return i>0?mh(vh(i),9007199254740991):0},Sh=bh,aa=function(i){return Sh(i.length)},gh=ci,yh=ph,Eh=aa,an=function(i){return function(e,t,r){var s=gh(e),n=Eh(s),o=yh(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Th={includes:an(!0),indexOf:an(!1)},$h=Ee,jr=Me,Ph=ci,kh=Th.indexOf,Ah=ta,nn=$h([].push),wh=function(i,e){var t=Ph(i),r=0,s=[],n;for(n in t)!jr(Ah,n)&&jr(t,n)&&nn(s,n);for(;e.length>r;)jr(t,n=e[r++])&&(~kh(s,n)||nn(s,n));return s},tl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],_h=wh,Rh=tl,Ih=Object.keys||function(e){return _h(e,Rh)},Nh=We,Dh=xo,Ch=vt,Oh=Qe,Lh=ci,xh=Ih;el.f=Nh&&!Dh?Object.defineProperties:function(e,t){Oh(e);for(var r=Lh(t),s=xh(t),n=s.length,o=0,l;n>o;)Ch.f(e,l=s[o++],r[l]);return e};var Bh=mt,il=Bh("document","documentElement"),Mh=Qe,Vh=el,on=tl,Fh=ta,Uh=il,jh=Js,Hh=ea,ln=">",un="<",Ns="prototype",Ds="script",rl=Hh("IE_PROTO"),Hr=function(){},sl=function(i){return un+Ds+ln+i+un+"/"+Ds+ln},dn=function(i){i.write(sl("")),i.close();var e=i.parentWindow.Object;return i=null,e},Gh=function(){var i=jh("iframe"),e="java"+Ds+":",t;return i.style.display="none",Uh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(sl("document.F=Object")),t.close(),t.F},_i,Yi=function(){try{_i=new ActiveXObject("htmlfile")}catch(e){}Yi=typeof document!="undefined"?document.domain&&_i?dn(_i):Gh():dn(_i);for(var i=on.length;i--;)delete Yi[Ns][on[i]];return Yi()};Fh[rl]=!0;var al=Object.create||function(e,t){var r;return e!==null?(Hr[Ns]=Mh(e),r=new Hr,Hr[Ns]=null,r[rl]=e):r=Yi(),t===void 0?r:Vh.f(r,t)},qh=ye,Yh=!qh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),zh=Me,Wh=ae,Qh=fr,Jh=ea,Kh=Yh,cn=Jh("IE_PROTO"),Cs=Object,Xh=Cs.prototype,nl=Kh?Cs.getPrototypeOf:function(i){var e=Qh(i);if(zh(e,cn))return e[cn];var t=e.constructor;return Wh(t)&&e instanceof t?t.prototype:e instanceof Cs?Xh:null},Zh=hi,na=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Zh(i,e,t),i},ef=ye,tf=ae,rf=ze,sf=al,hn=nl,af=na,nf=de,Os=nf("iterator"),ol=!1,qe,Gr,qr;[].keys&&(qr=[].keys(),"next"in qr?(Gr=hn(hn(qr)),Gr!==Object.prototype&&(qe=Gr)):ol=!0);var of=!rf(qe)||ef(function(){var i={};return qe[Os].call(i)!==i});of?qe={}:qe=sf(qe);tf(qe[Os])||af(qe,Os,function(){return this});var ll={IteratorPrototype:qe,BUGGY_SAFARI_ITERATORS:ol},lf=de,uf=lf("toStringTag"),ul={};ul[uf]="z";var oa=String(ul)==="[object z]",df=oa,cf=ae,zi=ui,hf=de,ff=hf("toStringTag"),pf=Object,vf=zi(function(){return arguments}())=="Arguments",mf=function(i,e){try{return i[e]}catch(t){}},pi=df?zi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=mf(e=pf(i),ff))=="string"?t:vf?zi(e):(r=zi(e))=="Object"&&cf(e.callee)?"Arguments":r},bf=oa,Sf=pi,gf=bf?{}.toString:function(){return"[object "+Sf(this)+"]"},yf=oa,Ef=vt.f,Tf=hi,$f=Me,Pf=gf,kf=de,fn=kf("toStringTag"),la=function(i,e,t,r){if(i){var s=t?i:i.prototype;$f(s,fn)||Ef(s,fn,{configurable:!0,value:e}),r&&!yf&&Tf(s,"toString",Pf)}},Af=ll.IteratorPrototype,wf=al,_f=pr,Rf=la,If=Vt,Nf=function(){return this},Df=function(i,e,t,r){var s=e+" Iterator";return i.prototype=wf(Af,{next:_f(+!r,t)}),Rf(i,s,!1,!0),If[s]=Nf,i},Cf=Re,Of=be,dl=nh,Lf=Df,xf=nl,Bf=la,pn=na,Mf=de,vn=Vt,cl=ll,Vf=dl.PROPER;dl.CONFIGURABLE;cl.IteratorPrototype;var Ri=cl.BUGGY_SAFARI_ITERATORS,Yr=Mf("iterator"),mn="keys",Ii="values",bn="entries",Ff=function(){return this},Uf=function(i,e,t,r,s,n,o){Lf(t,e,r);var l=function(v){if(v===s&&f)return f;if(!Ri&&v in d)return d[v];switch(v){case mn:return function(){return new t(this,v)};case Ii:return function(){return new t(this,v)};case bn:return function(){return new t(this,v)}}return function(){return new t(this)}},c=e+" Iterator",u=!1,d=i.prototype,h=d[Yr]||d["@@iterator"]||s&&d[s],f=!Ri&&h||l(s),p=e=="Array"&&d.entries||h,m,b,g;if(p&&(m=xf(p.call(new i)),m!==Object.prototype&&m.next&&(Bf(m,c,!0,!0),vn[c]=Ff)),Vf&&s==Ii&&h&&h.name!==Ii&&(u=!0,f=function(){return Of(h,this)}),s)if(b={values:l(Ii),keys:n?f:l(mn),entries:l(bn)},o)for(g in b)(Ri||u||!(g in d))&&pn(d,g,b[g]);else Cf({target:e,proto:!0,forced:Ri||u},b);return o&&d[Yr]!==f&&pn(d,Yr,f,{name:s}),vn[e]=f,b},jf=function(i,e){return{value:i,done:e}},Hf=ci,ua=Ku,Sn=Vt,hl=qo,Gf=vt.f,qf=Uf,Ni=jf,Yf=jo,zf=We,fl="Array Iterator",Wf=hl.set,Qf=hl.getterFor(fl);qf(Array,"Array",function(i,e){Wf(this,{type:fl,target:Hf(i),index:0,kind:e})},function(){var i=Qf(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Ni(void 0,!0)):t=="keys"?Ni(r,!1):t=="values"?Ni(e[r],!1):Ni([r,e[r]],!1)},"values");var gn=Sn.Arguments=Sn.Array;ua();ua();ua();if(!Yf&&zf&&gn.name!=="values")try{Gf(gn,"name",{value:"values"})}catch(i){}var Jf=de,Kf=Vt,Xf=Jf("iterator"),Zf=Array.prototype,ep=function(i){return i!==void 0&&(Kf.Array===i||Zf[Xf]===i)},tp=pi,yn=hr,ip=di,rp=Vt,sp=de,ap=sp("iterator"),pl=function(i){if(!ip(i))return yn(i,ap)||yn(i,"@@iterator")||rp[tp(i)]},np=be,op=bt,lp=Qe,up=cr,dp=pl,cp=TypeError,hp=function(i,e){var t=arguments.length<2?dp(i):e;if(op(t))return lp(np(t,i));throw cp(up(i)+" is not iterable")},fp=be,En=Qe,pp=hr,vp=function(i,e,t){var r,s;En(i);try{if(r=pp(i,"return"),!r){if(e==="throw")throw t;return t}r=fp(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return En(r),t},mp=vr,bp=be,Sp=Qe,gp=cr,yp=ep,Ep=aa,Tn=ur,Tp=hp,$p=pl,$n=vp,Pp=TypeError,Wi=function(i,e){this.stopped=i,this.result=e},Pn=Wi.prototype,da=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),c=mp(e,r),u,d,h,f,p,m,b,g=function(S){return u&&$n(u,"normal",S),new Wi(!0,S)},v=function(S){return s?(Sp(S),l?c(S[0],S[1],g):c(S[0],S[1])):l?c(S,g):c(S)};if(n)u=i.iterator;else if(o)u=i;else{if(d=$p(i),!d)throw Pp(gp(i)+" is not iterable");if(yp(d)){for(h=0,f=Ep(i);f>h;h++)if(p=v(i[h]),p&&Tn(Pn,p))return p;return new Wi(!1)}u=Tp(i,d)}for(m=n?i.next:u.next;!(b=bp(m,u)).done;){try{p=v(b.value)}catch(S){$n(u,"throw",S)}if(typeof p=="object"&&p&&Tn(Pn,p))return p}return new Wi(!1)},kp=Zs,Ap=vt,wp=pr,_p=function(i,e,t){var r=kp(e);r in i?Ap.f(i,r,wp(0,t)):i[r]=t},Rp=Re,Ip=da,Np=_p;Rp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Ip(e,function(r,s){Np(t,r,s)},{AS_ENTRIES:!0}),t}});var Dp=Ks,Cp=Dp.Object.fromEntries,Op={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},Lp=Op,xp=ue,Bp=pi,Mp=hi,kn=Vt,Vp=de,An=Vp("toStringTag");for(var zr in Lp){var wn=xp[zr],Wr=wn&&wn.prototype;Wr&&Bp(Wr)!==An&&Mp(Wr,An,zr),kn[zr]=kn.Array}var Fp=Cp,Up=Fp,jp=Up,Hp=jp,vi=Hp,Gp=ui,mr=typeof process!="undefined"&&Gp(process)=="process",qp=mt,Yp=vt,zp=de,Wp=We,_n=zp("species"),Qp=function(i){var e=qp(i),t=Yp.f;Wp&&e&&!e[_n]&&t(e,_n,{configurable:!0,get:function(){return this}})},Jp=ur,Kp=TypeError,Xp=function(i,e){if(Jp(e,i))return i;throw Kp("Incorrect invocation")},Zp=Ee,ev=ae,Ls=Xs,tv=Zp(Function.toString);ev(Ls.inspectSource)||(Ls.inspectSource=function(i){return tv(i)});var vl=Ls.inspectSource,iv=Ee,rv=ye,ml=ae,sv=pi,av=mt,nv=vl,bl=function(){},ov=[],Sl=av("Reflect","construct"),ca=/^\s*(?:class|function)\b/,lv=iv(ca.exec),uv=!ca.exec(bl),Kt=function(e){if(!ml(e))return!1;try{return Sl(bl,ov,e),!0}catch(t){return!1}},gl=function(e){if(!ml(e))return!1;switch(sv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return uv||!!lv(ca,nv(e))}catch(t){return!0}};gl.sham=!0;var dv=!Sl||rv(function(){var i;return Kt(Kt.call)||!Kt(Object)||!Kt(function(){i=!0})||i})?gl:Kt,cv=dv,hv=cr,fv=TypeError,pv=function(i){if(cv(i))return i;throw fv(hv(i)+" is not a constructor")},Rn=Qe,vv=pv,mv=di,bv=de,Sv=bv("species"),yl=function(i,e){var t=Rn(i).constructor,r;return t===void 0||mv(r=Rn(t)[Sv])?e:vv(r)},gv=Ee,yv=gv([].slice),Ev=TypeError,Tv=function(i,e){if(i<e)throw Ev("Not enough arguments");return i},$v=dr,El=/(?:ipad|iphone|ipod).*applewebkit/i.test($v),me=ue,Pv=zo,kv=vr,In=ae,Av=Me,Tl=ye,Nn=il,wv=yv,Dn=Js,_v=Tv,Rv=El,Iv=mr,xs=me.setImmediate,Bs=me.clearImmediate,Nv=me.process,Qr=me.Dispatch,Dv=me.Function,Cn=me.MessageChannel,Cv=me.String,Jr=0,ii={},On="onreadystatechange",li,dt,Kr,Xr;Tl(function(){li=me.location});var ha=function(i){if(Av(ii,i)){var e=ii[i];delete ii[i],e()}},Zr=function(i){return function(){ha(i)}},Ln=function(i){ha(i.data)},xn=function(i){me.postMessage(Cv(i),li.protocol+"//"+li.host)};(!xs||!Bs)&&(xs=function(e){_v(arguments.length,1);var t=In(e)?e:Dv(e),r=wv(arguments,1);return ii[++Jr]=function(){Pv(t,void 0,r)},dt(Jr),Jr},Bs=function(e){delete ii[e]},Iv?dt=function(i){Nv.nextTick(Zr(i))}:Qr&&Qr.now?dt=function(i){Qr.now(Zr(i))}:Cn&&!Rv?(Kr=new Cn,Xr=Kr.port2,Kr.port1.onmessage=Ln,dt=kv(Xr.postMessage,Xr)):me.addEventListener&&In(me.postMessage)&&!me.importScripts&&li&&li.protocol!=="file:"&&!Tl(xn)?(dt=xn,me.addEventListener("message",Ln,!1)):On in Dn("script")?dt=function(i){Nn.appendChild(Dn("script"))[On]=function(){Nn.removeChild(this),ha(i)}}:dt=function(i){setTimeout(Zr(i),0)});var $l={set:xs,clear:Bs},Pl=function(){this.head=null,this.tail=null};Pl.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 kl=Pl,Ov=dr,Lv=/ipad|iphone|ipod/i.test(Ov)&&typeof Pebble!="undefined",xv=dr,Bv=/web0s(?!.*chrome)/i.test(xv),pt=ue,Bn=vr,Mv=ia.f,es=$l.set,Vv=kl,Fv=El,Uv=Lv,jv=Bv,ts=mr,Mn=pt.MutationObserver||pt.WebKitMutationObserver,Vn=pt.document,Fn=pt.process,Di=pt.Promise,Un=Mv(pt,"queueMicrotask"),Ms=Un&&Un.value,At,is,rs,Ci,jn;if(!Ms){var Oi=new Vv,Li=function(){var i,e;for(ts&&(i=Fn.domain)&&i.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&At(),t}i&&i.enter()};!Fv&&!ts&&!jv&&Mn&&Vn?(is=!0,rs=Vn.createTextNode(""),new Mn(Li).observe(rs,{characterData:!0}),At=function(){rs.data=is=!is}):!Uv&&Di&&Di.resolve?(Ci=Di.resolve(void 0),Ci.constructor=Di,jn=Bn(Ci.then,Ci),At=function(){jn(Li)}):ts?At=function(){Fn.nextTick(Li)}:(es=Bn(es,pt),At=function(){es(Li)}),Ms=function(i){Oi.head||At(),Oi.add(i)}}var Hv=Ms,Gv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},fa=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},qv=ue,Ft=qv.Promise,Al=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Yv=Al,zv=mr,Wv=!Yv&&!zv&&typeof window=="object"&&typeof document=="object",Qv=ue,ri=Ft,Jv=ae,Kv=Xo,Xv=vl,Zv=de,em=Wv,tm=Al,ss=Mo,Hn=ri&&ri.prototype,im=Zv("species"),Vs=!1,wl=Jv(Qv.PromiseRejectionEvent),rm=Kv("Promise",function(){var i=Xv(ri),e=i!==String(ri);if(!e&&ss===66||!(Hn.catch&&Hn.finally))return!0;if(!ss||ss<51||!/native code/.test(i)){var t=new ri(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[im]=r,Vs=t.then(function(){})instanceof r,!Vs)return!0}return!e&&(em||tm)&&!wl}),mi={CONSTRUCTOR:rm,REJECTION_EVENT:wl,SUBCLASSING:Vs},Ut={},Gn=bt,sm=TypeError,am=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw sm("Bad Promise constructor");e=r,t=s}),this.resolve=Gn(e),this.reject=Gn(t)};Ut.f=function(i){return new am(i)};var nm=Re,tr=mr,rt=ue,bi=be,om=na,lm=la,um=Qp,dm=bt,Fs=ae,cm=ze,hm=Xp,fm=yl,_l=$l.set,pa=Hv,pm=Gv,vm=fa,mm=kl,Rl=qo,Us=Ft,va=mi,Il=Ut,br="Promise",Nl=va.CONSTRUCTOR,bm=va.REJECTION_EVENT;va.SUBCLASSING;var as=Rl.getterFor(br),Sm=Rl.set,gm=Us&&Us.prototype,It=Us,ns=gm,Dl=rt.TypeError,js=rt.document,ma=rt.process,Hs=Il.f,ym=Hs,Em=!!(js&&js.createEvent&&rt.dispatchEvent),Cl="unhandledrejection",Tm="rejectionhandled",qn=0,Ol=1,$m=2,ba=1,Ll=2,xi,Yn,Pm,xl=function(i){var e;return cm(i)&&Fs(e=i.then)?e:!1},Bl=function(i,e){var t=e.value,r=e.state==Ol,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,c,u,d;try{s?(r||(e.rejection===Ll&&Am(e),e.rejection=ba),s===!0?c=t:(l&&l.enter(),c=s(t),l&&(l.exit(),d=!0)),c===i.promise?o(Dl("Promise-chain cycle")):(u=xl(c))?bi(u,c,n,o):n(c)):o(t)}catch(h){l&&!d&&l.exit(),o(h)}},Ml=function(i,e){i.notified||(i.notified=!0,pa(function(){for(var t=i.reactions,r;r=t.get();)Bl(r,i);i.notified=!1,e&&!i.rejection&&km(i)}))},Vl=function(i,e,t){var r,s;Em?(r=js.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),rt.dispatchEvent(r)):r={promise:e,reason:t},!bm&&(s=rt["on"+i])?s(r):i===Cl&&pm("Unhandled promise rejection",t)},km=function(i){bi(_l,rt,function(){var e=i.facade,t=i.value,r=zn(i),s;if(r&&(s=vm(function(){tr?ma.emit("unhandledRejection",t,e):Vl(Cl,e,t)}),i.rejection=tr||zn(i)?Ll:ba,s.error))throw s.value})},zn=function(i){return i.rejection!==ba&&!i.parent},Am=function(i){bi(_l,rt,function(){var e=i.facade;tr?ma.emit("rejectionHandled",e):Vl(Tm,e,i.value)})},Nt=function(i,e,t){return function(r){i(e,r,t)}},Ct=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=$m,Ml(i,!0))},Gs=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Dl("Promise can't be resolved itself");var r=xl(e);r?pa(function(){var s={done:!1};try{bi(r,e,Nt(Gs,s,i),Nt(Ct,s,i))}catch(n){Ct(s,n,i)}}):(i.value=e,i.state=Ol,Ml(i,!1))}catch(s){Ct({done:!1},s,i)}}};Nl&&(It=function(e){hm(this,ns),dm(e),bi(xi,this);var t=as(this);try{e(Nt(Gs,t),Nt(Ct,t))}catch(r){Ct(t,r)}},ns=It.prototype,xi=function(e){Sm(this,{type:br,done:!1,notified:!1,parent:!1,reactions:new mm,rejection:!1,state:qn,value:void 0})},xi.prototype=om(ns,"then",function(e,t){var r=as(this),s=Hs(fm(this,It));return r.parent=!0,s.ok=Fs(e)?e:!0,s.fail=Fs(t)&&t,s.domain=tr?ma.domain:void 0,r.state==qn?r.reactions.add(s):pa(function(){Bl(s,r)}),s.promise}),Yn=function(){var i=new xi,e=as(i);this.promise=i,this.resolve=Nt(Gs,e),this.reject=Nt(Ct,e)},Il.f=Hs=function(i){return i===It||i===Pm?new Yn(i):ym(i)});nm({global:!0,constructor:!0,wrap:!0,forced:Nl},{Promise:It});lm(It,br,!1,!0);um(br);var wm=de,Fl=wm("iterator"),Ul=!1;try{var _m=0,Wn={next:function(){return{done:!!_m++}},return:function(){Ul=!0}};Wn[Fl]=function(){return this},Array.from(Wn,function(){throw 2})}catch(i){}var Rm=function(i,e){if(!e&&!Ul)return!1;var t=!1;try{var r={};r[Fl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},Im=Ft,Nm=Rm,Dm=mi.CONSTRUCTOR,jl=Dm||!Nm(function(i){Im.all(i).then(void 0,function(){})}),Cm=Re,Om=be,Lm=bt,xm=Ut,Bm=fa,Mm=da,Vm=jl;Cm({target:"Promise",stat:!0,forced:Vm},{all:function(e){var t=this,r=xm.f(t),s=r.resolve,n=r.reject,o=Bm(function(){var l=Lm(t.resolve),c=[],u=0,d=1;Mm(e,function(h){var f=u++,p=!1;d++,Om(l,t,h).then(function(m){p||(p=!0,c[f]=m,--d||s(c))},n)}),--d||s(c)});return o.error&&n(o.value),r.promise}});var Fm=Re,Um=mi.CONSTRUCTOR,Qn=Ft;Qn&&Qn.prototype;Fm({target:"Promise",proto:!0,forced:Um,real:!0},{catch:function(i){return this.then(void 0,i)}});var jm=Re,Hm=be,Gm=bt,qm=Ut,Ym=fa,zm=da,Wm=jl;jm({target:"Promise",stat:!0,forced:Wm},{race:function(e){var t=this,r=qm.f(t),s=r.reject,n=Ym(function(){var o=Gm(t.resolve);zm(e,function(l){Hm(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var Qm=Re,Jm=be,Km=Ut,Xm=mi.CONSTRUCTOR;Qm({target:"Promise",stat:!0,forced:Xm},{reject:function(e){var t=Km.f(this);return Jm(t.reject,void 0,e),t.promise}});var Zm=Qe,eb=ze,tb=Ut,Hl=function(i,e){if(Zm(i),eb(e)&&e.constructor===i)return e;var t=tb.f(i),r=t.resolve;return r(e),t.promise},ib=Re,rb=mt,sb=jo,ab=Ft,nb=mi.CONSTRUCTOR,ob=Hl,lb=rb("Promise"),ub=!nb;ib({target:"Promise",stat:!0,forced:sb},{resolve:function(e){return ob(ub&&this===lb?ab:this,e)}});var db=Re,qs=Ft,cb=ye,hb=mt,fb=ae,pb=yl,Jn=Hl,vb=qs&&qs.prototype,mb=!!qs&&cb(function(){vb.finally.call({then:function(){}},function(){})});db({target:"Promise",proto:!0,real:!0,forced:mb},{finally:function(i){var e=pb(this,hb("Promise")),t=fb(i);return this.then(t?function(r){return Jn(e,i()).then(function(){return r})}:i,t?function(r){return Jn(e,i()).then(function(){throw r})}:i)}});var bb=mt,Sa=bb,Sb=Sa,gb=Sb("Promise","finally"),yb=gb,Eb=yb,Tb=Eb,$b=Tb,Sr=$b,Ot;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Ot||(Ot={}));var Lt=(i,e=0,t=Ot.OFFSET_P)=>{switch(t){case Ot.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Ot.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},k=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};exports.VideoQuality=void 0;(function(i){i.INVARIANT="Invariant quality",i.Q_144P="144p",i.Q_240P="240p",i.Q_360P="360p",i.Q_480P="480p",i.Q_720P="720p",i.Q_1080P="1080p",i.Q_1440P="1440p",i.Q_2160P="2160p",i.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const _e={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Qi=(i,e)=>_e[i].height>_e[e].height,Pb=(i,e)=>_e[i].height>=_e[e].height,si=(i,e)=>_e[i].height<_e[e].height,kb=(i,e)=>_e[i].height<=_e[e].height,Ab=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:si(e,t)?1:-1)[0],wb=Object.keys(_e).sort((i,e)=>si(i,e)?-1:1),St=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return wb.find(s=>{const n=_e[s];return n.width>=r&&n.height>=t})},_b=i=>_e[i].height,ir=i=>i===exports.VideoQuality.INVARIANT;class K{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}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const Rb=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 Ib=5,Nb=5,Db=500,Kn=7e3;class Cb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new K(O.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&r!==O.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case O.PLAYING:case O.PAUSED:case O.READY:break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){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(r)}break}case exports.PlaybackState.PAUSED:{switch(r){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(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Rb(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(Db)).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)>Ib)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),c=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==c&&this.params.output.isBuffering$.next(c),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Nb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(O.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:B.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PAUSED||e===O.PLAYING)&&(this.videoState.setState(O.PAUSED),k(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),k(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&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==O.STOPPED&&this.videoState.setState(O.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const d=r[e];a.assertNonNullable(d);const h=Ab(Object.keys(d));a.assertNonNullable(h);const f=d[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const d=r[e];a.assertNonNullable(d),s=d.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const d=r[e];a.assertNonNullable(d),s=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const d=r[e];a.assertNonNullable(d),s=d.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const d=r[e];a.assertNonNullable(d),s=Lt(d.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 d="Unsupported format for Chromecast",h=new Error(d);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:d,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:c,subtitle:u}=this.params.meta;return a.isNonNullable(c)&&(l.metadata.title=c),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===B.Applying||r.state===B.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Kn).subscribe(()=>n(`timeout(${Kn})`)))});Sr(Promise.race([t,r]).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()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Xn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Gl extends Xn{constructor(){super(),this.listeners||Xn.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 ql=class{constructor(){Object.defineProperty(this,"signal",{value:new Gl,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ql.prototype[Symbol.toStringTag]="AbortController",Gl.prototype[Symbol.toStringTag]="AbortSignal");function Yl(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 Ob(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!Yl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,d){let h;d&&d.signal&&(h=d.signal,delete d.signal);const f=new t(u,d);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(c,u)=>{const d=n&&n.prototype.isPrototypeOf(c)?c.signal:u?u.signal:void 0;if(d){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(d.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{d.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(c,u)])}return o(c,u)},Request:n}}const gr=Yl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zl=gr?Ob({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xt=gr?zl.fetch:window.fetch;gr?zl.Request:window.Request;const ft=gr?ql:window.AbortController,Xt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ai{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return Q(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=Xt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(Xt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),c=new ft,u=c.signal,d={url:e,from:s,to:n,loaded:0,data:null,abortController:c};u.addEventListener("abort",()=>this.onBigRequestAbort(d));const h=f=>{var p,m;throw(m=(p=this.params).onError)===null||m===void 0||m.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return xt(l,{signal:u}).then(f=>{var p,m,b;if(d.response=f,!f.ok||!f.body){this.onBigRequestError(d);return}const[g,v]=f.body.tee();(m=(p=this.params).onDownloadStream)===null||m===void 0||m.call(p,v);const S=g.getReader(),y=parseInt((b=f.headers.get("Content-Length"))!==null&&b!==void 0?b:"",10)||n-s+1;d.data=new ArrayBuffer(y);const E=new Uint8Array(d.data),T=({done:A,value:L})=>Q(this,void 0,void 0,function*(){A?this.onBigRequestProgress(d):L&&(E.set(L,d.loaded),d.loaded+=L.byteLength,this.onBigRequestProgress(d),yield S==null?void 0:S.read().then(T,ai.suppressStreamErrors).catch(h))});S==null||S.read().then(T,ai.suppressStreamErrors).catch(h)},ai.suppressAbort).catch(f=>this.onBigRequestError(d,f)),d}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,c,u,d,h,f,p,m;if(!this.activeRequests.has(e)||!n)return;const b=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const g of b){const{request:v}=g,[S,y]=Xt(v),E=S>=t&&y<=t+s,T=t>=S&&t+s<y,A=n.slice(S-t,Math.min(y-t+1,s));if((E||T)&&(v.requestStartDate=(c=v.requestStartDate)!==null&&c!==void 0?c:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=A.byteLength,v.bytesTotal=r-t),E){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((d=this.dashJsRequestQueue.get(e))!==null&&d!==void 0?d:[]).filter(R=>R!==g)),(h=g.success)===null||h===void 0||h.call(g,A,"",e);const L=o?Array.from(o.headers.entries()).map(([R,N])=>`${R}: ${N}`).join(`\r
|
|
7
|
-
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(v,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,L,[])}else T&&((m=g.progress)===null||m===void 0||m.call(g,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,c;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const d of u){const[h,f]=Xt(d.request);(h>=t&&h<r||f>t&&f<=r)&&((c=d==null?void 0:d.error)===null||c===void 0||c.call(d,d.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[c,u]=Xt(l.request);(c>=t&&c<r||u>t&&u<=r)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class rr{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(rr.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;rr.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Lb=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new rr(s,e,r)}}),xb=(i,e)=>{const t=new ai(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return Lb(o,t)}}},!0),()=>t.destroy()};var Bb=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},Mb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},c=d=>{var h,f,p,m,b;const g=vi(d.getAllResponseHeaders().trim().split(/[\n\r]+/).map(y=>y.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const y=parseInt((h=d.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=d.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=E!=null?E:y*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const v=(m=g["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,S=(b={1:!0,0:!1}[g["x-reused"]])!==null&&b!==void 0?b:void 0;r.next(v),s.next(S)},u=d=>{d.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:d}=this,h=d.load.bind(d);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...b){return c(this),p(...b)},f.progress=function(...b){return u(this),m(...b)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},Bt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Vb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Bt}),!0),Fb=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const Ie=i=>{i.removeAttribute("src"),i.load()},Be=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),c=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(d=>{const h=i.getState();r(d,h)&&i.setState(d)},n)),r(l,o)||(t(o),c&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(d=>{t(d.to),c&&i.setState(d.to)},n)),u},gt=(i,e,t)=>Be(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),Je=(i,e,t,r)=>Be(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),st=(i,e,t,r)=>Be(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Ub=i=>["__",i.language,i.label].join("|"),jb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Ve{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}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(Be(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},c)=>l===o[c].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:s})),this.subscription.add(Be(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Be(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var c,u,d,h,f;const p=(u=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ve.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:Ub(e);return this.externalTracks.has(s)?{id:s,type:"external",language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",language:t,label:r}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(r=>r.id===t)).forEach(t=>this.detach(t))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&jb(t,e)?t.mode="showing":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),this.externalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ke=i=>{let e=i.querySelector("video");const t=Boolean(e);return e?Ie(e):(e=document.createElement("video"),i.appendChild(e)),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),console.log("init video, reused:",t,e),{reused:t,video:e}};class ga{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 Wl=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},Zn=i=>{const e=Wl(i);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===i)},Hb=i=>{const e=Wl(i);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)};var Ql=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Ys=3;class Gb{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Ys&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Ys))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var Jl=(i,e,t=Ys)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let c=n-1;c>=0;c--)i.end(c)+t>=r&&(r=i.start(c));for(let c=n+1;c<i.length;c++)i.start(c)-t<=s&&(s=i.end(c))}}return{from:r,to:s}};const qb=100,Yb=i=>i.webkitAudioDecodedByteCount!==void 0?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!==void 0?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,Xe=i=>{const e=y=>a.fromEvent(i,y).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(y=>a.fromEvent(i,y))).pipe(a.map(y=>y.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Jl(i.buffered,i.currentTime))),n=Ql()?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),o=a.fromEvent(i,"playing").pipe(a.debounce(qb),a.map(()=>Yb(i))),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),c=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var y;const E=i.error;return{id:E?`MediaError#${E.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:E?E.message:"Error event from HTML video element",thrown:(y=i.error)!==null&&y!==void 0?y:void 0}})),d=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;d.subscribe(y=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(y)&&p>=i.duration-f&&y<=f&&h.next(p),p=y});const m=a.fromEvent(i,"enterpictureinpicture"),b=a.fromEvent(i,"leavepictureinpicture"),g=new a.ValueSubject(Hb(i));m.subscribe(()=>g.next(!0)),b.subscribe(()=>g.next(!1));const v=new a.ValueSubject(Zn(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>Zn(i))).subscribe(v),{playing$:n,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:d,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,isAudioAvailable$:o,playbackRateState$:c,inPiP$:g,inFullscreen$:v}},ya=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var zb=Re,Wb=fr,Qb=aa,Jb=sa;zb({target:"Array",proto:!0},{at:function(e){var t=Wb(this),r=Qb(t),s=Jb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Kb=Sa,Xb=Kb("Array","at"),Zb=Xb,eS=Zb,tS=eS,iS=tS,Ue=iS;let Ea=!1,He={};const rS=i=>{Ea=i},sS=()=>{He={}},aS=i=>{i(He)},Bi=(i,e)=>{var t;Ea&&(He.meta=(t=He.meta)!==null&&t!==void 0?t:{},He.meta[i]=e)};class Le{constructor(e){this.name=e}next(e){var t,r;if(!Ea)return;He.series=(t=He.series)!==null&&t!==void 0?t:{};const s=(r=He.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),He.series[this.name]=s}}const nS=new Le("best_bitrate"),oS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class lS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Si=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:c,history:u})=>{var d,h,f,p;const m=r.usePixelRatio&&(d=window.devicePixelRatio)!==null&&d!==void 0?d:1,b=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*r.containerSizeFactor,height:e.height*m*r.containerSizeFactor},g=b&&St(b),v=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,S=i.filter(I=>!ir(I.quality)).sort((I,_)=>Qi(I.quality,_.quality)?-1:1),y=(h=Ue(S,-1))===null||h===void 0?void 0:h.quality,E=(f=Ue(S,0))===null||f===void 0?void 0:f.quality,T=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&si(s.max,s.min)||a.isNonNullable(s.min)&&E&&Qi(s.min,E)||a.isNonNullable(s.max)&&y&&si(s.max,y),A=v*oS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),R=S.filter(I=>{const _=g?si(I.quality,g):!0,H=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(I.bitrate)?t-n>=I.bitrate*A:!0,J=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&c&&!ir(c.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&Qi(I.quality,c.quality),ee=T||(a.isNullable(s.max)||kb(I.quality,s.max))&&(a.isNullable(s.min)||Pb(I.quality,s.min));return _&&H&&!J&&ee})[0];R&&R.bitrate&&nS.next(R.bitrate);const N=(p=R!=null?R:S[Math.ceil((S.length-1)/2)])!==null&&p!==void 0?p:i[0],V=N&&u&&u.history[N.id]&&a.now()-u.history[N.id]<=r.trackCooldown&&(!u.last||N.id!==u.last.id);if(N!=null&&N.id&&u&&!V&&u.recordSelection(N),V&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(N),N};var ce=i=>new URL(i).hostname;const uS=300,sr=(i,e=uS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(Ou(o=>{const l=o[0];if(!l)return;let c,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,c=l.contentBoxSize[0].inlineSize):l.contentRect&&(c=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(c)&&a.isNonNullable(u)&&t.next({width:c,height:u})},e));return n.observe(i),()=>n.disconnect()}),Ze=i=>{try{i.pause(),i.playbackRate=0,Ie(i),i.remove()}catch(e){console.error(e)}},dS=5e3,Zt={};var M;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class eo{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(M.DOWNLOADING_LIB),this.textTracksManager=new Ve,this.videoTracks=[],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 ga,this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState(),c=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(s===M.DOWNLOADING_LIB||s===M.STREAM_INITIALIZED))switch((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&s!==M.STOPPED&&n!==exports.PlaybackState.STOPPED&&(c?this.seek(l.position-this.liveOffset.getTotalPausedTime()):this.seek(l.position)),n){case exports.PlaybackState.STOPPED:{switch(s){case M.STOPPED:break;case M.PLAYING:case M.PAUSED:case M.READY:this.stop();break;default:a.assertNever(s)}break}case exports.PlaybackState.READY:{switch(s){case M.STOPPED:this.prepare();break;case M.PLAYING:case M.PAUSED:case M.READY:break;default:a.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case M.PLAYING:break;case M.PAUSED:c&&(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 M.READY:this.play();break;case M.STOPPED:this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case M.PLAYING:this.pause(),this.liveOffset.pause();break;case M.PAUSED:break;case M.READY:this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.STOPPED:this.prepare();break;default:a.assertNever(s)}break}default:a.assertNever(n)}};const{reused:t,video:r}=Ke(e.container);this.video=r,this.videoReused=t,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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),dS);Sr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Zt.MediaPlayer=s.MediaPlayer,Zt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Zt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Zt.Debug,"dashjs not loaded"),this.player=Zt.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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?ya(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=xb(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&Fb(this.player),Bb(this.player),this.params.tuning.requestQuick&&Vb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},s=(v,S)=>this.subscription.add(v.subscribe(S,r));s(sr(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(v=>{const S=typeof v.error=="object"?v.error.code:v.error,y=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${S}`,message:y}})),e.error$),s(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.find(({bitrateInfo:y})=>y.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===M.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Be(t.videoTrack,()=>{var v,S;const y=this.player.getQualityFor("video");return(S=(v=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===y))===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 y=(S=this.videoTracks.find(({track:E})=>E.id===v))===null||S===void 0?void 0:S.bitrateInfo;y&&this.player.setQualityFor("video",y.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:r}))},r)),this.subscription.add(Be(t.autoVideoTrackSwitching,()=>{var v,S,y;return(y=(S=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||y===void 0?void 0:y.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:S}})=>{var y,E;const T=this.player.getDashMetrics(),A=T.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),L=(y=T.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&y!==void 0?y:exports.HttpConnectionType.HTTP1,R=(E={1:!0,0:!1}[A])!==null&&E!==void 0?E:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(R),e.hostname$.next(ce(S))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:S,availableFrom:y}}})=>{this.isLive$.next(S),this.availableFrom$.next(y.getTime()),S||e.duration$.next(v),this.videoTracks=[];const E=this.player.getQualityFor("video");let T;for(const A of this.player.getBitrateInfoListFor("video")){const L=A.qualityIndex.toString(10),R=St(A),N=A.bitrate/1e3,V={width:A.width,height:A.height},I=this.frameRatesByFrameHeight[A.height];if(R){const _={id:L,quality:R,bitrate:N,size:V,fps:I};this.videoTracks.push({track:_,bitrateInfo:A}),A.qualityIndex===E&&(T=_)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:A})=>A)),T&&e.currentVideoTrack$.next(T),this.videoState.setState(M.STREAM_INITIALIZED),this.videoState.startTransitionTo(M.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const S=v.requestEndDate.getTime()-v.firstByteDate.getTime(),y=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(y,S)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=Si(this.videoTracks.map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),y=this.videoTracks.find(({track:E})=>E===S);y!=null&&y.bitrateInfo&&this.player.setQualityFor("video",y==null?void 0:y.bitrateInfo.qualityIndex,!1)}),s(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));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:S})=>this.params.output.liveTime$.next(v+S*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>Jl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(M.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(M.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===M.READY&&this.videoState.setState(M.READY)}),s(this.isLive$,e.isLive$),s(sr(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));s(l,this.syncPlayback);const{playbackDuration$:c,ping$:u,connectionType$:d,connectionReused$:h}=Mb(this.player);s(d,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(c,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(re(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(v=>v<60))}),({isLive:v,isShort:S})=>{const y=!v&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:y}}})}),s(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$,r))},r)),s(re(this.player,"manifestLoaded"),v=>{var S,y,E,T,A,L,R;if(!((y=(S=v.data)===null||S===void 0?void 0:S.Period)===null||y===void 0)&&y.AdaptationSet){const N=[];for(const V of(T=(E=v.data)===null||E===void 0?void 0:E.Period)===null||T===void 0?void 0:T.AdaptationSet)if(V.contentType==="text"){const I=(A=V.Representation)===null||A===void 0?void 0:A.id,_=new URL((L=V.Representation)===null||L===void 0?void 0:L.BaseURL,(R=v.data)===null||R===void 0?void 0:R.baseUri).toString(),H="internal",J=V.lang,ee=Boolean(I.includes("auto"));N.push({id:I,url:_,type:H,language:J,isAuto:ee})}e.availableTextTracks$.next(N)}}),this.subscription.add(gt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:b,inFullscreen$:g}=Xe(this.video);this.subscription.add(Je(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(st(this.video,t.playbackRate,m,r)),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(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(M.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,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=Lt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ot.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(M.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(M.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(r){}this.videoReused?Ie(this.video):Ze(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var gi=i=>{switch(i){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}};const to=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 at=i=>Q(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!to(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return to(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});function le(){return a.now()}function Kl(i){return le()-i}function io(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,c=!1)=>{s(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return c&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function cS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Ji(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,c=!1,u=0,d,h,f=!1,p="arraybuffer",m=7e3,b=2e3,g=()=>{if(c)return;a.assertNonNullable(d);const _=Kl(d);let H;if(_<b){H=b-_,setTimeout(g,H);return}b*=2,b>m&&(b=m),o&&o.abort(),o=new s,A()};const v=_=>(n=_,I),S=_=>(h=_,I),y=()=>(p="json",I),E=()=>{if(!c){if(--u>=0){g(),r&&r();return}c=!0,h&&h(),t&&t()}},T=_=>(f=_,I),A=()=>{d=le(),o=new s,o.open("get",i);let _=0,H,J=0;const ee=()=>(a.assertNonNullable(d),Math.max(d,Math.max(H||0,J||0)));if(n&&o.addEventListener("progress",P=>{const C=le();n.updateChunk&&P.loaded>_&&(n.updateChunk(ee(),P.loaded-_),_=P.loaded,H=C)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(c)return;a.assertNonNullable(o);const P=o.status;if(P>=200&&P<300){if(o.response.byteLength&&n){const C=o.response.byteLength-_;C&&n.updateChunk&&n.updateChunk(ee(),C)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const P=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(J=le(),o.removeEventListener("readystatechange",P))};o.addEventListener("readystatechange",P)}return o.responseType=p,o.send(),I},I={withBitrateReporting:v,withParallel:T,withJSONResponse:y,withRetryCount:_=>(u=_,I),withRetryInterval:(_,H)=>(a.isNonNullable(_)&&(b=_),a.isNonNullable(H)&&(m=H),I),withTimeout:_=>(l=_,I),withFinally:S,send:A,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return I}const hS=100,fS=2e3,pS=500;let vS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-pS;if(t-e>fS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const c=n.bytes*o/l;s+=c,n.start=t,n.bytes-=c}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>hS&&(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 mS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=le(),s=c=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=c,e._errorCB?e._errorCB(c):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=c=>{e._complete=1,e._responseData=c,e._downloadTime=le()-r,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(c,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Ji(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=le()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=le();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Mi=1e4,Vi=3,bS=300,SS=2e3,gS=6e4,yS=10,ES=1,TS=500;class $S{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 vS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=io(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=io(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{cS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new mS(Vi,Mi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,c=null,u=null,d=!1;const h=()=>{const E=n&&(!d||d===this.rep);return E||t("Not running!"),E},f=(E,T,A)=>{c&&c.abort(),c=Ji(this.urlResolver.resolve(E,!1),T,A,()=>this._retryCallback()).withTimeout(Mi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Vi).withFinally(()=>{c=null}).send()},p=(E,T,A)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,A,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=E=>{const T=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),r.playbackRate=E)},b=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const A=le()-1e4;let L=0;for(let N=0;N<this.bufferStates.length;N++){const V=this.bufferStates[N];E=Math.min(E,V.buf),V.ts<A&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${E} drop=${L} jitter=${this.sourceJitter}`);let R=E-ES;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?m(1.15):R>1?m(1.1):R>.3?m(1.05):m(1)}},v=E=>{let T;const A=()=>T&&T.start?T.start.length:0,L=P=>T.start[P]/1e3,R=P=>T.dur[P]/1e3,N=P=>T.fragIndex+P,V=(P,C)=>({chunkIdx:N(P),startTS:L(P),dur:R(P),discontinuity:C}),I=()=>{let P=0;if(T&&T.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=C;this.sourceJitter>1&&(te+=this.sourceJitter-1);let se=T.dur.length-1;for(;se>=0&&(te-=T.dur[se],!(te<=0));--se);P=Math.min(se,T.dur.length-1-z),P=Math.max(P,0)}return V(P,!0)},_=P=>{const C=A();if(!(C<=0)){if(a.isNonNullable(P)){for(let z=0;z<C;z++)if(L(z)>P)return V(z)}return I()}},H=P=>{const C=A(),z=P?P.chunkIdx+1:0,te=z-T.fragIndex;if(!(C<=0)){if(!P||te<0||te-C>yS)return t(`Resync: offset=${te} bChunks=${C} chunk=`+JSON.stringify(P)),I();if(!(te>=C))return V(z-T.fragIndex,!1)}},J=(P,C,z)=>{u&&u.abort(),u=Ji(this.urlResolver.resolve(P,!0,this.lowLatency),C,z,()=>this._retryCallback()).withTimeout(Mi).withRetryCount(Vi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,C)=>{J(E,z=>{if(!h())return;T=z;const te=Boolean(T.lowLatency);te!==this.lowLatency&&b(te);let se=0;for(let he=0;he<T.dur.length;++he)se+=T.dur[he];se>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/T.dur.length)),s({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,P(_(C))},()=>this._handleNetworkError())},nextChunk:H}},S=()=>{n=!1,l&&l.abort(),c&&c.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return d={start:E=>{const{videoElement:T,logger:A}=this.params;let L=v(e.jidxUrl),R,N,V,I,_=0,H,J,ee;const P=()=>{H&&(clearTimeout(H),H=void 0);const U=Math.max(TS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=_+U,fe=le(),$e=Math.min(1e4,ne-fe);_=fe;const Fe=()=>{u||h()&&L.seek(()=>{h()&&(_=le(),C(),P())})};$e>0?H=window.setTimeout(()=>{this.paused?P():Fe()},$e):Fe()},C=()=>{let U;for(;U=L.nextChunk(I);)I=U,Ne(U);const ne=L.nextChunk(V);if(ne){if(V&&ne.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?P():(S(),this._initPlayerWith(e));return}he(ne)}else P()},z=(U,ne)=>{if(!h()||!this.sourceBuffer)return;let fe,$e,Fe;const nt=et=>{window.setTimeout(()=>{h()&&z(U,ne)},et)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),nt(100);else{const et=le(),yt=T.currentTime;!this.paused&&T.buffered.length>1&&J===yt&&et-ee>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),J!==yt&&(J=yt,ee=et);const De=this._getBufferSizeSec();if(De>30)A(`Buffered ${De} seconds; delaying appendBuffer`),nt(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:De}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(jt){if(jt.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Fe=this.sourceBuffer.buffered.length,Fe!==0&&(fe=this.sourceBuffer.buffered.start(0),$e=yt,$e-fe>4&&this.sourceBuffer.remove(fe,$e-3)),nt(1e3);else throw jt}}},te=()=>{N&&R&&(A([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(V)]),z(N,function(){N=null,C()}))},se=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),he=U=>{h()&&p(se(U),(ne,fe)=>{if(h()){if(fe/=1e3,N=ne,V=U,o=U.startTS,fe){const $e=Math.min(10,U.dur/fe);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*$e:$e}te()}},()=>this._handleNetworkError())},Ne=U=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(U),!1)))},Te=U=>{h()&&(e.cachedHeader=U,z(U,()=>{R=!0,te()}))};n=!0,L.seek(U=>{if(h()){if(_=le(),!U){P();return}I=U,!a.isNullable(E)||U.startTS>E?he(U):(V=U,C())}},E),e.cachedHeader?Te(e.cachedHeader):f(e.headerUrl,Te,()=>this._handleNetworkError())},stop:S,getTimestampSec:()=>o},d}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,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=le();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,c=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(c&&h>l&&Kl(o)<3e4)return;r(h)}c=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=le();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=Ji(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Mi).withRetryCount(Vi).withRetryInterval(bS,SS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;at(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((c,u)=>{c.video&&s.canPlayType(c.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(c.codecs)&&(c.index=u,l.push(c))}),l.sort(function(c,u){return c.video&&u.video?u.video.height-c.video.height:u.bitrate-c.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},gS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var x;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const PS=[x.PAUSED,x.PLAYING,x.READY],kS=[x.PAUSED,x.PLAYING,x.READY];class AS{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(x.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Ve,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ga,this._dashCb=o=>{var l,c,u,d;switch(o.name){case"buffering":{const h=o.isBuffering;this.params.output.isBuffering$.next(h);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${o.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const h=o.manifest,f=[];for(const p of h){const m=(l=p.name)!==null&&l!==void 0?l:p.index.toString(10),b=(c=gi(p.name))!==null&&c!==void 0?c:St(p.video),g=p.bitrate/1e3,v=Object.assign({},p.video);if(!b)continue;const S={id:m,quality:b,bitrate:g,size:v};f.push({track:S,representation:p})}this.representations$.next(f),this.params.output.availableVideoTracks$.next(f.map(({track:p})=>p)),((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const h=o.quality,f=(d=this.representations$.getValue().find(({representation:p})=>p===h))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(h.headerUrl,this.params.source.url).hostname),a.isNonNullable(f)&&this.params.output.currentVideoTrack$.next(f);break}case"bandwidth":{const{size:h,duration:f}=o;this.params.dependencies.throughputEstimator.addRawSpeed(h,f);break}case"index":{this.maxSeekBackTime$.next(o.shiftDuration),this.zeroTime$.next(o.zeroTime);break}}},this.syncPlayback=()=>{var o;const l=this.videoState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),h=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${l}; videoTransition: ${JSON.stringify(c)}; desiredPlaybackState: ${u}; seekState: ${JSON.stringify(h)};`}),u===exports.PlaybackState.STOPPED){l!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(!c){if(kS.includes(l)){const f=(o=this.params.desiredState.videoTrack.getTransition())===null||o===void 0?void 0:o.to;a.isNonNullable(f)&&this.setVideoTrack(f);const p=this.params.desiredState.autoVideoTrackSwitching.getTransition();p&&this.setAutoQuality(p.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested&&PS.includes(l)){this.seek(h.position-this.liveOffset.getTotalPausedTime());return}switch(l){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(Lt(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(u===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(u===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const f=d==null?void 0:d.from;f&&f===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)})}return;case x.PLAYING:u===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:u===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(x.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(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(l)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=o=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const{reused:r,video:s}=Ke(e.container);this.video=s,this.videoReused=r,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.hostname$.next(ce(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 n=Xe(this.video);this.subscription.add(n.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===x.READY&&this.videoState.setState(x.READY)},t)).add(n.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(n.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(n.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(o=>-o/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:n.timeUpdate$}).subscribe(({zeroTime:o,position:l})=>this.params.output.liveTime$.next(o+l*1e3),t)).add(gt(this.video,this.params.desiredState.isLooped,t)).add(Je(this.video,this.params.desiredState.volume,n.volumeState$,t)).add(n.volumeState$.subscribe(this.params.output.volume$,t)).add(st(this.video,this.params.desiredState.playbackRate,n.playbackRateState$,t)).add(n.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(n.playing$.subscribe(this.params.output.firstFrameEvent$)).add(n.canplay$.subscribe(this.params.output.canplay$)).add(n.inPiP$.subscribe(this.params.output.inPiP$)).add(n.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:o}})=>{const l=o&&_b(o);this.dash.setMaxAutoQuality(l)})).add(this.videoState.stateChangeEnded$.subscribe(o=>{var l;switch(o.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.READY:((l=this.params.desiredState.playbackState.getTransition())===null||l===void 0?void 0:l.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(this.video)}createLiveDashPlayer(){const e=new $S({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,r,s,n,o;const l=this.representations$.getValue(),c=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),d=!u&&a.isNonNullable(c)?c:(n=Si(l.map(({track:f})=>f),{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()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===d))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(d),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Lt(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}}var Xl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},ht=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const wS=i=>{const e=document.createElement("a");return e.href=i,e.origin},_S=i=>{const e=document.createElement("a");return e.href=i,e.host};class Zl{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,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,r,s,n,o,l,c,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.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 d=vi(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(d))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((c=this._progressCb)===null||c===void 0||c.call(this,this._xhr.response))}catch(d){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(d)}`,d),d}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(_S(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!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 ar{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(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let c=0;const u=Date.now();let d=0,h=0,f=0;const p=b=>{s(ar._str2ua(b.substr(c))),c=b.length};let m=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(m=Bt(m)),this._lastXhr=new Zl(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-c>l&&p(b),h===0){h=Date.now();return}f=b.length-d;const g=Date.now()-h;f>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:f,duration:g,speed:8*f/(g/1e3)}),f=0,d=b.length,h=Date.now()),this._onDashCallback("loading",{size:b.length,done:!1})},o,(b,g,v)=>this._params.onError(b,g,v))})}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(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};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=ar._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 r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);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 RS{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)?)?$/,r=(l,c)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*c},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=Bt(r)),new Zl(r,t,s=>{this.attachManifest(s,t,wS(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,d)=>{const h=u.attributes.getNamedItem(d);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],c=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var d,h,f,p,m,b,g,v,S,y,E,T,A,L,R,N,V,I,_;const H=u.getElementsByTagName("SegmentBase")[0],J=H&&o(H,"indexRange").split("-"),ee=H&&H.getElementsByTagName("Initialization")[0],P=ee&&o(ee,"range").split("-");if(!P||!J){const Ne=u.parentElement;if((Ne==null?void 0:Ne.getAttribute("contentType"))==="text"){const Te=(d=u.getAttribute("id"))!==null&&d!==void 0?d:void 0,U=(r?r+"/":"")+((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),ne=(b=Ne.getAttribute("lang"))!==null&&b!==void 0?b:void 0,fe=Te==null?void 0:Te.includes("auto");U&&c.push({id:Te,url:U,language:ne,isAuto:fe})}return}const C=.1,z=Number((g=u.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),te=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let se;const he=(S=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&S!==void 0?S:void 0;se=he?ya(he):void 0,l.push({width:Number((y=u.attributes.getNamedItem("width"))===null||y===void 0?void 0:y.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:z,baseURL:te,failoverHosts:t,indexFrom:Number(J[0]),indexTo:Number(J[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(A=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&A!==void 0?A:void 0,mimeType:(R=(L=u.attributes.getNamedItem("mimeType"))===null||L===void 0?void 0:L.value)!==null&&R!==void 0?R:void 0,fps:se,bufferSize:C*z/8,bufferLength:C,name:(V=(N=u.attributes.getNamedItem("okQuality"))===null||N===void 0?void 0:N.value)!==null&&V!==void 0?V:void 0,id:(_=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&_!==void 0?_:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}c.forEach(({id:u,language:d,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),d&&f.setAttribute("srclang",d),this._video.appendChild(f)}),this._representations.sort((u,d)=>d.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:c})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let c=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const d=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<d;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),m=c+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:c/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,c=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,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},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 r=new t;let s,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 d=this._appendVector[String(u.fromTime)];d!==s&&(s=d,this._params.onRepresentationPlay(d));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)},c=()=>{if(!this._stream)try{const u=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new ar({mediaSource:r,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),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",c),r.removeEventListener("webkitsourceopen",c)};r.addEventListener("sourceopen",c,!1),r.addEventListener("webkitsourceopen",c,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),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,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),c=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=c?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 r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,c)=>this._stream.remove(l,c)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,c)=>this._stream.remove(l,c)),this._loadRef(e,s.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 r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var F;(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"})(F||(F={}));const IS=[F.PAUSED,F.PLAYING];class NS{constructor(e){this.videoState=new K(F.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Ve,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:s,textRepresentations:n})=>{var o,l,c;const u=[];for(const d of s){const h=(l=(o=d.name)!==null&&o!==void 0?o:d.id)!==null&&l!==void 0?l:d.height.toString(10),f=(c=d.name&&gi(d.name))!==null&&c!==void 0?c:St(d),p=d.bandwidth/1e3,m={width:d.width,height:d.height},b=d.fps;if(!f)continue;const g={id:h,quality:f,bitrate:p,size:m,fps:b};u.push({track:g,representation:d})}if(this.representations$.next(u),this.params.output.availableVideoTracks$.next(u.map(({track:d})=>d)),(n==null?void 0:n.length)>0){const d=[];for(const h of n){const f=h.id||`${h.language}_${Date.now()}`;d.push({id:f,type:"internal",url:h.url,language:h.language,isAuto:h.isAuto})}this.params.output.availableTextTracks$.next(d)}this.videoState.setState(F.MANIFEST_LOADED)},this.handleRepresentationPlay=s=>{var n;const o=(n=this.representations$.getValue().find(({representation:l})=>l===s))===null||n===void 0?void 0:n.track;o&&(this.params.output.currentVideoTrack$.next(o),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(o.id))},this.selectRepresentation=()=>{const s=this.currentRepresentation$.getValue();return a.assertNonNullable(s,"Can't select representation. something went wrong"),s},this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(c)};`}),o===exports.PlaybackState.STOPPED){s!==F.STOPPED&&(this.videoState.startTransitionTo(F.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(F.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!n)switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&c.state===B.Requested&&IS.includes(s)&&this.seek(c.position,c.forcePrecise),s){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_LOADED),this.prepare();return;case F.MANIFEST_LOADED:this.videoState.startTransitionTo(F.INITIAL_REPRESENTATION_SELECTED);return;case F.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(F.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case F.METADATA_LOADED:this.videoState.startTransitionTo(F.READY),this.dash.updateRefsForCurrentTime();return;case F.READY:o===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed());return;case F.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(F.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case F.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(s)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})});const{reused:t,video:r}=Ke(e.container);this.video=r,this.videoReused=t,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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Gb(this.video),this.dash=new RS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:s=>this.dashLiteEvents.idxRequestPing$.next(s),onResponseHeaders:s=>this.dashLiteEvents.responseHeaders$.next(s),onManifestReady:({representations:s,textRepresentations:n})=>this.dashLiteEvents.manifestReady$.next({representations:s,textRepresentations:n}),onRepresentationPlay:s=>this.dashLiteEvents.representationPlay$.next(s),onBandwidthChange:s=>this.params.dependencies.throughputEstimator.addRawSpeed(s.size,s.duration),onError:(s,n,o)=>{this.log({message:`[DashLite error], ${s}`}),this.dashLiteEvents.error$.next({id:s,message:n,thrown:o,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,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();return c?c.to:l},n=Xe(this.video),o=(l,c)=>this.subscription.add(l.subscribe(c,r));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.isAudioAvailable$,e.isAudioAvailable$),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()===F.PLAYING||this.videoState.getState()===F.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(Je(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(st(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(sr(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===F.READY&&this.videoState.setState(F.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(F.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:c,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:c,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.stateChangeEnded$,this.params.output.element$,this.elementSize$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,c,u;const d=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=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let v;if(!g&&a.isNonNullable(p))v=p;else{const S=ht(this.video.buffered,this.video.currentTime*1e3),y=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(S/y,1);v=(c=Si(h.map(({track:T})=>T),{container:b,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:T})=>T===d))===null||l===void 0?void 0:l.track}))===null||c===void 0?void 0:c.id}return a.isNonNullable(v)?(u=h.find(({track:S})=>S.id===v))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===F.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(F.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,c)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=c.height:l===c)).subscribe(l=>{const c=ht(this.video.buffered,this.video.currentTime*1e3),u=Math.min(c/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ce(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:c,reused:u}=Xl(l);this.params.output.httpConnectionType$.next(c),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,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(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(){at(this.video).then(e=>{e||(this.videoState.setState(F.PAUSED),k(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 nr;(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"})(nr||(nr={}));var ge;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ge||(ge={}));var G;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(G||(G={}));var Mt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Mt||(Mt={}));var zs=(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 DS=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},CS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ro=CS?DS:window.requestIdleCallback;var os,ls;let eu=!1;try{eu=Ql()&&parseInt((ls=(os=navigator.userAgent.match(/Version\/(\d+)/))===null||os===void 0?void 0:os[1])!==null&&ls!==void 0?ls:"",10)<16}catch(i){console.error(i)}class OS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return Q(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return Q(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return Q(this,void 0,void 0,function*(){return new Promise(t=>{let r;eu&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask);try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var so=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const tu=new TextDecoder("ascii"),iu=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=tu.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},LS=i=>tu.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",xS=(i,e,t)=>{const r=iu(i),s=[];let n=0;const o=()=>{const b=r.contents.getUint32(n);return n+=4,b};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),d=o(),h=o(),f=o()&4294967295;let p=d/u*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+h;for(let b=0;b<f;b++){const g=o(),v=g>>>31,S=g<<1>>>1,y=o();if(o(),v!==0)throw new Error("Unsupported multilevel sidx");const E=y/u*1e3;s.push({status:G.NONE,time:{from:p,to:p+E},byte:{from:m,to:m+S-1}}),p+=E,m+=S}return s},BS=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=iu(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},MS={validateData:LS,parseInit:()=>null,getIndexRange:()=>{},parseSegments:xS,parseFeedableSegmentChunk:BS};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.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 w;(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"})(w||(w={}));const ao={[$.EBML]:{type:w.Master},[$.EBMLVersion]:{type:w.UnsignedInteger},[$.EBMLReadVersion]:{type:w.UnsignedInteger},[$.EBMLMaxIDLength]:{type:w.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[$.DocType]:{type:w.String},[$.DocTypeVersion]:{type:w.UnsignedInteger},[$.DocTypeReadVersion]:{type:w.UnsignedInteger},[$.Void]:{type:w.Binary},[$.Segment]:{type:w.Master},[$.SeekHead]:{type:w.Master},[$.Seek]:{type:w.Master},[$.SeekID]:{type:w.Binary},[$.SeekPosition]:{type:w.UnsignedInteger},[$.Info]:{type:w.Master},[$.TimestampScale]:{type:w.UnsignedInteger},[$.Duration]:{type:w.Float},[$.Tracks]:{type:w.Master},[$.Chapters]:{type:w.Master},[$.Cluster]:{type:w.Master},[$.Timestamp]:{type:w.UnsignedInteger},[$.SilentTracks]:{type:w.Master},[$.SilentTrackNumber]:{type:w.UnsignedInteger},[$.Position]:{type:w.UnsignedInteger},[$.PrevSize]:{type:w.UnsignedInteger},[$.SimpleBlock]:{type:w.Binary},[$.BlockGroup]:{type:w.Master},[$.EncryptedBlock]:{type:w.Binary},[$.Attachments]:{type:w.Master},[$.Tags]:{type:w.Master},[$.Cues]:{type:w.Master},[$.CuePoint]:{type:w.Master},[$.CueTime]:{type:w.UnsignedInteger},[$.CueTrackPositions]:{type:w.Master},[$.CueTrack]:{type:w.UnsignedInteger},[$.CueClusterPosition]:{type:w.UnsignedInteger},[$.CueRelativePosition]:{type:w.UnsignedInteger},[$.CueDuration]:{type:w.UnsignedInteger},[$.CueBlockNumber]:{type:w.UnsignedInteger},[$.CueCodecState]:{type:w.UnsignedInteger},[$.CueReference]:{type:w.Master},[$.CueRefTime]:{type:w.UnsignedInteger}},ru=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=or(i,t),s=r in ao,n=s?ao[r].type:w.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const c=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,d=or(c),h=u*Math.pow(2,(l-1)*8)+d,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},or=(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},Ge=(i,e)=>{switch(e){case w.SignedInteger:return i.getInt8(0);case w.UnsignedInteger:return or(i);case w.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(i);case w.UTF8:return new TextDecoder("utf-8").decode(i);case w.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case w.Master:return i;case w.Binary:return i;default:a.assertNever(e)}},yi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=ru(r);if(!e(s))return;s.type===w.Master&&yi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},VS=i=>{if(i.getUint32(0)!==$.EBML)return!1;let e,t,r;const s=ru(i);return yi(s.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=Ge(l,o):n===$.DocType?t=Ge(l,o):n===$.DocTypeReadVersion&&(r=Ge(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},su=[$.Info,$.SeekHead,$.Tracks,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],FS=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],US=i=>{let e,t,r,s,n=!1,o=!1,l=!1,c,u;return yi(i,({tag:d,type:h,value:f,valueSize:p})=>{if(d===$.SeekID){const m=Ge(f,h);u=or(m)}else d!==$.SeekPosition&&(u=void 0);return d===$.Segment?(e=f.byteOffset,t=f.byteOffset+p):d===$.Info?n=!0:d===$.SeekHead?o=!0:d===$.TimestampScale?r=Ge(f,h):d===$.Duration?s=Ge(f,h):d===$.SeekPosition&&u===$.Cues?c=Ge(f,h):n&&o&&su.includes(d)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:c}},jS=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},HS=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return yi(i,({tag:l,type:c,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&s(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=Ge(u,c));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=Ge(u,c));break;default:t&&su.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,c)=>{const{time:u,position:d}=l,h=n[c+1];return{status:G.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+d,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},GS=i=>{let e=0,t=!1;try{yi(i,r=>r.tag===$.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):FS.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},qS={validateData:VS,parseInit:US,getIndexRange:jS,parseSegments:HS,parseFeedableSegmentChunk:GS};class no{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:c=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ft,this.destroyAbortController=new ft,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return we(this,arguments,function*(){const d=this.representations.get(u);a.assertNonNullable(d,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${d.mime}; codecs="${d.codecs}"`),this.sourceBufferTaskQueue=new OS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),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(m=>{if(!this.sourceBuffer)return;const b=Math.min(this.bufferLimit,so(this.sourceBuffer.buffered)*.8);this.bufferLimit=b,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield D(this.loadInit(d,"high",!0));const h=this.initData.get(d.id),f=this.segments.get(d.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield D(void 0);let p=0;for(const m of f)m.time.from-p>0&&this.gaps.push({representation:d.id,from:p,to:m.time.from}),p=m.time.to;a.isNonNullable(d.duration)&&d.duration-p>0&&this.gaps.push({representation:d.id,from:p,to:d.duration}),yield yield D(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return we(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield D(void 0);this.switchingToRepresentationId=u;const d=this.representations.get(u);a.assertNonNullable(d,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield D(this.loadInit(d,"high",!1)):h instanceof Promise&&(yield yield D(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield D(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield D(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=c,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=r,r){case Mt.MP4:this.containerParser=MS;break;case Mt.WEBM:this.containerParser=qS;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.map(u=>[u.id,u])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new ft,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const d=ht(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&d>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&so(this.sourceBuffer.buffered)>=this.bufferLimit){const u=ht(this.sourceBuffer.buffered,e),d=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<d);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const d=Ue(l,0);d&&d.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===G.FED&&!l.length&&ht(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const c=Ue(r,-1);c&&c.status===G.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===c))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(c=>c.time.from<=e&&c.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const b=f<=r&&p>=r,g=f>r||b||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),S=this.preloadOnly&&f<=r+v||p<=r+v;return(h===G.NONE||h===G.PARTIALLY_EJECTED&&g&&S&&this.sourceBuffer&&!zs(this.sourceBuffer.buffered,r))&&g&&S});if(s===-1)return[];if(t!==ge.BYTE_RANGE)return e.slice(s,s+1);const n=e;let o=0,l=0;const c=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,d=this.preloadOnly?this.forwardBufferTarget:0;for(let h=s;h<n.length&&(o<=u||l<=d);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===G.NONE||f.status===G.PARTIALLY_EJECTED)c.push(f);else break}return c}loadSegments(e,t,r="auto"){return Q(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case ge.BYTE_RANGE:{s=t.segmentReference.url,n={from:Ue(e,0).byte.from,to:Ue(e,-1).byte.to};break}case ge.TEMPLATE:{const u=Ue(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=G.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:c}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(c,function(){return we(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield D(new Promise(d=>setTimeout(d,u)))})}.bind(this))(),c.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(s,{range:n,onProgress:(u,d)=>{if(!c.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,d,c)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:c,priority:r}).then(()=>this.failedDownloads=0,u=>{for(const d of this.activeSegments)e.includes(d.segment)&&this.abortSegment(d.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=ht((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=G.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===G.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=G.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},c=this.representations.get(t);if(!c)return;const u=c.segmentReference.type,d=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===ge.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:d;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const g=p?f.byte.from-r:0,v=p?f.byte.to-r:e.byteLength,S=g<s,y=v<=s;if(f.status===G.DOWNLOADING&&S&&y){f.status=G.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(h.loadedBytes=Math.min(m,s-g),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=G.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(A=>{if(n.aborted)o();else if(A)h.fedBytes+=T.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=ro(()=>Sr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return Q(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return we(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield D(new Promise(c=>setTimeout(c,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>{if(!l)return;const{dataView:c,segments:u}=l,d=c.buffer.slice(c.byteOffset,c.byteOffset+c.byteLength);this.initData.set(e.id,d),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return Q(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const c=u=>{var d;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(d=u.size)!==null&&d!==void 0?d:0:u.byte.to-u.byte.from;s+=h};for(const u of this.segments.values())for(const d of u){if(d.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;d.status===G.FED&&c(d)}if(l=isFinite(n)&&isFinite(o),!l){s=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const d of u){if(d.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||s>t)break;d.status===G.FED&&c(d)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const d=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===G.NONE&&Math.round(p.time.from)<=Math.round(d)&&Math.round(p.time.to)>=Math.round(h)){n=d,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&r){s=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const d of this.segments.values())for(const h of d)h.time.from>e+u&&h.status===G.FED&&c(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}detectGaps(e,t){if(this.sourceBuffer)for(const r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ro(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==G.FED&&n!==G.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.time.to),c=e.some(d=>d.from-t<=o&&d.to+t>=l),u=e.filter(d=>o>=d.from-t&&o<=d.to+t||l>=d.from-t&&l<=d.to+t);c||(u.length===1?s.status=G.PARTIALLY_EJECTED:s.status=G.NONE)}}}var Dt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Dt||(Dt={}));class YS{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new ft,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return we(this,arguments,function*(){let n=s;this.requestQuic&&(n=Bt(n));const o=yield yield D(xt(n,{signal:this.abortAllController.signal}).catch(ei));return o?(this.onHeadersReceived(o.headers),yield D(o.text())):yield D(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Dt.HEADER:Dt.PARAM,range:o,onProgress:l,priority:c="auto",signal:u,measureThroughput:d=!0}={}){var h,f,p,m;return we(this,arguments,function*(){let b=s;const g=new Headers;if(o)switch(n){case Dt.HEADER:{g.append("Range",`bytes=${o.from}-${o.to}`);break}case Dt.PARAM:{const P=new URL(b,location.href);P.searchParams.append("bytes",`${o.from}-${o.to}`),b=P.toString();break}default:a.assertNever(n)}this.requestQuic&&(b=Bt(b));let v=this.abortAllController.signal;if(u){const P=new ft;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{P.abort()}catch(C){ei(C)}})),this.abortAllController.signal.aborted||u.aborted)try{P.abort()}catch(C){ei(C)}v=P.signal}const S=a.now(),y=yield yield D(xt(b,{priority:c,headers:g,signal:v}).catch(ei)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-S),!y)return yield D(null);if(!y.ok||!y.body)return yield D(Promise.reject(new Error(`Fetch error ${y.status}: ${y.statusText}`)));this.onHeadersReceived(y.headers);const T=parseInt((f=y.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const P=yield yield D(y.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(P.byteLength,a.now()-E),l==null||l(new DataView(P),P.byteLength),yield D(P)}if(!l&&!d)return yield D(y.arrayBuffer());const[A,L]=y.body.tee(),R=A.getReader();d&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(L));let N=0;const V=new ArrayBuffer(T),I=new Uint8Array(V),_=new DataView(V);let H=!1;const J=P=>{H=!0,ei(P)},ee=a.abortable(v,function({done:P,value:C}){return we(this,arguments,function*(){if(N===0&&this.lastRequestFirstBytes$.next(a.now()-S),v.aborted)return yield D(void 0);!P&&C&&(I.set(C,N),N+=C.byteLength,l==null||l(_,N),yield yield D(R==null?void 0:R.read().then(ee,J)))})}.bind(this));return yield yield D(R==null?void 0:R.read().then(ee,J)),yield D(H?null:V)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return we(this,arguments,function*(){if(s.type!==ge.BYTE_RANGE)return yield D(null);const{from:c,to:u}=s.initRange;let d=c,h=u,f=!1,p,m;s.indexRange&&(p=s.indexRange.from,m=s.indexRange.to,f=u+1===p,f&&(d=Math.min(p,c),h=Math.max(m,u))),d=Math.min(d,0);const b=yield yield D(this.fetch(s.url,{range:{from:d,to:h},priority:o,measureThroughput:!1}));if(!b)return yield D(null);const g=new DataView(b,c-d,u-d+1);if(!n.validateData(g))throw new Error("Invalid media file");const v=n.parseInit(g),S=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(v);if(!S)throw new ReferenceError("No way to load representation index");let y;if(f)y=new DataView(b,S.from-d,S.to-S.from+1);else{const T=yield yield D(this.fetch(s.url,{range:S,priority:o,measureThroughput:!1}));if(!T)return yield D(null);y=new DataView(T)}const E=n.parseSegments(y,v,S);return yield D({dataView:new DataView(b),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return we(this,arguments,function*(){if(s.type!==ge.TEMPLATE)return yield D(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield D(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield D(null);const c=s.segments.map(u=>Object.assign(Object.assign({},u),{status:G.NONE,size:void 0}));return yield D({segments:c,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=Xl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return Q(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case ge.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case ge.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ei=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var zS=ze,WS=ui,QS=de,JS=QS("match"),KS=function(i){var e;return zS(i)&&((e=i[JS])!==void 0?!!e:WS(i)=="RegExp")},XS=pi,ZS=String,eg=function(i){if(XS(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return ZS(i)},tg=Qe,ig=function(){var i=tg(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},rg=be,sg=Me,ag=ur,ng=ig,oo=RegExp.prototype,og=function(i){var e=i.flags;return e===void 0&&!("flags"in oo)&&!sg(i,"flags")&&ag(oo,i)?rg(ng,i):e},Ta=Ee,lg=fr,ug=Math.floor,us=Ta("".charAt),dg=Ta("".replace),ds=Ta("".slice),cg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,hg=/\$([$&'`]|\d{1,2})/g,fg=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,c=hg;return s!==void 0&&(s=lg(s),c=cg),dg(n,c,function(u,d){var h;switch(us(d,0)){case"$":return"$";case"&":return i;case"`":return ds(e,0,t);case"'":return ds(e,o);case"<":h=s[ds(d,1,-1)];break;default:var f=+d;if(f===0)return u;if(f>l){var p=ug(f/10);return p===0?u:p<=l?r[p-1]===void 0?us(d,1):r[p-1]+us(d,1):u}h=r[f-1]}return h===void 0?"":h})},pg=Re,vg=be,$a=Ee,lo=Qs,mg=ae,bg=di,Sg=KS,wt=eg,gg=hr,yg=og,Eg=fg,Tg=de,$g=Tg("replace"),Pg=TypeError,au=$a("".indexOf),kg=$a("".replace),uo=$a("".slice),Ag=Math.max,co=function(i,e,t){return t>i.length?-1:e===""?t:au(i,e,t)};pg({target:"String",proto:!0},{replaceAll:function(e,t){var r=lo(this),s,n,o,l,c,u,d,h,f,p=0,m=0,b="";if(!bg(e)){if(s=Sg(e),s&&(n=wt(lo(yg(e))),!~au(n,"g")))throw Pg("`.replaceAll` does not allow non-global regexes");if(o=gg(e,$g),o)return vg(o,e,r,t);if(s)return kg(wt(r),e,t)}for(l=wt(r),c=wt(e),u=mg(t),u||(t=wt(t)),d=c.length,h=Ag(1,d),p=co(l,c,0);p!==-1;)f=u?wt(t(c,p,l)):Eg(c,l,p,[],void 0,t),b+=uo(l,m,p)+f,m=p+d,p=co(l,c,p+h);return m<l.length&&(b+=uo(l,m)),b}});var wg=Sa,_g=wg("String","replaceAll"),Rg=_g,Ig=Rg,Ng=Ig,Dg=Ng,ho=Dg;const fo=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const c=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(c)?0:c)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},cs=(i,e)=>{let t=i;t=ho(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=ho(t,o,(l,c)=>a.isNullable(n)?l:a.isNullable(c)?n:n.padStart(parseInt(c,10),"0"))}return t},Cg=(i,e)=>{var t,r,s,n,o,l,c,u,d,h,f,p,m,b,g,v,S,y,E,T,A,L,R,N,V,I,_,H,J,ee,P,C,z,te,se,he,Ne,Te,U,ne;const $e=new DOMParser().parseFromString(i,"application/xml"),Fe={video:[],audio:[],text:[]},nt=$e.children[0],et=nt.getElementsByTagName("Period")[0],yt=et.children;let De;const jt=nt.getAttribute("mediaPresentationDuration"),Pa=et.getAttribute("duration");if(jt)De=fo(jt);else if(Pa){const Pe=fo(Pa);a.isNonNullable(Pe)&&(De=Pe)}let hu=0;const Er=(r=(t=nt.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],fu=Er.includes(nr.WEBM_AS_IN_FFMPEG)||Er.includes(nr.WEBM_AS_IN_SPEC)?Mt.WEBM:Mt.MP4;for(const Pe of yt){const Ei=Pe.getAttribute("mimeType"),pu=Pe.getAttribute("codecs"),ka=(s=Pe.getAttribute("contentType"))!==null&&s!==void 0?s:Ei==null?void 0:Ei.split("/")[0],vu=(o=(n=Pe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Aa=Pe.querySelectorAll("Representation"),mu=Pe.querySelector("SegmentTemplate");if(ka===oe.TEXT){for(const ie of Aa){const tt=ie.getAttribute("id")||"",Ti=Pe.getAttribute("lang"),Et=(u=(c=(l=ie.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||c===void 0?void 0:c.trim())!==null&&u!==void 0?u:"",Tr=tt.includes("auto"),$r=new URL(Et,e).toString();Fe[oe.TEXT].push({id:tt,lang:Ti,kind:oe.TEXT,url:$r,isAuto:Tr})}continue}for(const ie of Aa){const tt=(d=ie.getAttribute("mimeType"))!==null&&d!==void 0?d:Ei,Ti=(f=(h=ie.getAttribute("codecs"))!==null&&h!==void 0?h:pu)!==null&&f!==void 0?f:"",Et=(m=(p=ie.getAttribute("contentType"))!==null&&p!==void 0?p:tt==null?void 0:tt.split("/")[0])!==null&&m!==void 0?m:ka,Tr=(g=(b=Pe.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&g!==void 0?g:[],$r=parseInt((v=ie.getAttribute("width"))!==null&&v!==void 0?v:"",10),wa=parseInt((S=ie.getAttribute("height"))!==null&&S!==void 0?S:"",10),_a=parseInt((y=ie.getAttribute("bandwidth"))!==null&&y!==void 0?y:"",10)/1e3,Ra=(E=ie.getAttribute("frameRate"))!==null&&E!==void 0?E:"",bu=(T=ie.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Su=Ra?ya(Ra):void 0,gu=(A=ie.getAttribute("id"))!==null&&A!==void 0?A:(hu++).toString(10),yu=Et==="video"?`${wa}p`:Et==="audio"?`${_a}Kbps`:Ti,Eu=`${gu}@${yu}`,Tu=(N=(R=(L=ie.querySelector("BaseURL"))===null||L===void 0?void 0:L.textContent)===null||R===void 0?void 0:R.trim())!==null&&N!==void 0?N:"",Ia=new URL(Tu,e).toString(),$u=[...Er,...vu,...Tr];let Pr;const Pu=ie.querySelector("SegmentBase"),ot=(V=ie.querySelector("SegmentTemplate"))!==null&&V!==void 0?V:mu;if(Pu){const Ht=(_=(I=ie.querySelector("SegmentBase Initialization"))===null||I===void 0?void 0:I.getAttribute("range"))!==null&&_!==void 0?_:"",[Gt,Ar]=Ht.split("-").map(lt=>parseInt(lt,10)),qt={from:Gt,to:Ar},Yt=(H=ie.querySelector("SegmentBase"))===null||H===void 0?void 0:H.getAttribute("indexRange"),[wr,$i]=Yt?Yt.split("-").map(lt=>parseInt(lt,10)):[],zt=Yt?{from:wr,to:$i}:void 0;Pr={type:ge.BYTE_RANGE,url:Ia,initRange:qt,indexRange:zt}}else if(ot){const Ht={representationId:(J=ie.getAttribute("id"))!==null&&J!==void 0?J:void 0,bandwidth:(ee=ie.getAttribute("bandwidth"))!==null&&ee!==void 0?ee:void 0},Gt=parseInt((P=ot.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),Ar=(C=ot.getAttribute("initialization"))!==null&&C!==void 0?C:"",qt=ot.getAttribute("media"),Yt=(te=parseInt((z=ot.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&te!==void 0?te:1,wr=cs(Ar,Ht);if(!qt)throw new ReferenceError("No media attribute in SegmentTemplate");const $i=(se=ot.querySelectorAll("SegmentTimeline S"))!==null&&se!==void 0?se:[],zt=[];if($i.length){let lt=Yt,ut=0;for(const Wt of $i){const Tt=parseInt((he=Wt.getAttribute("d"))!==null&&he!==void 0?he:"",10)*1e3,Qt=parseInt((Ne=Wt.getAttribute("r"))!==null&&Ne!==void 0?Ne:"",10)||0,Jt=(U=parseInt((Te=Wt.getAttribute("t"))!==null&&Te!==void 0?Te:"",10))!==null&&U!==void 0?U:void 0;for(let Na=0;Na<Qt+1;Na++){const ku=cs(qt,Object.assign(Object.assign({},Ht),{segmentNumber:lt.toString(10),segmentTime:Jt.toString(10)})),Au=Jt?Jt/Gt:ut;ut+=Tt/Gt;const wu=ut;lt++,zt.push({time:{from:Au,to:wu},url:ku})}}}else if(a.isNonNullable(De)){const ut=parseInt((ne=ot.getAttribute("duration"))!==null&&ne!==void 0?ne:"",10)/Gt*1e3,Wt=Math.ceil(De/ut);let Tt=0;for(let Qt=1;Qt<Wt;Qt++){const Jt=cs(qt,Object.assign(Object.assign({},Ht),{segmentNumber:Qt.toString(10),segmentTime:Tt.toString(10)}));zt.push({time:{from:Tt,to:Tt+ut},url:Jt}),Tt+=ut}}Pr={type:ge.TEMPLATE,baseUrl:Ia,initUrl:wr,segments:zt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Et||!tt)continue;const kr={video:oe.VIDEO,audio:oe.AUDIO,text:oe.TEXT}[Et];kr&&Fe[kr].push({id:Eu,kind:kr,segmentReference:Pr,profiles:$u,duration:De,bitrate:_a,mime:tt,codecs:Ti,width:$r,height:wa,fps:Su,quality:bu})}}return{duration:De,container:fu,representations:Fe}},Og=["timeupdate","progress","play","seeked","stalled","waiting"];var Se;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Se||(Se={}));let Lg=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new K(Se.NONE),this.currentVideoRepresentation$=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.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new ft,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return we(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Se.MANIFEST_READY);const s=yield yield D(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield D(void 0);let n;try{n=Cg(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield D(void 0);const o=({kind:l,mime:c,codecs:u})=>{var d,h,f;return Boolean(((d=t.canPlayType)===null||d===void 0?void 0:d.call(t,c))&&((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0?void 0:f.call(h,`${c}; codecs="${u}"`))||l===oe.TEXT)};this.manifest=Object.assign(Object.assign({},n),{representations:vi(Object.entries(n.representations).map(([l,c])=>[l,c.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(Se.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return we(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(Se.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new no(oe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new no(oe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));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.subscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:c})=>l&&c))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(c=>!c.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(c){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:c})}})),this.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield D(new Promise(l=>{var c;return(c=this.source)===null||c===void 0?void 0:c.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield D(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield D(this.videoBufferManager.startWith(t)),this.state$.setState(Se.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),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 YS({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Se.RUNNING),this.subscription.add(a.merge(...Og.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&&zs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return Q(this,void 0,void 0,function*(){const r={[oe.VIDEO]:this.videoBufferManager,[oe.AUDIO]:this.audioBufferManager,[oe.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let c;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?c=e:c=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),zs(this.element.buffered,c)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(c),(l=this.audioBufferManager)===null||l===void 0||l.maintain(c),this.element.currentTime=c/1e3}stop(){var e,t;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(Se.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.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}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const xg=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?gi(n):void 0)!==null&&o!==void 0?o:St({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},Bg=({id:i,bitrate:e})=>({id:i,bitrate:e}),Mg=({id:i,lang:e,url:t,isAuto:r})=>({id:i,url:t,isAuto:r,type:"internal",language:e}),Vg=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=Ue(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:Ue(i,-1)};class Fg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Ve,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new lS,this.textTracks=[],this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(l.state===B.Requested&&(o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&s!==X.STOPPED&&n!==exports.PlaybackState.STOPPED&&this.seek(l.position,l.forcePrecise),n===exports.PlaybackState.STOPPED){s!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(X.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(s){case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();return;case X.READY:n===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(s)}}},this.params=e;const{reused:t,video:r}=Ke(e.container);this.video=r,this.videoReused=t,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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Lg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=Xe(this.video),s=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,d)=>this.subscription.add(u.subscribe(d,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.isAudioAvailable$,e.isAudioAvailable$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(gt(this.video,t.isLooped,s)),this.subscription.add(Je(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(st(this.video,t.playbackRate,r.playbackRateState$,s)),n(sr(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var d;if(u===Se.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,v)=>v.bitrate-g.bitrate),p=Array.from(h.video).sort((g,v)=>v.bitrate-g.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const v=Bg(g);v&&this.audioTracks.push({track:v,representation:g})}for(const g of p){const v=xg(g);if(v){this.videoTracks.push({track:v,representation:g});const S=!this.params.tuning.isAudioDisabled&&Vg(f,p,g);S&&this.audioRepresentations.set(g.id,S)}}for(const g of m){const v=Mg(g);v&&this.textTracks.push({track:v,representation:g})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.output.availableTextTracks$.next(this.textTracks.map(({track:g})=>g));const b=this.selectVideoRepresentation();a.assertNonNullable(b),this.player.initRepresentations(b.id,(d=this.audioRepresentations.get(b.id))===null||d===void 0?void 0:d.id)}else u===Se.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),d=this.player.state$.getTransition();if(u!==Se.RUNNING||d||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(oe.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(oe.AUDIO,f.id).catch(o)}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var d;return u&&((d=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||d===void 0?void 0:d.track)})).subscribe(e.currentVideoTrack$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const c=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),c=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:v}})=>v===c))===null||e===void 0?void 0:e.track,d=this.params.output.currentVideoTrack$.getValue(),h=ht(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(r=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&r!==void 0?r:0,d&&(n=(s=this.audioRepresentations.get(d.id))===null||s===void 0?void 0:s.bitrate)!==null&&n!==void 0?n:0),b=Si(this.videoTracks.map(({track:v})=>v),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:p,current:d,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),g=l?b!=null?b:u:u!=null?u:b;return g&&((o=this.videoTracks.find(({track:v})=>v===g))===null||o===void 0?void 0:o.representation)}prepare(){return Q(this,void 0,void 0,function*(){this.player.initManifest(this.video,this.params.source.url)})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(this.video)}playIfAllowed(){at(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(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}))}}const Ug=5e3,Oe={};var j;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const ti=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class jg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(j.INITIALIZING),this.textTracksManager=new Ve,this.trackLevels=new Map,this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(s!==j.INITIALIZING)switch((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&this.seek(l.position),n){case exports.PlaybackState.STOPPED:switch(s){case j.STOPPED:break;case j.READY:case j.PLAYING:case j.PAUSED:this.stop();break;default:a.assertNever(s)}break;case exports.PlaybackState.READY:switch(s){case j.STOPPED:this.prepare();break;case j.READY:case j.PLAYING:case j.PAUSED:break;default:a.assertNever(s)}break;case exports.PlaybackState.PLAYING:switch(s){case j.PLAYING:break;case j.STOPPED:this.prepare();break;case j.READY:case j.PAUSED:this.playIfAllowed();break;default:a.assertNever(s)}break;case exports.PlaybackState.PAUSED:switch(s){case j.PAUSED:break;case j.STOPPED:this.prepare();break;case j.READY:this.videoState.setState(j.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case j.PLAYING:this.pause();break;default:a.assertNever(s)}break;default:a.assertNever(n)}};const{reused:t,video:r}=Ke(e.container);this.video=r,this.videoReused=t,this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Ug);Sr(import("hls.js").then(s=>{e||(Oe.Hls=s.default,Oe.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Oe.Hls,"hls.js not loaded"),this.hls=new Oe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(j.STOPPED)}subscribe(){a.assertNonNullable(Oe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=Xe(this.video),n=(u,d)=>this.subscription.add(u.subscribe(d,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.isAudioAvailable$,t.isAudioAvailable$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(gt(this.video,e.isLooped,r)),this.subscription.add(Je(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(st(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(ti(this.hls,Oe.Events.ERROR).subscribe(u=>{var d;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(d=u.err)===null||d===void 0?void 0:d.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===j.READY&&this.videoState.setState(j.READY),this.videoState.getState()===j.PLAYING&&this.playIfAllowed()},r)),n(ti(this.hls,Oe.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((d,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:b,height:g}=h,v=(p=gi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:St({width:b,height:g});if(!v)return d;const S=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,y={id:m.toString(),quality:v,bitrate:h.bitrate/1e3,size:{width:b,height:g},fps:S};return this.trackLevels.set(m,{track:y,level:h}),d.push(y),d},[]))),t.availableVideoTracks$),n(ti(this.hls,Oe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const d=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI,m=h.lang,b="internal",g=f.includes("auto");d.push({id:f,url:p,language:m,type:b,isAuto:g})}t.availableTextTracks$.next(d)}}),n(ti(this.hls,Oe.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ce(u))),t.hostname$),this.subscription.add(Be(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var d;return(d=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||d===void 0?void 0:d.track},l=ti(this.hls,Oe.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(Be(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var d;if(a.isNullable(u))return;const h=(d=this.trackLevels.get(u))===null||d===void 0?void 0:d.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,m=this.hls.levels[p];!m||h.bitrate>m.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const c=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(c.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(j.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return Q(this,void 0,void 0,function*(){this.videoState.startTransitionTo(j.PLAYING),(yield at(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState(j.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(j.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const po="X-Playback-Duration";var vo=i=>Q(void 0,void 0,void 0,function*(){const e=yield xt(i,{method:"HEAD"});return e.headers.has(po)?parseInt(e.headers.get(po),10):void 0});const Hg=i=>{let e=null;if(i.QUALITY&&(e=gi(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=St({width:t,height:r})}return e!=null?e:null},nu=(i,e=i)=>Q(void 0,void 0,void 0,function*(){var t;const n=(yield(yield xt(i)).text()).split(`
|
|
8
|
-
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const d=vi(u[1].split(",").map(v=>v.split("="))),h=(t=d.QUALITY)!==null&&t!==void 0?t:`stream-${d.BANDWIDTH}`,f=Hg(d);let p;d.BANDWIDTH&&(p=parseInt(d.BANDWIDTH,10)/1e3||void 0),!p&&d["AVERAGE-BANDWIDTH"]&&(p=parseInt(d["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=d["FRAME-RATE"]?parseFloat(d["FRAME-RATE"]):void 0;let b;if(d.RESOLUTION){const[v,S]=d.RESOLUTION.split("x").map(y=>parseInt(y,10));v&&S&&(b={width:v,height:S})}const g=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:g,bandwidth:p,size:b,fps:m})}return o});var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(q||(q={}));class Gg{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new K(q.STOPPED),this.textTracksManager=new Ve,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ga,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const o=this.videoState.getState(),l=this.params.desiredState.playbackState.getState(),c=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(l===exports.PlaybackState.STOPPED){o!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const f=this.params.desiredState.seekState.getState();if(o===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(u||d){const p=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(p),this.prepare(),f.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((c==null?void 0:c.to)!==exports.PlaybackState.PAUSED&&f.state===B.Requested){this.videoState.startTransitionTo(q.READY),this.seek(f.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(o){case q.READY:l===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):l===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:l===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.liveOffset.pause(),this.video.pause()):(c==null?void 0:c.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:l===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(c==null?void 0:c.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case q.CHANGING_MANIFEST:break;default:return a.assertNever(o)}},this.params=e;const{reused:r,video:s}=Ke(e.container);this.video=s,this.videoReused=r,this.params.output.element$.next(this.video);const n={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([n]),nu(Lt(this.params.source.url),this.params.source.url).then(o=>{this.manifests$.next([n,...o])},o=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:o})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",c=this.manifests$.getValue();if(!c)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),c.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=Xe(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(Je(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(st(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from===q.CHANGING_MANIFEST&&this.videoState.setState(c.to),l&&l.state===B.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,c,u;const d=(u=(c=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||c===void 0?void 0:c.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(d||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:c})=>this.params.output.liveTime$.next(l+c*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:c,quality:u,size:d,bandwidth:h,fps:f})=>({id:c,quality:u,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Lt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),vo(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{xt(t).then(o=>o.text()).then(o=>{var l;const c=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(c){const u=new URL(c,t).toString();vo(u).then(d=>{a.isNullable(d)||this.maxSeekBackTime$.next(d)})}})}catch(o){}}})}playIfAllowed(){at(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class qg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(W.STOPPED),this.textTracksManager=new Ve,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(o===exports.PlaybackState.STOPPED){n!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(n===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(c||u){const f=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(f);const{currentTime:p}=this.video;this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:p*1e3,forcePrecise:!0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested&&this.seek(h.position),n){case W.READY:o===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(n)}},this.params=e;const{reused:t,video:r}=Ke(e.container);this.video=r,this.videoReused=t,this.params.output.element$.next(this.video);const s={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),nu(this.params.source.url).then(n=>{this.manifests$.next([s,...n])},n=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:n})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",c=this.manifests$.getValue();if(!c)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),c.find(d=>d.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=Xe(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(Je(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(st(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),c=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}d&&this.params.desiredState.autoVideoTrackSwitching.setState(d.to),c&&c.from===W.CHANGING_MANIFEST&&this.videoState.setState(c.to),l.state===B.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:c,quality:u,size:d,bandwidth:h,fps:f})=>({id:c,quality:u,size:d,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){at(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class Yg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(Z.STOPPED),this.trackUrls={},this.textTracksManager=new Ve,this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===exports.PlaybackState.STOPPED){s!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.seekState.getState();if(s===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(c){const{currentTime:d}=this.video;this.prepare(),u.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:d*1e3,forcePrecise:!0});return}switch((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&u.state===B.Requested&&this.seek(u.position),s){case Z.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(s)}},this.params=e;const{reused:t,video:r}=Ke(e.container);this.video=r,this.videoReused=t,this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([s,n],o)=>{const l=o.toString(10);this.trackUrls[l]={track:{quality:s,id:l},url:n}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:s})=>s)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=Xe(this.video),n=(l,c)=>this.subscription.add(l.subscribe(c,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(Je(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(st(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY);const c=this.params.desiredState.videoTrack.getTransition();c&&a.isNonNullable(c.to)&&(this.params.desiredState.videoTrack.setState(c.to),this.params.output.currentVideoTrack$.next(this.trackUrls[c.to].track)),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(this.video)}prepare(){var e,t;const r=(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();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=Bt(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(ce(s))}playIfAllowed(){at(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const mo=["stun:videostun.mycdn.me:80"],zg=1e3,Wg=3,hs=()=>null;class Qg{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=hs,this.externalStopCallback=hs,this.externalErrorCallback=hs,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return Q(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return Q(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:mo}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return Q(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return Q(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return Q(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return Q(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),zg)}normalizeOptions(e={}){const t={stunServerList:mo,maxRetryNumber:Wg,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Y||(Y={}));class Jg{constructor(e){this.videoState=new K(Y.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition();if(n===exports.PlaybackState.STOPPED){s!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.videoTrack.getTransition();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(c){this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(s)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider");const{reused:t,video:r}=Ke(e.container);this.video=r,this.videoReused=t,this.liveStreamClient=new Qg(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),this.videoReused?Ie(this.video):Ze(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=Xe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.READY&&this.videoState.setState(Y.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Je(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Y.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Y.READY:break;case Y.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Y.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Y.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){at(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class bo{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var Kg=()=>{var i,e;const t=window.navigator;return t.userAgentData?((e=(i=t.userAgentData)===null||i===void 0?void 0:i.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},fs,ps,vs,ms,bs,Ss,Fi,gs,Ui,ys,ji,Es,Hi,Ts,Gi,$s,qi,Ps;const ou=Kg(),it=document.createElement("video"),Xg='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Zg='video/mp4; codecs="hev1.1.6.L93.B0"',lu='video/webm; codecs="vp09.00.10.08"',uu='video/webm; codecs="av01.0.00M.08"',ey='audio/mp4; codecs="mp4a.40.2"',ty='audio/webm; codecs="opus"',ke={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ps=(fs=window.SourceBuffer)===null||fs===void 0?void 0:fs.prototype)===null||ps===void 0?void 0:ps.appendBuffer)),hls:Boolean(((vs=it.canPlayType)===null||vs===void 0?void 0:vs.call(it,"application/x-mpegurl"))||((ms=it.canPlayType)===null||ms===void 0?void 0:ms.call(it,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},pe={mp4:Boolean((bs=it.canPlayType)===null||bs===void 0?void 0:bs.call(it,"video/mp4")),webm:Boolean((Ss=it.canPlayType)===null||Ss===void 0?void 0:Ss.call(it,"video/webm")),cmaf:!0},xe={h264:Boolean((gs=(Fi=window.MediaSource)===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||gs===void 0?void 0:gs.call(Fi,Xg)),h265:Boolean((ys=(Ui=window.MediaSource)===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||ys===void 0?void 0:ys.call(Ui,Zg)),vp9:Boolean((Es=(ji=window.MediaSource)===null||ji===void 0?void 0:ji.isTypeSupported)===null||Es===void 0?void 0:Es.call(ji,lu)),av1:Boolean((Ts=(Hi=window.MediaSource)===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||Ts===void 0?void 0:Ts.call(Hi,uu)),aac:Boolean(($s=(Gi=window.MediaSource)===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||$s===void 0?void 0:$s.call(Gi,ey)),opus:Boolean((Ps=(qi=window.MediaSource)===null||qi===void 0?void 0:qi.isTypeSupported)===null||Ps===void 0?void 0:Ps.call(qi,ty))},_t=(xe.h264||xe.h265)&&xe.aac;var je;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(je||(je={}));let ct;const iy=()=>Q(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:uu})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:lu})}))]);ct={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{iy()}catch(i){console.error(i)}const yr=ke.hls&&pe.mp4,ry=()=>Object.keys(xe).filter(i=>xe[i]),sy=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return ke.mse&&pe.mp4&&_t;case exports.VideoFormat.DASH_SEP:return ke.mse&&pe.mp4&&_t;case exports.VideoFormat.DASH_WEBM:return ke.mse&&pe.webm&&xe.vp9&&xe.opus;case exports.VideoFormat.DASH_WEBM_AV1:return ke.mse&&pe.webm&&xe.av1&&xe.opus;case exports.VideoFormat.DASH_LIVE:return ke.mse&&pe.mp4&&_t;case exports.VideoFormat.DASH_LIVE_CMAF:return ke.mse&&pe.mp4&&_t&&pe.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return ke.mse&&pe.mp4&&_t;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return yr||e&&ke.mse&&pe.mp4&&_t;case exports.VideoFormat.MPEG:return pe.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return ke.webrtc&&ke.ws&&xe.h264&&(pe.mp4||pe.webm);default:return a.assertNever(t)}}),ks=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case je.VP9:return[e,t];case je.AV1:return[t,e];case je.NONE:return[];case je.SMOOTH:return ct?ct[t].smooth?[t,e]:ct[e].smooth?[e,t]:[t,e]:[e,t];case je.POWER_EFFICIENT:return ct?ct[t].powerEfficient?[t,e]:ct[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(i)}return[e,t]},ay=(i=je.VP9)=>ou?[exports.VideoFormat.MPEG,...ks(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:yr?[...ks(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...ks(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],ny=()=>ou?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:yr?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],So=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var oy=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:d})=>`${u}-${d}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,c="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),c=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),c="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(c),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const go={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},ly={cacheDuration:12e4},uy={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},dy={maxPausedTime:3e4},yo={maxPausedTime:3e4};class cy{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=sy([...ny(),...ay(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:r}=this.params.tuning,s=r.length?[...t.filter(o=>!r.includes(o)),...t.filter(o=>r.includes(o))]:t;this.screenFormatsIterator=new bo(s);const n=[...So(!0),...So(!1)];this.chromecastFormatsIterator=new bo(n.filter(o=>a.isNonNullable(e.sources[o])))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;a.assertNonNullable(e,"No current provider"),this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),s=r.state!==B.None;this.params.desiredState.seekState.setState({state:B.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ve.SCREEN:return this.createScreenProvider(t);case ve.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new NS(Object.assign(Object.assign({},o),{source:l,config:ly}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new eo(Object.assign(Object.assign({},o),{source:l,format:e,config:yo})):new Fg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new eo(Object.assign(Object.assign({},o),{source:l,format:e,config:yo}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),yr||!this.params.tuning.useHlsJs?new qg(Object.assign(Object.assign({},o),{source:l})):new jg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Gg(Object.assign(Object.assign({},o),{source:l,config:dy}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Yg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new AS(Object.assign(Object.assign({},o),{source:l,config:uy}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Jg({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Cb({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ve.CHROMECAST:ve.SCREEN}chooseFormat(e){switch(e){case ve.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ve.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case ve.SCREEN:return this.screenFormatsIterator.next();case ve.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case ve.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case ve.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:r(e.url)})}return vi(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,oy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:go.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:s})=>s!==void 0))}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{if(this.current$.getValue().destination===ve.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=s.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=r<go.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}const Ws=(i,e,t)=>t*e+(1-t)*i,du=(i,e)=>i.reduce((t,r)=>t+r,0)/e,hy=(i,e,t,r)=>{let s=0,n=t;const o=du(i,e),l=e<r?e:r;for(let c=0;c<l;c++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class cu{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Le(`raw_${r}`),this.smoothedSeries$=new Le(`smoothed_${r}`),this.reportedSeries$=new Le(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class fy extends cu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ws(this.slow,e,this.params.emaAlphaSlow),this.fast=Ws(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class py extends cu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=du(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ws(this.emaSmoothed,e,this.params.emaAlpha);const r=hy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class Eo{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new fy({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new py({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}}const vy=5e3,To="one_video_throughput",$o="one_video_rtt",Ye=window.navigator.connection,Po=()=>{const i=Ye==null?void 0:Ye.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},ko=()=>{const i=Ye==null?void 0:Ye.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},Ao=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ni{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ni.load(To)||(e.useBrowserEstimation?Po():void 0)||vy,n=(r=(t=ni.load($o))!==null&&t!==void 0?t:e.useBrowserEstimation?ko():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Ao(s,n,e.rttPenaltyRequestSize)),this.throughput=Eo.getSmoothedValue(s,-1,e),this.rtt=Eo.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const c=Po();c&&this.throughput.next(c);const u=ko();a.isNonNullable(u)&&this.rtt.next(u)};Ye&&"onchange"in Ye&&this.subscription.add(a.fromEvent(Ye,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(To,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set($o,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>Ao(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),c=o-t,u=l-r;this.addRawSpeed(c,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},c=({done:u,value:d})=>Q(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):d&&(r+=d.byteLength,n+=d.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(c,l))});this.concurrentDownloads.add(e),t==null||t.read().then(c,l)}addRawSpeed(e,t,r=1){if(ni.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=a.safeStorage.get(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const wo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:je.VP9,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},my=i=>{const e={};for(const t of Object.keys(wo)){const r=wo[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?t==="configName"?e[t]=[...s,...r]:e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var by=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===B.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===B.None))),Sy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};class gy{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:B.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:aS},this.initLogs(),this.tuning=my(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new xu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ni(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const c=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(r)}`,d=`Exception calling ${u} (${c.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:d,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=Sy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new cy({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(r=>r.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===B.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===B.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:B.Applying})):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:l})=>l).sort((l,c)=>ir(l)?1:ir(c)?-1:Qi(c,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const c of o)c.fps&&(l[c.quality]=c.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(a.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(a.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$}).pipe(a.map(({isLive:o,position:l})=>o&&l>-a.ACTIVE_LIVE_VALID_DELAY),a.filterChanged()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(by({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||r.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,c;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(c=o==null?void 0:o.size)===null||c===void 0?void 0:c.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),c=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let d;u===exports.ChromecastState.CONNECTED?d=exports.Surface.SECOND_SCREEN:c?o?d=exports.Surface.PIP:l?d=exports.Surface.FULLSCREEN:d=exports.Surface.INLINE:d=exports.Surface.NONE,this.info.surface$.getValue()!==d&&this.info.surface$.next(d)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Si(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),sS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>rS(r)),this.providerContainer.current$.subscribe(({type:r})=>Bi("provider",r)),t.duration$.subscribe(r=>Bi("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Bi("tracks",r)),this.events.fatalError$.subscribe(new Le("fatalError")),this.events.managedError$.subscribe(new Le("managedError")),t.position$.subscribe(new Le("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Le("quality")),this.info.currentBuffer$.subscribe(new Le("buffer")),t.isBuffering$.subscribe(new Le("isBuffering"))].forEach(r=>this.subscription.add(r)),Bi("codecs",ry())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>Q(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}}const yy=`@vkontakte/videoplayer-core@${_o}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});exports.Player=gy;exports.SDK_VERSION=yy;exports.VERSION=_o;
|
|
6
|
+
"use strict";var Pu=Object.create;var wa=Object.defineProperty;var ku=Object.getOwnPropertyDescriptor;var Au=Object.getOwnPropertyNames;var wu=Object.getPrototypeOf,_u=Object.prototype.hasOwnProperty;var Ru=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Au(e))!_u.call(i,s)&&s!==t&&wa(i,s,{get:()=>e[s],enumerable:!(r=ku(e,s))||r.enumerable});return i};var _a=(i,e,t)=>(t=i!=null?Pu(wu(i)):{},Ru(e||!i||!i.__esModule?wa(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Iu=require("lodash/debounce.js");const Po="2.0.88";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 le;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(le||(le={}));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 Q(i,e,t,r){function s(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(r.next(c))}catch(h){o(h)}}function d(c){try{u(r.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):s(c.value).then(l,d)}u((r=r.apply(i,e||[])).next())})}function C(i){return this instanceof C?(this.v=i,this):new C(i)}function Ae(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(m,S){n.push([f,p,m,S])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof C?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 Nu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class Cu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Nu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(Du),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=r.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(s===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:s)}))}initializeCastApi(){var e;let t,r,s;try{t=cast.framework.CastContext.getInstance(),r=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:r,autoJoinPolicy:s}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Du=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 Ra=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},ge=function(i){try{return!!i()}catch(e){return!0}},Ou=ge,ir=!Ou(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),ko=ir,Ao=Function.prototype,gs=Ao.call,Lu=ko&&Ao.bind.bind(gs,gs),ye=ko?Lu:function(i){return function(){return gs.apply(i,arguments)}},wo=ye,xu=wo({}.toString),Bu=wo("".slice),ai=function(i){return Bu(xu(i),8,-1)},Mu=ye,Vu=ge,Fu=ai,Tr=Object,Uu=Mu("".split),ju=Vu(function(){return!Tr("z").propertyIsEnumerable(0)})?function(i){return Fu(i)=="String"?Uu(i,""):Tr(i)}:Tr,ni=function(i){return i==null},Hu=ni,Gu=TypeError,Hs=function(i){if(Hu(i))throw Gu("Can't call method on "+i);return i},qu=ju,Yu=Hs,oi=function(i){return qu(Yu(i))},zu=function(){},xt={},yi=function(i){return i&&i.Math==Math&&i},de=yi(typeof globalThis=="object"&&globalThis)||yi(typeof window=="object"&&window)||yi(typeof self=="object"&&self)||yi(typeof Ra=="object"&&Ra)||function(){return this}()||Function("return this")(),ys=typeof document=="object"&&document.all,Wu=typeof ys=="undefined"&&ys!==void 0,_o={all:ys,IS_HTMLDDA:Wu},Ro=_o,Qu=Ro.all,ae=Ro.IS_HTMLDDA?function(i){return typeof i=="function"||i===Qu}:function(i){return typeof i=="function"},Ju=de,Ku=ae,Ia=Ju.WeakMap,Xu=Ku(Ia)&&/native code/.test(String(Ia)),Na=ae,Io=_o,Zu=Io.all,Ge=Io.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Na(i)||i===Zu}:function(i){return typeof i=="object"?i!==null:Na(i)},ed=ge,qe=!ed(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ft={},td=de,Ca=Ge,Ts=td.document,id=Ca(Ts)&&Ca(Ts.createElement),Gs=function(i){return id?Ts.createElement(i):{}},rd=qe,sd=ge,ad=Gs,No=!rd&&!sd(function(){return Object.defineProperty(ad("div"),"a",{get:function(){return 7}}).a!=7}),nd=qe,od=ge,Co=nd&&od(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),ld=Ge,ud=String,dd=TypeError,Ye=function(i){if(ld(i))return i;throw dd(ud(i)+" is not an object")},cd=ir,Ti=Function.prototype.call,me=cd?Ti.bind(Ti):function(){return Ti.apply(Ti,arguments)},qs={},Er=qs,$r=de,hd=ae,Da=function(i){return hd(i)?i:void 0},pt=function(i,e){return arguments.length<2?Da(Er[i])||Da($r[i]):Er[i]&&Er[i][e]||$r[i]&&$r[i][e]},fd=ye,rr=fd({}.isPrototypeOf),sr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Do=de,Pr=sr,Oa=Do.process,La=Do.Deno,xa=Oa&&Oa.versions||La&&La.version,Ba=xa&&xa.v8,ke,Yi;Ba&&(ke=Ba.split("."),Yi=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Yi&&Pr&&(ke=Pr.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Pr.match(/Chrome\/(\d+)/),ke&&(Yi=+ke[1])));var Oo=Yi,Ma=Oo,pd=ge,Lo=!!Object.getOwnPropertySymbols&&!pd(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Ma&&Ma<41}),vd=Lo,xo=vd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",md=pt,bd=ae,Sd=rr,gd=xo,yd=Object,Bo=gd?function(i){return typeof i=="symbol"}:function(i){var e=md("Symbol");return bd(e)&&Sd(e.prototype,yd(i))},Td=String,ar=function(i){try{return Td(i)}catch(e){return"Object"}},Ed=ae,$d=ar,Pd=TypeError,vt=function(i){if(Ed(i))return i;throw Pd($d(i)+" is not a function")},kd=vt,Ad=ni,nr=function(i,e){var t=i[e];return Ad(t)?void 0:kd(t)},kr=me,Ar=ae,wr=Ge,wd=TypeError,_d=function(i,e){var t,r;if(e==="string"&&Ar(t=i.toString)&&!wr(r=kr(t,i))||Ar(t=i.valueOf)&&!wr(r=kr(t,i))||e!=="string"&&Ar(t=i.toString)&&!wr(r=kr(t,i)))return r;throw wd("Can't convert object to primitive value")},zi={},Rd={get exports(){return zi},set exports(i){zi=i}},Mo=!0,Va=de,Id=Object.defineProperty,Nd=function(i,e){try{Id(Va,i,{value:e,configurable:!0,writable:!0})}catch(t){Va[i]=e}return e},Cd=de,Dd=Nd,Fa="__core-js_shared__",Od=Cd[Fa]||Dd(Fa,{}),Ys=Od,Ua=Ys;(Rd.exports=function(i,e){return Ua[i]||(Ua[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var Ld=Hs,xd=Object,or=function(i){return xd(Ld(i))},Bd=ye,Md=or,Vd=Bd({}.hasOwnProperty),Le=Object.hasOwn||function(e,t){return Vd(Md(e),t)},Fd=ye,Ud=0,jd=Math.random(),Hd=Fd(1 .toString),Vo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Hd(++Ud+jd,36)},Gd=de,qd=zi,ja=Le,Yd=Vo,zd=Lo,Wd=xo,At=Gd.Symbol,_r=qd("wks"),Qd=Wd?At.for||At:At&&At.withoutSetter||Yd,ce=function(i){return ja(_r,i)||(_r[i]=zd&&ja(At,i)?At[i]:Qd("Symbol."+i)),_r[i]},Jd=me,Ha=Ge,Ga=Bo,Kd=nr,Xd=_d,Zd=ce,ec=TypeError,tc=Zd("toPrimitive"),ic=function(i,e){if(!Ha(i)||Ga(i))return i;var t=Kd(i,tc),r;if(t){if(e===void 0&&(e="default"),r=Jd(t,i,e),!Ha(r)||Ga(r))return r;throw ec("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xd(i,e)},rc=ic,sc=Bo,zs=function(i){var e=rc(i,"string");return sc(e)?e:e+""},ac=qe,nc=No,oc=Co,Ei=Ye,qa=zs,lc=TypeError,Rr=Object.defineProperty,uc=Object.getOwnPropertyDescriptor,Ir="enumerable",Nr="configurable",Cr="writable";ft.f=ac?oc?function(e,t,r){if(Ei(e),t=qa(t),Ei(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Cr in r&&!r[Cr]){var s=uc(e,t);s&&s[Cr]&&(e[t]=r.value,r={configurable:Nr in r?r[Nr]:s[Nr],enumerable:Ir in r?r[Ir]:s[Ir],writable:!1})}return Rr(e,t,r)}:Rr:function(e,t,r){if(Ei(e),t=qa(t),Ei(r),nc)try{return Rr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw lc("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var lr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},dc=qe,cc=ft,hc=lr,li=dc?function(i,e,t){return cc.f(i,e,hc(1,t))}:function(i,e,t){return i[e]=t,i},fc=zi,pc=Vo,Ya=fc("keys"),Ws=function(i){return Ya[i]||(Ya[i]=pc(i))},Qs={},vc=Xu,Fo=de,mc=Ge,bc=li,Dr=Le,Or=Ys,Sc=Ws,gc=Qs,za="Object already initialized",Es=Fo.TypeError,yc=Fo.WeakMap,Wi,ri,Qi,Tc=function(i){return Qi(i)?ri(i):Wi(i,{})},Ec=function(i){return function(e){var t;if(!mc(e)||(t=ri(e)).type!==i)throw Es("Incompatible receiver, "+i+" required");return t}};if(vc||Or.state){var Ne=Or.state||(Or.state=new yc);Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,Wi=function(i,e){if(Ne.has(i))throw Es(za);return e.facade=i,Ne.set(i,e),e},ri=function(i){return Ne.get(i)||{}},Qi=function(i){return Ne.has(i)}}else{var yt=Sc("state");gc[yt]=!0,Wi=function(i,e){if(Dr(i,yt))throw Es(za);return e.facade=i,bc(i,yt,e),e},ri=function(i){return Dr(i,yt)?i[yt]:{}},Qi=function(i){return Dr(i,yt)}}var Uo={set:Wi,get:ri,has:Qi,enforce:Tc,getterFor:Ec},$c=ir,jo=Function.prototype,Wa=jo.apply,Qa=jo.call,Ho=typeof Reflect=="object"&&Reflect.apply||($c?Qa.bind(Wa):function(){return Qa.apply(Wa,arguments)}),Pc=ai,kc=ye,Go=function(i){if(Pc(i)==="Function")return kc(i)},Js={},qo={},Yo={}.propertyIsEnumerable,zo=Object.getOwnPropertyDescriptor,Ac=zo&&!Yo.call({1:2},1);qo.f=Ac?function(e){var t=zo(this,e);return!!t&&t.enumerable}:Yo;var wc=qe,_c=me,Rc=qo,Ic=lr,Nc=oi,Cc=zs,Dc=Le,Oc=No,Ja=Object.getOwnPropertyDescriptor;Js.f=wc?Ja:function(e,t){if(e=Nc(e),t=Cc(t),Oc)try{return Ja(e,t)}catch(r){}if(Dc(e,t))return Ic(!_c(Rc.f,e,t),e[t])};var Lc=ge,xc=ae,Bc=/#|\.prototype\./,ui=function(i,e){var t=Vc[Mc(i)];return t==Uc?!0:t==Fc?!1:xc(e)?Lc(e):!!e},Mc=ui.normalize=function(i){return String(i).replace(Bc,".").toLowerCase()},Vc=ui.data={},Fc=ui.NATIVE="N",Uc=ui.POLYFILL="P",Wo=ui,Ka=Go,jc=vt,Hc=ir,Gc=Ka(Ka.bind),ur=function(i,e){return jc(i),e===void 0?i:Hc?Gc(i,e):function(){return i.apply(e,arguments)}},$i=de,qc=Ho,Yc=Go,zc=ae,Wc=Js.f,Qc=Wo,Tt=qs,Jc=ur,Et=li,Xa=Le,Kc=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return qc(i,this,arguments)};return e.prototype=i.prototype,e},_e=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?$i:s?$i[t]:($i[t]||{}).prototype,l=r?Tt:Tt[t]||Et(Tt,t,{})[t],d=l.prototype,u,c,h,f,p,m,S,g,v;for(f in e)u=Qc(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Xa(o,f),m=l[f],c&&(i.dontCallGetSet?(v=Wc(o,f),S=v&&v.value):S=o[f]),p=c&&S?S:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?g=Jc(p,$i):i.wrap&&c?g=Kc(p):n&&zc(p)?g=Yc(p):g=p,(i.sham||p&&p.sham||m&&m.sham)&&Et(g,"sham",!0),Et(l,f,g),n&&(h=t+"Prototype",Xa(Tt,h)||Et(Tt,h,{}),Et(Tt[h],f,p),i.real&&d&&(u||!d[f])&&Et(d,f,p)))},$s=qe,Xc=Le,Qo=Function.prototype,Zc=$s&&Object.getOwnPropertyDescriptor,Ks=Xc(Qo,"name"),eh=Ks&&function(){}.name==="something",th=Ks&&(!$s||$s&&Zc(Qo,"name").configurable),ih={EXISTS:Ks,PROPER:eh,CONFIGURABLE:th},Jo={},rh=Math.ceil,sh=Math.floor,ah=Math.trunc||function(e){var t=+e;return(t>0?sh:rh)(t)},nh=ah,Xs=function(i){var e=+i;return e!==e||e===0?0:nh(e)},oh=Xs,lh=Math.max,uh=Math.min,dh=function(i,e){var t=oh(i);return t<0?lh(t+e,0):uh(t,e)},ch=Xs,hh=Math.min,fh=function(i){return i>0?hh(ch(i),9007199254740991):0},ph=fh,Zs=function(i){return ph(i.length)},vh=oi,mh=dh,bh=Zs,Za=function(i){return function(e,t,r){var s=vh(e),n=bh(s),o=mh(r,n),l;if(i&&t!=t){for(;n>o;)if(l=s[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in s)&&s[o]===t)return i||o||0;return!i&&-1}},Sh={includes:Za(!0),indexOf:Za(!1)},gh=ye,Lr=Le,yh=oi,Th=Sh.indexOf,Eh=Qs,en=gh([].push),$h=function(i,e){var t=yh(i),r=0,s=[],n;for(n in t)!Lr(Eh,n)&&Lr(t,n)&&en(s,n);for(;e.length>r;)Lr(t,n=e[r++])&&(~Th(s,n)||en(s,n));return s},Ko=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ph=$h,kh=Ko,Ah=Object.keys||function(e){return Ph(e,kh)},wh=qe,_h=Co,Rh=ft,Ih=Ye,Nh=oi,Ch=Ah;Jo.f=wh&&!_h?Object.defineProperties:function(e,t){Ih(e);for(var r=Nh(t),s=Ch(t),n=s.length,o=0,l;n>o;)Rh.f(e,l=s[o++],r[l]);return e};var Dh=pt,Xo=Dh("document","documentElement"),Oh=Ye,Lh=Jo,tn=Ko,xh=Qs,Bh=Xo,Mh=Gs,Vh=Ws,rn=">",sn="<",Ps="prototype",ks="script",Zo=Vh("IE_PROTO"),xr=function(){},el=function(i){return sn+ks+rn+i+sn+"/"+ks+rn},an=function(i){i.write(el("")),i.close();var e=i.parentWindow.Object;return i=null,e},Fh=function(){var i=Mh("iframe"),e="java"+ks+":",t;return i.style.display="none",Bh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(el("document.F=Object")),t.close(),t.F},Pi,ji=function(){try{Pi=new ActiveXObject("htmlfile")}catch(e){}ji=typeof document!="undefined"?document.domain&&Pi?an(Pi):Fh():an(Pi);for(var i=tn.length;i--;)delete ji[Ps][tn[i]];return ji()};xh[Zo]=!0;var tl=Object.create||function(e,t){var r;return e!==null?(xr[Ps]=Oh(e),r=new xr,xr[Ps]=null,r[Zo]=e):r=ji(),t===void 0?r:Lh.f(r,t)},Uh=ge,jh=!Uh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Hh=Le,Gh=ae,qh=or,Yh=Ws,zh=jh,nn=Yh("IE_PROTO"),As=Object,Wh=As.prototype,il=zh?As.getPrototypeOf:function(i){var e=qh(i);if(Hh(e,nn))return e[nn];var t=e.constructor;return Gh(t)&&e instanceof t?t.prototype:e instanceof As?Wh:null},Qh=li,ea=function(i,e,t,r){return r&&r.enumerable?i[e]=t:Qh(i,e,t),i},Jh=ge,Kh=ae,Xh=Ge,Zh=tl,on=il,ef=ea,tf=ce,ws=tf("iterator"),rl=!1,je,Br,Mr;[].keys&&(Mr=[].keys(),"next"in Mr?(Br=on(on(Mr)),Br!==Object.prototype&&(je=Br)):rl=!0);var rf=!Xh(je)||Jh(function(){var i={};return je[ws].call(i)!==i});rf?je={}:je=Zh(je);Kh(je[ws])||ef(je,ws,function(){return this});var sl={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:rl},sf=ce,af=sf("toStringTag"),al={};al[af]="z";var ta=String(al)==="[object z]",nf=ta,of=ae,Hi=ai,lf=ce,uf=lf("toStringTag"),df=Object,cf=Hi(function(){return arguments}())=="Arguments",hf=function(i,e){try{return i[e]}catch(t){}},di=nf?Hi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=hf(e=df(i),uf))=="string"?t:cf?Hi(e):(r=Hi(e))=="Object"&&of(e.callee)?"Arguments":r},ff=ta,pf=di,vf=ff?{}.toString:function(){return"[object "+pf(this)+"]"},mf=ta,bf=ft.f,Sf=li,gf=Le,yf=vf,Tf=ce,ln=Tf("toStringTag"),ia=function(i,e,t,r){if(i){var s=t?i:i.prototype;gf(s,ln)||bf(s,ln,{configurable:!0,value:e}),r&&!mf&&Sf(s,"toString",yf)}},Ef=sl.IteratorPrototype,$f=tl,Pf=lr,kf=ia,Af=xt,wf=function(){return this},_f=function(i,e,t,r){var s=e+" Iterator";return i.prototype=$f(Ef,{next:Pf(+!r,t)}),kf(i,s,!1,!0),Af[s]=wf,i},Rf=_e,If=me,nl=ih,Nf=_f,Cf=il,Df=ia,un=ea,Of=ce,dn=xt,ol=sl,Lf=nl.PROPER;nl.CONFIGURABLE;ol.IteratorPrototype;var ki=ol.BUGGY_SAFARI_ITERATORS,Vr=Of("iterator"),cn="keys",Ai="values",hn="entries",xf=function(){return this},Bf=function(i,e,t,r,s,n,o){Nf(t,e,r);var l=function(v){if(v===s&&f)return f;if(!ki&&v in c)return c[v];switch(v){case cn:return function(){return new t(this,v)};case Ai:return function(){return new t(this,v)};case hn:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Vr]||c["@@iterator"]||s&&c[s],f=!ki&&h||l(s),p=e=="Array"&&c.entries||h,m,S,g;if(p&&(m=Cf(p.call(new i)),m!==Object.prototype&&m.next&&(Df(m,d,!0,!0),dn[d]=xf)),Lf&&s==Ai&&h&&h.name!==Ai&&(u=!0,f=function(){return If(h,this)}),s)if(S={values:l(Ai),keys:n?f:l(cn),entries:l(hn)},o)for(g in S)(ki||u||!(g in c))&&un(c,g,S[g]);else Rf({target:e,proto:!0,forced:ki||u},S);return o&&c[Vr]!==f&&un(c,Vr,f,{name:s}),dn[e]=f,S},Mf=function(i,e){return{value:i,done:e}},Vf=oi,ra=zu,fn=xt,ll=Uo,Ff=ft.f,Uf=Bf,wi=Mf,jf=Mo,Hf=qe,ul="Array Iterator",Gf=ll.set,qf=ll.getterFor(ul);Uf(Array,"Array",function(i,e){Gf(this,{type:ul,target:Vf(i),index:0,kind:e})},function(){var i=qf(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,wi(void 0,!0)):t=="keys"?wi(r,!1):t=="values"?wi(e[r],!1):wi([r,e[r]],!1)},"values");var pn=fn.Arguments=fn.Array;ra();ra();ra();if(!jf&&Hf&&pn.name!=="values")try{Ff(pn,"name",{value:"values"})}catch(i){}var Yf=ce,zf=xt,Wf=Yf("iterator"),Qf=Array.prototype,Jf=function(i){return i!==void 0&&(zf.Array===i||Qf[Wf]===i)},Kf=di,vn=nr,Xf=ni,Zf=xt,ep=ce,tp=ep("iterator"),dl=function(i){if(!Xf(i))return vn(i,tp)||vn(i,"@@iterator")||Zf[Kf(i)]},ip=me,rp=vt,sp=Ye,ap=ar,np=dl,op=TypeError,lp=function(i,e){var t=arguments.length<2?np(i):e;if(rp(t))return sp(ip(t,i));throw op(ap(i)+" is not iterable")},up=me,mn=Ye,dp=nr,cp=function(i,e,t){var r,s;mn(i);try{if(r=dp(i,"return"),!r){if(e==="throw")throw t;return t}r=up(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return mn(r),t},hp=ur,fp=me,pp=Ye,vp=ar,mp=Jf,bp=Zs,bn=rr,Sp=lp,gp=dl,Sn=cp,yp=TypeError,Gi=function(i,e){this.stopped=i,this.result=e},gn=Gi.prototype,sa=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=hp(e,r),u,c,h,f,p,m,S,g=function(b){return u&&Sn(u,"normal",b),new Gi(!0,b)},v=function(b){return s?(pp(b),l?d(b[0],b[1],g):d(b[0],b[1])):l?d(b,g):d(b)};if(n)u=i.iterator;else if(o)u=i;else{if(c=gp(i),!c)throw yp(vp(i)+" is not iterable");if(mp(c)){for(h=0,f=bp(i);f>h;h++)if(p=v(i[h]),p&&bn(gn,p))return p;return new Gi(!1)}u=Sp(i,c)}for(m=n?i.next:u.next;!(S=fp(m,u)).done;){try{p=v(S.value)}catch(b){Sn(u,"throw",b)}if(typeof p=="object"&&p&&bn(gn,p))return p}return new Gi(!1)},Tp=zs,Ep=ft,$p=lr,Pp=function(i,e,t){var r=Tp(e);r in i?Ep.f(i,r,$p(0,t)):i[r]=t},kp=_e,Ap=sa,wp=Pp;kp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Ap(e,function(r,s){wp(t,r,s)},{AS_ENTRIES:!0}),t}});var _p=qs,Rp=_p.Object.fromEntries,Ip={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},Np=Ip,Cp=de,Dp=di,Op=li,yn=xt,Lp=ce,Tn=Lp("toStringTag");for(var Fr in Np){var En=Cp[Fr],Ur=En&&En.prototype;Ur&&Dp(Ur)!==Tn&&Op(Ur,Tn,Fr),yn[Fr]=yn.Array}var xp=Rp,Bp=xp,Mp=Bp,Vp=Mp,ci=Vp,Fp=ai,dr=typeof process!="undefined"&&Fp(process)=="process",Up=pt,jp=ft,Hp=ce,Gp=qe,$n=Hp("species"),qp=function(i){var e=Up(i),t=jp.f;Gp&&e&&!e[$n]&&t(e,$n,{configurable:!0,get:function(){return this}})},Yp=rr,zp=TypeError,Wp=function(i,e){if(Yp(e,i))return i;throw zp("Incorrect invocation")},Qp=ye,Jp=ae,_s=Ys,Kp=Qp(Function.toString);Jp(_s.inspectSource)||(_s.inspectSource=function(i){return Kp(i)});var cl=_s.inspectSource,Xp=ye,Zp=ge,hl=ae,ev=di,tv=pt,iv=cl,fl=function(){},rv=[],pl=tv("Reflect","construct"),aa=/^\s*(?:class|function)\b/,sv=Xp(aa.exec),av=!aa.exec(fl),Wt=function(e){if(!hl(e))return!1;try{return pl(fl,rv,e),!0}catch(t){return!1}},vl=function(e){if(!hl(e))return!1;switch(ev(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return av||!!sv(aa,iv(e))}catch(t){return!0}};vl.sham=!0;var nv=!pl||Zp(function(){var i;return Wt(Wt.call)||!Wt(Object)||!Wt(function(){i=!0})||i})?vl:Wt,ov=nv,lv=ar,uv=TypeError,dv=function(i){if(ov(i))return i;throw uv(lv(i)+" is not a constructor")},Pn=Ye,cv=dv,hv=ni,fv=ce,pv=fv("species"),ml=function(i,e){var t=Pn(i).constructor,r;return t===void 0||hv(r=Pn(t)[pv])?e:cv(r)},vv=ye,mv=vv([].slice),bv=TypeError,Sv=function(i,e){if(i<e)throw bv("Not enough arguments");return i},gv=sr,bl=/(?:ipad|iphone|ipod).*applewebkit/i.test(gv),ve=de,yv=Ho,Tv=ur,kn=ae,Ev=Le,Sl=ge,An=Xo,$v=mv,wn=Gs,Pv=Sv,kv=bl,Av=dr,Rs=ve.setImmediate,Is=ve.clearImmediate,wv=ve.process,jr=ve.Dispatch,_v=ve.Function,_n=ve.MessageChannel,Rv=ve.String,Hr=0,Zt={},Rn="onreadystatechange",si,lt,Gr,qr;Sl(function(){si=ve.location});var na=function(i){if(Ev(Zt,i)){var e=Zt[i];delete Zt[i],e()}},Yr=function(i){return function(){na(i)}},In=function(i){na(i.data)},Nn=function(i){ve.postMessage(Rv(i),si.protocol+"//"+si.host)};(!Rs||!Is)&&(Rs=function(e){Pv(arguments.length,1);var t=kn(e)?e:_v(e),r=$v(arguments,1);return Zt[++Hr]=function(){yv(t,void 0,r)},lt(Hr),Hr},Is=function(e){delete Zt[e]},Av?lt=function(i){wv.nextTick(Yr(i))}:jr&&jr.now?lt=function(i){jr.now(Yr(i))}:_n&&!kv?(Gr=new _n,qr=Gr.port2,Gr.port1.onmessage=In,lt=Tv(qr.postMessage,qr)):ve.addEventListener&&kn(ve.postMessage)&&!ve.importScripts&&si&&si.protocol!=="file:"&&!Sl(Nn)?(lt=Nn,ve.addEventListener("message",In,!1)):Rn in wn("script")?lt=function(i){An.appendChild(wn("script"))[Rn]=function(){An.removeChild(this),na(i)}}:lt=function(i){setTimeout(Yr(i),0)});var gl={set:Rs,clear:Is},yl=function(){this.head=null,this.tail=null};yl.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 Tl=yl,Iv=sr,Nv=/ipad|iphone|ipod/i.test(Iv)&&typeof Pebble!="undefined",Cv=sr,Dv=/web0s(?!.*chrome)/i.test(Cv),ht=de,Cn=ur,Ov=Js.f,zr=gl.set,Lv=Tl,xv=bl,Bv=Nv,Mv=Dv,Wr=dr,Dn=ht.MutationObserver||ht.WebKitMutationObserver,On=ht.document,Ln=ht.process,_i=ht.Promise,xn=Ov(ht,"queueMicrotask"),Ns=xn&&xn.value,$t,Qr,Jr,Ri,Bn;if(!Ns){var Ii=new Lv,Ni=function(){var i,e;for(Wr&&(i=Ln.domain)&&i.exit();e=Ii.get();)try{e()}catch(t){throw Ii.head&&$t(),t}i&&i.enter()};!xv&&!Wr&&!Mv&&Dn&&On?(Qr=!0,Jr=On.createTextNode(""),new Dn(Ni).observe(Jr,{characterData:!0}),$t=function(){Jr.data=Qr=!Qr}):!Bv&&_i&&_i.resolve?(Ri=_i.resolve(void 0),Ri.constructor=_i,Bn=Cn(Ri.then,Ri),$t=function(){Bn(Ni)}):Wr?$t=function(){Ln.nextTick(Ni)}:(zr=Cn(zr,ht),$t=function(){zr(Ni)}),Ns=function(i){Ii.head||$t(),Ii.add(i)}}var Vv=Ns,Fv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},oa=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Uv=de,Bt=Uv.Promise,El=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",jv=El,Hv=dr,Gv=!jv&&!Hv&&typeof window=="object"&&typeof document=="object",qv=de,ei=Bt,Yv=ae,zv=Wo,Wv=cl,Qv=ce,Jv=Gv,Kv=El,Kr=Oo,Mn=ei&&ei.prototype,Xv=Qv("species"),Cs=!1,$l=Yv(qv.PromiseRejectionEvent),Zv=zv("Promise",function(){var i=Wv(ei),e=i!==String(ei);if(!e&&Kr===66||!(Mn.catch&&Mn.finally))return!0;if(!Kr||Kr<51||!/native code/.test(i)){var t=new ei(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Xv]=r,Cs=t.then(function(){})instanceof r,!Cs)return!0}return!e&&(Jv||Kv)&&!$l}),hi={CONSTRUCTOR:Zv,REJECTION_EVENT:$l,SUBCLASSING:Cs},Mt={},Vn=vt,em=TypeError,tm=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw em("Bad Promise constructor");e=r,t=s}),this.resolve=Vn(e),this.reject=Vn(t)};Mt.f=function(i){return new tm(i)};var im=_e,Ji=dr,et=de,fi=me,rm=ea,sm=ia,am=qp,nm=vt,Ds=ae,om=Ge,lm=Wp,um=ml,Pl=gl.set,la=Vv,dm=Fv,cm=oa,hm=Tl,kl=Uo,Os=Bt,ua=hi,Al=Mt,cr="Promise",wl=ua.CONSTRUCTOR,fm=ua.REJECTION_EVENT;ua.SUBCLASSING;var Xr=kl.getterFor(cr),pm=kl.set,vm=Os&&Os.prototype,wt=Os,Zr=vm,_l=et.TypeError,Ls=et.document,da=et.process,xs=Al.f,mm=xs,bm=!!(Ls&&Ls.createEvent&&et.dispatchEvent),Rl="unhandledrejection",Sm="rejectionhandled",Fn=0,Il=1,gm=2,ca=1,Nl=2,Ci,Un,ym,Cl=function(i){var e;return om(i)&&Ds(e=i.then)?e:!1},Dl=function(i,e){var t=e.value,r=e.state==Il,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===Nl&&Em(e),e.rejection=ca),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o(_l("Promise-chain cycle")):(u=Cl(d))?fi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Ol=function(i,e){i.notified||(i.notified=!0,la(function(){for(var t=i.reactions,r;r=t.get();)Dl(r,i);i.notified=!1,e&&!i.rejection&&Tm(i)}))},Ll=function(i,e,t){var r,s;bm?(r=Ls.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),et.dispatchEvent(r)):r={promise:e,reason:t},!fm&&(s=et["on"+i])?s(r):i===Rl&&dm("Unhandled promise rejection",t)},Tm=function(i){fi(Pl,et,function(){var e=i.facade,t=i.value,r=jn(i),s;if(r&&(s=cm(function(){Ji?da.emit("unhandledRejection",t,e):Ll(Rl,e,t)}),i.rejection=Ji||jn(i)?Nl:ca,s.error))throw s.value})},jn=function(i){return i.rejection!==ca&&!i.parent},Em=function(i){fi(Pl,et,function(){var e=i.facade;Ji?da.emit("rejectionHandled",e):Ll(Sm,e,i.value)})},_t=function(i,e,t){return function(r){i(e,r,t)}},It=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=gm,Ol(i,!0))},Bs=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw _l("Promise can't be resolved itself");var r=Cl(e);r?la(function(){var s={done:!1};try{fi(r,e,_t(Bs,s,i),_t(It,s,i))}catch(n){It(s,n,i)}}):(i.value=e,i.state=Il,Ol(i,!1))}catch(s){It({done:!1},s,i)}}};wl&&(wt=function(e){lm(this,Zr),nm(e),fi(Ci,this);var t=Xr(this);try{e(_t(Bs,t),_t(It,t))}catch(r){It(t,r)}},Zr=wt.prototype,Ci=function(e){pm(this,{type:cr,done:!1,notified:!1,parent:!1,reactions:new hm,rejection:!1,state:Fn,value:void 0})},Ci.prototype=rm(Zr,"then",function(e,t){var r=Xr(this),s=xs(um(this,wt));return r.parent=!0,s.ok=Ds(e)?e:!0,s.fail=Ds(t)&&t,s.domain=Ji?da.domain:void 0,r.state==Fn?r.reactions.add(s):la(function(){Dl(s,r)}),s.promise}),Un=function(){var i=new Ci,e=Xr(i);this.promise=i,this.resolve=_t(Bs,e),this.reject=_t(It,e)},Al.f=xs=function(i){return i===wt||i===ym?new Un(i):mm(i)});im({global:!0,constructor:!0,wrap:!0,forced:wl},{Promise:wt});sm(wt,cr,!1,!0);am(cr);var $m=ce,xl=$m("iterator"),Bl=!1;try{var Pm=0,Hn={next:function(){return{done:!!Pm++}},return:function(){Bl=!0}};Hn[xl]=function(){return this},Array.from(Hn,function(){throw 2})}catch(i){}var km=function(i,e){if(!e&&!Bl)return!1;var t=!1;try{var r={};r[xl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},Am=Bt,wm=km,_m=hi.CONSTRUCTOR,Ml=_m||!wm(function(i){Am.all(i).then(void 0,function(){})}),Rm=_e,Im=me,Nm=vt,Cm=Mt,Dm=oa,Om=sa,Lm=Ml;Rm({target:"Promise",stat:!0,forced:Lm},{all:function(e){var t=this,r=Cm.f(t),s=r.resolve,n=r.reject,o=Dm(function(){var l=Nm(t.resolve),d=[],u=0,c=1;Om(e,function(h){var f=u++,p=!1;c++,Im(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||s(d))},n)}),--c||s(d)});return o.error&&n(o.value),r.promise}});var xm=_e,Bm=hi.CONSTRUCTOR,Gn=Bt;Gn&&Gn.prototype;xm({target:"Promise",proto:!0,forced:Bm,real:!0},{catch:function(i){return this.then(void 0,i)}});var Mm=_e,Vm=me,Fm=vt,Um=Mt,jm=oa,Hm=sa,Gm=Ml;Mm({target:"Promise",stat:!0,forced:Gm},{race:function(e){var t=this,r=Um.f(t),s=r.reject,n=jm(function(){var o=Fm(t.resolve);Hm(e,function(l){Vm(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var qm=_e,Ym=me,zm=Mt,Wm=hi.CONSTRUCTOR;qm({target:"Promise",stat:!0,forced:Wm},{reject:function(e){var t=zm.f(this);return Ym(t.reject,void 0,e),t.promise}});var Qm=Ye,Jm=Ge,Km=Mt,Vl=function(i,e){if(Qm(i),Jm(e)&&e.constructor===i)return e;var t=Km.f(i),r=t.resolve;return r(e),t.promise},Xm=_e,Zm=pt,eb=Mo,tb=Bt,ib=hi.CONSTRUCTOR,rb=Vl,sb=Zm("Promise"),ab=!ib;Xm({target:"Promise",stat:!0,forced:eb},{resolve:function(e){return rb(ab&&this===sb?tb:this,e)}});var nb=_e,Ms=Bt,ob=ge,lb=pt,ub=ae,db=ml,qn=Vl,cb=Ms&&Ms.prototype,hb=!!Ms&&ob(function(){cb.finally.call({then:function(){}},function(){})});nb({target:"Promise",proto:!0,real:!0,forced:hb},{finally:function(i){var e=db(this,lb("Promise")),t=ub(i);return this.then(t?function(r){return qn(e,i()).then(function(){return r})}:i,t?function(r){return qn(e,i()).then(function(){throw r})}:i)}});var fb=pt,ha=fb,pb=ha,vb=pb("Promise","finally"),mb=vb,bb=mb,Sb=bb,gb=Sb,hr=gb,Nt;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Nt||(Nt={}));var Ct=(i,e=0,t=Nt.OFFSET_P)=>{switch(t){case Nt.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Nt.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i},k=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};class K{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}setState(e){const t=this.transition,r=this.state;this.transition=void 0,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:r,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,r=this.state;r===e||a.isNonNullable(t)&&t.to===e||(this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:r,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}const yb=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 Tb=5,Eb=5,$b=500,Yn=7e3;class Pb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new K(O.STOPPED),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){r!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&r!==O.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case O.PLAYING:case O.PAUSED:case O.READY:break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){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(r)}break}case exports.PlaybackState.PAUSED:{switch(r){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(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(yb(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce($b)).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)>Tb)&&s.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),s=>{this.logRemoteEvent(s),s.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),s=>{this.logRemoteEvent(s);const{remotePlayer:n}=this.params.connection,o=s.value,l=this.params.output.isBuffering$.getValue(),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<Eb&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({volume:s.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),s=>{this.logRemoteEvent(s),this.handleRemoteVolumeChange({muted:s.value})});const r=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(r,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(O.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(O.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:B.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PAUSED||e===O.PLAYING)&&(this.videoState.setState(O.PAUSED),k(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),k(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&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==O.STOPPED&&this.videoState.setState(O.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=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=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=r[e];a.assertNonNullable(c),s=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=r[e];a.assertNonNullable(c),s=Ct(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:s,n);l.contentUrl=s,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 r=this.params.desiredState.seekState.getState();return r.state===B.Applying||r.state===B.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Yn).subscribe(()=>n(`timeout(${Yn})`)))});hr(Promise.race([t,r]).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()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class zn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,r){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:r})}removeEventListener(e,t){if(!(e in this.listeners))return;const r=this.listeners[e];for(let s=0,n=r.length;s<n;s++)if(r[s].callback===t){r.splice(s,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const r=this.listeners[e.type].slice();for(let s=0,n=r.length;s<n;s++){const o=r[s];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Fl extends zn{constructor(){super(),this.listeners||zn.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 Ul=class{constructor(){Object.defineProperty(this,"signal",{value:new Fl,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(s){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let r=e;if(r===void 0)if(typeof document=="undefined")r=new Error("This operation was aborted"),r.name="AbortError";else try{r=new DOMException("signal is aborted without reason")}catch(s){r=new Error("This operation was aborted"),r.name="AbortError"}this.signal.reason=r,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Ul.prototype[Symbol.toStringTag]="AbortController",Fl.prototype[Symbol.toStringTag]="AbortSignal");function jl(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 kb(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!jl({fetch:e,Request:t,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||s)&&(n=function(u,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 fr=jl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Hl=fr?kb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Dt=fr?Hl.fetch:window.fetch;fr?Hl.Request:window.Request;const ct=fr?Ul:window.AbortController,Qt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ti{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:r}=e.request,s=(t=this.dashJsRequestQueue.get(r))!==null&&t!==void 0?t:[];s.push(e),this.dashJsRequestQueue.set(r,s)}executeNextRequests(){return Q(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const r=this.activeRequests.get(e);if(r){t.length&&this.onBigRequestProgress(r);const s=t[0];if(!s||!s.request.range)continue;const[n,o]=Qt(s.request);if(n>=r.from&&o<=r.to)continue;this.activeRequests.delete(e)}if(t.length){const s=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,s)}}})}abort(e){var t;if(e){const{request:r}=e,s=((t=this.dashJsRequestQueue.get(r.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(r.url);s&&n&&n.abortController.abort()}else for(const{abortController:r}of this.activeRequests.values())r.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const r=t.map(Qt),s=r[0][0];let n=r[0][1];for(let f=1;f<r.length&&n<this.params.minDataSize;f++){const p=r[f][1];p-s<=2*this.params.minDataSize&&(n=Math.max(n,p))}s===0?n=Math.max(n,s+this.params.minInitSize):n=Math.max(n,s+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${s}-${n}`);const l=o.toString(),d=new ct,u=d.signal,c={url:e,from:s,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var p,m;throw(m=(p=this.params).onError)===null||m===void 0||m.call(p,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return Dt(l,{signal:u}).then(f=>{var p,m,S;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[g,v]=f.body.tee();(m=(p=this.params).onDownloadStream)===null||m===void 0||m.call(p,v);const b=g.getReader(),E=parseInt((S=f.headers.get("Content-Length"))!==null&&S!==void 0?S:"",10)||n-s+1;c.data=new ArrayBuffer(E);const y=new Uint8Array(c.data),T=({done:A,value:L})=>Q(this,void 0,void 0,function*(){A?this.onBigRequestProgress(c):L&&(y.set(L,c.loaded),c.loaded+=L.byteLength,this.onBigRequestProgress(c),yield b==null?void 0:b.read().then(T,ti.suppressStreamErrors).catch(h))});b==null||b.read().then(T,ti.suppressStreamErrors).catch(h)},ti.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:r,loaded:s,data:n,response:o}){var l,d,u,c,h,f,p,m;if(!this.activeRequests.has(e)||!n)return;const S=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const g of S){const{request:v}=g,[b,E]=Qt(v),y=b>=t&&E<=t+s,T=t>=b&&t+s<E,A=n.slice(b-t,Math.min(E-t+1,s));if((y||T)&&(v.requestStartDate=(d=v.requestStartDate)!==null&&d!==void 0?d:new Date,v.firstByteDate=(u=v.firstByteDate)!==null&&u!==void 0?u:new Date,v.bytesLoaded=A.byteLength,v.bytesTotal=r-t),y){v.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(R=>R!==g)),(h=g.success)===null||h===void 0||h.call(g,A,"",e);const L=o?Array.from(o.headers.entries()).map(([R,N])=>`${R}: ${N}`).join(`\r
|
|
7
|
+
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(v,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,L,[])}else T&&((m=g.progress)===null||m===void 0||m.call(g,{loaded:s,total:r-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:r},s){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:a.ErrorCategory.NETWORK,message:"Download error",thrown:s}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=Qt(c.request);(h>=t&&h<r||f>t&&f<=r)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(s)))}if(this.activeRequests.delete(e),s)throw s}onBigRequestAbort({url:e,from:t,to:r}){var s,n;if(!this.activeRequests.has(e))return;const o=(s=this.dashJsRequestQueue.get(e))!==null&&s!==void 0?s:[];for(const l of o){const[d,u]=Qt(l.request);(d>=t&&d<r||u>t&&u<=r)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Ki{constructor(e,t,r){this.baseLoader=e,this.config=r,this.bigRequest=t,t.setMetrics(r.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Ki.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Ki.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Ab=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new Ki(s,e,r)}}),wb=(i,e)=>{const t=new ti(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return Ab(o,t)}}},!0),()=>t.destroy()};var _b=i=>{let e,t=!1,r=!1;i.on("playbackTimeUpdated",({timeToEnd:s})=>{r=s<=3,t&&r&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:s}=this,n=s.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&r&&(e==null||e())}}},!0)},Rb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,r=new a.ValueSubject(void 0),s=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,S;const g=ci(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(E=>E.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const E=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),y=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=y!=null?y:E*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const v=(m=g["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,b=(S={1:!0,0:!1}[g["x-reused"]])!==null&&S!==void 0?S:void 0;r.next(v),s.next(b)},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(...S){return d(this),p(...S)},f.progress=function(...S){return u(this),m(...S)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},Ot=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Ib=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Ot}),!0),Nb=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:r=>{if(r.request&&r.request.range){const[s,n]=r.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(r.request.url,location.href);o.searchParams.append("bytes",`${s}-${n}`),r.request.url=o.toString(),r.request.range=void 0}t(r)}}},!0)};const we=(i,e,t,{equal:r=(o,l)=>o===l,changed$:s,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(s),u=new a.Subscription;return s&&u.add(s.subscribe(c=>{const h=i.getState();r(c,h)&&i.setState(c)},n)),r(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},mt=(i,e,t)=>we(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),ze=(i,e,t,r)=>we(e,()=>({muted:i.muted,volume:i.volume}),s=>{a.isNonNullable(s)&&(i.muted=s.muted,i.volume=s.volume)},{equal:(s,n)=>s===n||(s==null?void 0:s.muted)===(n==null?void 0:n.muted)&&(s==null?void 0:s.volume)===(n==null?void 0:n.volume),changed$:t,onError:r}),tt=(i,e,t,r)=>we(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Cb=i=>["__",i.language,i.label].join("|"),Db=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class xe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,r){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const s=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(r.availableTextTracks$)),this.subscription.add(this.current$.subscribe(r.currentTextTrack$)),this.subscription.add(this.error$.subscribe(r.error$)),this.subscription.add(we(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:s})),this.subscription.add(we(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:s})),this.subscription.add(we(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(we(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var 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=r.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(r=>{var s;(s=r.track)===null||s===void 0||s.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const r of Array.from(e)){const s=r;a.isNonNullable(t.align)&&(s.align=t.align),a.isNonNullable(t.position)&&(s.position=t.position),a.isNonNullable(t.size)&&(s.size=t.size),a.isNonNullable(t.line)&&(s.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(xe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:Cb(e),n=this.externalTracks.has(s),o=s.includes("auto");return n?{id:s,type:"external",isAuto:o,language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",isAuto:o,language:t,label:r,url:this.internalTracks.get(s).url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t)))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&Db(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const fa=i=>{i.removeAttribute("src"),i.load()},Ob=i=>{try{i.pause(),i.playbackRate=0,fa(i),i.remove()}catch(e){console.error(e)}};class Lb{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 Vs=window.WeakMap?new WeakMap:new Lb,We=i=>{let e=i.querySelector("video");const t=Boolean(e);return e?fa(e):(e=document.createElement("video"),i.appendChild(e)),Vs.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Qe=i=>{const e=Vs.get(i);Vs.delete(i),e?fa(i):Ob(i)};class pa{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 Gl=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},Wn=i=>{const e=Gl(i);return Boolean(e&&e.fullscreenElement&&e.fullscreenElement===i)},xb=i=>{const e=Gl(i);return Boolean(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Fs=3;class Bb{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,r=this._source.buffered.length;t<r;t++){let s=this._source.buffered.start(t);const n=this._source.buffered.end(t);s>e&&s-e<Fs&&(s=e),this._buffer.push({from:s,to:n,i:t})}return this._buffer.sort(function(t,r){return t.from-r.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const r=this.getNext(e);if(r&&r.from-e.to<(t||Fs))return r}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,r){this._buffer.forEach(({from:s,to:n})=>{const o=s>=e&&s<t,l=n>=e&&n<t;o&&l||(o?r(t,n):l?r(s,e):s<e&&n>t?(r(t,n),r(s,e)):r(s,n))})}destroy(){this._buffer=[]}}var ql=(i,e,t=Fs)=>{let r=0,s=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(r=o,s=l,!t)return{from:r,to:s};for(let d=n-1;d>=0;d--)i.end(d)+t>=r&&(r=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=s&&(s=i.end(d))}}return{from:r,to:s}};const Mb=1e3,Vb=i=>{const e=a.getCurrentBrowser();return e.browser===a.CurrentClientBrowser.Chrome&&e.device===a.CurrentClientDevice.Android?!0:i.webkitAudioDecodedByteCount!==void 0?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!==void 0?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0},Je=i=>{const e=y=>a.fromEvent(i,y).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(y=>a.fromEvent(i,y))).pipe(a.map(y=>y.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>ql(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,"playing").pipe(a.debounce(Mb),a.map(()=>Vb(i))),d=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),u=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),c=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var y;const T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(y=i.error)!==null&&y!==void 0?y:void 0}})),h=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),f=new a.Subject,p=.3;let m;h.subscribe(y=>{i.loop&&a.isNonNullable(m)&&a.isNonNullable(y)&&m>=i.duration-p&&y<=p&&f.next(m),m=y});const S=a.fromEvent(i,"enterpictureinpicture"),g=a.fromEvent(i,"leavepictureinpicture"),v=new a.ValueSubject(xb(i));S.subscribe(()=>v.next(!0)),g.subscribe(()=>v.next(!1));const b=new a.ValueSubject(Wn(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>Wn(i))).subscribe(b),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:f,error$:c,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:h,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:d,isAudioAvailable$:l,playbackRateState$:u,inPiP$:v,inFullscreen$:b}},va=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Fb=_e,Ub=or,jb=Zs,Hb=Xs;Fb({target:"Array",proto:!0},{at:function(e){var t=Ub(this),r=jb(t),s=Hb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Gb=ha,qb=Gb("Array","at"),Yb=qb,zb=Yb,Wb=zb,Qb=Wb,Me=Qb;let ma=!1,Fe={};const Jb=i=>{ma=i},Kb=()=>{Fe={}},Xb=i=>{i(Fe)},Di=(i,e)=>{var t;ma&&(Fe.meta=(t=Fe.meta)!==null&&t!==void 0?t:{},Fe.meta[i]=e)};class De{constructor(e){this.name=e}next(e){var t,r;if(!ma)return;Fe.series=(t=Fe.series)!==null&&t!==void 0?t:{};const s=(r=Fe.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Fe.series[this.name]=s}}const Zb=new De("best_bitrate"),eS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class tS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const pi=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,p;const m=r.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,S=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*r.containerSizeFactor,height:e.height*m*r.containerSizeFactor},g=S&&a.videoSizeToQuality(S),v=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,b=i.filter(I=>!a.isInvariantQuality(I.quality)).sort((I,_)=>a.isHigher(I.quality,_.quality)?-1:1),E=(h=Me(b,-1))===null||h===void 0?void 0:h.quality,y=(f=Me(b,0))===null||f===void 0?void 0:f.quality,T=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&a.isLower(s.max,s.min)||a.isNonNullable(s.min)&&y&&a.isHigher(s.min,y)||a.isNonNullable(s.max)&&E&&a.isLower(s.max,E),A=v*eS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),R=b.filter(I=>{const _=g?a.isLower(I.quality,g):!0,H=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(I.bitrate)?t-n>=I.bitrate*A:!0,J=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&a.isHigher(I.quality,d.quality),re=T||(a.isNullable(s.max)||a.isLowerOrEqual(I.quality,s.max))&&(a.isNullable(s.min)||a.isHigherOrEqual(I.quality,s.min));return _&&H&&!J&&re})[0];R&&R.bitrate&&Zb.next(R.bitrate);const N=(p=R!=null?R:b[Math.ceil((b.length-1)/2)])!==null&&p!==void 0?p:i[0],V=N&&u&&u.history[N.id]&&a.now()-u.history[N.id]<=r.trackCooldown&&(!u.last||N.id!==u.last.id);if(N!=null&&N.id&&u&&!V&&u.recordSelection(N),V&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(N),N};var he=i=>new URL(i).hostname;const iS=300,Xi=(i,e=iS)=>new a.Observable(t=>{const{width:r,height:s}=i.getBoundingClientRect();if(t.next({width:r,height:s}),!window.ResizeObserver)return;const n=new ResizeObserver(Iu(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()}),rS=5e3,Jt={};var M;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const ie=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class Qn{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(M.DOWNLOADING_LIB),this.textTracksManager=new xe,this.videoTracks=[],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 pa,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===M.DOWNLOADING_LIB||t===M.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&t!==M.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case M.STOPPED:break;case M.PLAYING:case M.PAUSED:case M.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case M.STOPPED:this.prepare();break;case M.PLAYING:case M.PAUSED:case M.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case M.PLAYING:break;case M.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 M.READY:this.play();break;case M.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case M.PLAYING:this.pause(),this.liveOffset.pause();break;case M.PAUSED:break;case M.READY:this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=We(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(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=s=>{var n;e||this.params.output.error$.next({id:s==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=s==null?void 0:s.toString)===null||n===void 0?void 0:n.call(s)}`,thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),rS);hr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Jt.MediaPlayer=s.MediaPlayer,Jt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Jt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Jt.Debug,"dashjs not loaded"),this.player=Jt.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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?va(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_WEBM_AV1)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=wb(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&Nb(this.player),_b(this.player),this.params.tuning.requestQuick&&Ib(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},s=(v,b)=>this.subscription.add(v.subscribe(b,r));s(Xi(this.video),this.elementSize$),s(ie(this.player,"error").pipe(a.map(v=>{const b=typeof v.error=="object"?v.error.code:v.error,E=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:E}})),e.error$),s(ie(this.player,"playbackError").pipe(a.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=ie(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({newQuality:v})=>{var b;return(b=this.videoTracks.find(({bitrateInfo:E})=>E.qualityIndex===v))===null||b===void 0?void 0:b.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:v})=>v===M.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(we(t.videoTrack,()=>{var v,b;const E=this.player.getQualityFor("video");return(b=(v=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===E))===null||v===void 0?void 0:v.track)===null||b===void 0?void 0:b.id},v=>{var b;if(a.isNullable(v))return;const E=(b=this.videoTracks.find(({track:y})=>y.id===v))===null||b===void 0?void 0:b.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:r}))},r)),this.subscription.add(we(t.autoVideoTrackSwitching,()=>{var v,b,E;return(E=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||E===void 0?void 0:E.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:r})),s(ie(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),s(ie(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:b}})=>{var E,y;const T=this.player.getDashMetrics(),A=T.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),L=(E=T.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,R=(y={1:!0,0:!1}[A])!==null&&y!==void 0?y:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(R),e.hostname$.next(he(b))}),s(ie(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:E}}})=>{this.isLive$.next(b),this.availableFrom$.next(E.getTime()),b||e.duration$.next(v),this.videoTracks=[];const y=this.player.getQualityFor("video");let T;for(const A of this.player.getBitrateInfoListFor("video")){const L=A.qualityIndex.toString(10),R=a.videoSizeToQuality(A),N=A.bitrate/1e3,V={width:A.width,height:A.height},I=this.frameRatesByFrameHeight[A.height];if(R){const _={id:L,quality:R,bitrate:N,size:V,fps:I};this.videoTracks.push({track:_,bitrateInfo:A}),A.qualityIndex===y&&(T=_)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:A})=>A)),T&&e.currentVideoTrack$.next(T),this.videoState.setState(M.STREAM_INITIALIZED),this.videoState.startTransitionTo(M.READY)}),s(ie(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),E=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,b)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=pi(this.videoTracks.map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),E=this.videoTracks.find(({track:y})=>y===b);E!=null&&E.bitrateInfo&&this.player.setQualityFor("video",E==null?void 0:E.bitrateInfo.qualityIndex,!1)}),s(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=ie(this.player,"playbackTimeUpdated").pipe(a.map(({time:v})=>v!=null?v:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:b})=>this.params.output.liveTime$.next(v+b*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(ie(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(ie(this.player,"playbackEnded"),e.endedEvent$),s(ie(this.player,"playbackProgress").pipe(a.map(()=>ql(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(ie(this.player,"playbackPlaying"),()=>{this.videoState.setState(M.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(ie(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(ie(this.player,"playbackPaused"),()=>{this.videoState.setState(M.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),s(ie(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===M.READY&&this.videoState.setState(M.READY)}),s(this.isLive$,e.isLive$),s(Xi(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));s(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Rb(this.player);s(c,this.params.output.httpConnectionType$),s(h,this.params.output.httpConnectionReused$),s(d,this.maxSeekBackTime$),s(u.pipe(a.once()),e.firstBytesEvent$),s(ie(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&s(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(v=>v<60))}),({isLive:v,isShort:b})=>{const E=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),s(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(ie(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(ie(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),s(ie(this.player,"manifestLoaded"),v=>{var b,E,y,T,A,L,R;if(!((E=(b=v.data)===null||b===void 0?void 0:b.Period)===null||E===void 0)&&E.AdaptationSet){const N=[];for(const V of(T=(y=v.data)===null||y===void 0?void 0:y.Period)===null||T===void 0?void 0:T.AdaptationSet)if(V.contentType==="text"){const I=(A=V.Representation)===null||A===void 0?void 0:A.id,_=new URL((L=V.Representation)===null||L===void 0?void 0:L.BaseURL,(R=v.data)===null||R===void 0?void 0:R.baseUri).toString(),H="internal",J=V.lang;N.push({id:I,url:_,type:H,language:J})}t.internalTextTracks.startTransitionTo(N)}}),this.subscription.add(mt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:S,inFullscreen$:g}=Je(this.video);this.subscription.add(ze(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(tt(this.video,t.playbackRate,m,r)),this.subscription.add(S.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(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(M.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,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=Ct(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Nt.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(M.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(M.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(r){}Qe(this.video),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var vi=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 Jn=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 it=i=>Q(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!Jn(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return Jn(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});function ue(){return a.now()}function Yl(i){return ue()-i}function Kn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),r=/^([a-z]+:)?\/\//i,s=o=>r.test(o);return{resolve:(o,l,d=!1)=>{s(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 sS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function qi(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,S=2e3,g=()=>{if(d)return;a.assertNonNullable(c);const _=Yl(c);let H;if(_<S){H=S-_,setTimeout(g,H);return}S*=2,S>m&&(S=m),o&&o.abort(),o=new s,A()};const v=_=>(n=_,I),b=_=>(h=_,I),E=()=>(p="json",I),y=()=>{if(!d){if(--u>=0){g(),r&&r();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,I),A=()=>{c=ue(),o=new s,o.open("get",i);let _=0,H,J=0;const re=()=>(a.assertNonNullable(c),Math.max(c,Math.max(H||0,J||0)));if(n&&o.addEventListener("progress",P=>{const D=ue();n.updateChunk&&P.loaded>_&&(n.updateChunk(re(),P.loaded-_),_=P.loaded,H=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>y())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const P=o.status;if(P>=200&&P<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(re(),D)}h&&h(),o&&e(o.response)}else y()}),o.addEventListener("error",()=>{y()}),f){const P=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(J=ue(),o.removeEventListener("readystatechange",P))};o.addEventListener("readystatechange",P)}return o.responseType=p,o.send(),I},I={withBitrateReporting:v,withParallel:T,withJSONResponse:E,withRetryCount:_=>(u=_,I),withRetryInterval:(_,H)=>(a.isNonNullable(_)&&(S=_),a.isNonNullable(H)&&(m=H),I),withTimeout:_=>(l=_,I),withFinally:b,send:A,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const aS=100,nS=2e3,oS=500;let lS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-oS;if(t-e>nS){let r=0,s=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)r+=n.end-n.start,s+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;r+=o;const d=n.bytes*o/l;s+=d,n.start=t,n.bytes-=d}}}if(s>0&&r>0){const n=s*8/(r/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(r)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,r){return this.intervals.push(this._createInterval(e,t,r)),this._joinIntervals(),this.intervals.length>aS&&(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 uS{constructor(e,t,r,s,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=r,this.MAX_PARALLEL_REQUESTS=s,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const r=ue(),s=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=ue()-r,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=qi(t,n,()=>s("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=ue()}_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=ue();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Oi=1e4,Li=3,dS=300,cS=2e3,hS=6e4,fS=10,pS=1,vS=500;class mS{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 lS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Kn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let r=0;r<this.manifest.length;++r)if(t=this.manifest[r],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Kn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{sS(s,"progress",()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new uS(Li,Oi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const y=n&&(!c||c===this.rep);return y||t("Not running!"),y},f=(y,T,A)=>{d&&d.abort(),d=qi(this.urlResolver.resolve(y,!1),T,A,()=>this._retryCallback()).withTimeout(Oi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Li).withFinally(()=>{d=null}).send()},p=(y,T,A)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(y,!1),T,A,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=y=>{const T=r.playbackRate;r.playbackRate!==y&&(t(`Playback rate switch: ${T}=>${y}`),r.playbackRate=y)},S=y=>{this.lowLatency=y,t(`lowLatency changed to ${y}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let y=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const A=ue()-1e4;let L=0;for(let N=0;N<this.bufferStates.length;N++){const V=this.bufferStates[N];y=Math.min(y,V.buf),V.ts<A&&L++}this.bufferStates.splice(0,L),t(`update playback rate; minBuffer=${y} drop=${L} jitter=${this.sourceJitter}`);let R=y-pS;this.sourceJitter>=0?R-=this.sourceJitter/2:this.sourceJitter-=1,R>3?m(1.15):R>1?m(1.1):R>.3?m(1.05):m(1)}},v=y=>{let T;const A=()=>T&&T.start?T.start.length:0,L=P=>T.start[P]/1e3,R=P=>T.dur[P]/1e3,N=P=>T.fragIndex+P,V=(P,D)=>({chunkIdx:N(P),startTS:L(P),dur:R(P),discontinuity:D}),I=()=>{let P=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=D;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let se=T.dur.length-1;for(;se>=0&&(ee-=T.dur[se],!(ee<=0));--se);P=Math.min(se,T.dur.length-1-z),P=Math.max(P,0)}return V(P,!0)},_=P=>{const D=A();if(!(D<=0)){if(a.isNonNullable(P)){for(let z=0;z<D;z++)if(L(z)>P)return V(z)}return I()}},H=P=>{const D=A(),z=P?P.chunkIdx+1:0,ee=z-T.fragIndex;if(!(D<=0)){if(!P||ee<0||ee-D>fS)return t(`Resync: offset=${ee} bChunks=${D} chunk=`+JSON.stringify(P)),I();if(!(ee>=D))return V(z-T.fragIndex,!1)}},J=(P,D,z)=>{u&&u.abort(),u=qi(this.urlResolver.resolve(P,!0,this.lowLatency),D,z,()=>this._retryCallback()).withTimeout(Oi).withRetryCount(Li).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,D)=>{J(y,z=>{if(!h())return;T=z;const ee=Boolean(T.lowLatency);ee!==this.lowLatency&&S(ee);let se=0;for(let fe=0;fe<T.dur.length;++fe)se+=T.dur[fe];se>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/T.dur.length)),s({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,P(_(D))},()=>this._handleNetworkError())},nextChunk:H}},b=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:y=>{const{videoElement:T,logger:A}=this.params;let L=v(e.jidxUrl),R,N,V,I,_=0,H,J,re;const P=()=>{H&&(clearTimeout(H),H=void 0);const U=Math.max(vS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ne=_+U,Te=ue(),Ee=Math.min(1e4,ne-Te);_=Te;const Be=()=>{u||h()&&L.seek(()=>{h()&&(_=ue(),D(),P())})};Ee>0?H=window.setTimeout(()=>{this.paused?P():Be()},Ee):Be()},D=()=>{let U;for(;U=L.nextChunk(I);)I=U,Re(U);const ne=L.nextChunk(V);if(ne){if(V&&ne.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?P():(b(),this._initPlayerWith(e));return}fe(ne)}else P()},z=(U,ne)=>{if(!h()||!this.sourceBuffer)return;let Te,Ee,Be;const rt=Xe=>{window.setTimeout(()=>{h()&&z(U,ne)},Xe)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),rt(100);else{const Xe=ue(),bt=T.currentTime;!this.paused&&T.buffered.length>1&&J===bt&&Xe-re>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),J!==bt&&(J=bt,re=Xe);const Ie=this._getBufferSizeSec();if(Ie>30)A(`Buffered ${Ie} seconds; delaying appendBuffer`),rt(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:Xe,buf:Ie}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ne&&ne()}catch(Vt){if(Vt.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),Be=this.sourceBuffer.buffered.length,Be!==0&&(Te=this.sourceBuffer.buffered.start(0),Ee=bt,Ee-Te>4&&this.sourceBuffer.remove(Te,Ee-3)),rt(1e3);else throw Vt}}},ee=()=>{N&&R&&(A([`Appending chunk, sz=${N.byteLength}:`,JSON.stringify(V)]),z(N,function(){N=null,D()}))},se=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),fe=U=>{h()&&p(se(U),(ne,Te)=>{if(h()){if(Te/=1e3,N=ne,V=U,o=U.startTS,Te){const Ee=Math.min(10,U.dur/Te);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*Ee:Ee}ee()}},()=>this._handleNetworkError())},Re=U=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(U),!1)))},Ke=U=>{h()&&(e.cachedHeader=U,z(U,()=>{R=!0,ee()}))};n=!0,L.seek(U=>{if(h()){if(_=ue(),!U){P();return}I=U,!a.isNullable(y)||U.startTS>y?fe(U):(V=U,D())}},y),e.cachedHeader?Ke(e.cachedHeader):f(e.headerUrl,Ke,()=>this._handleNetworkError())},stop:b,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:r}=this.params;let s;e.bitrate!==this.bitrate&&(this.rep&&(s=this.rep.getTimestampSec(),a.isNonNullable(s)&&(s+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(s),r({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,r=h=>{if(!this.autoQuality)return;let f,p,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=ue();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&&Yl(o)<3e4)return;r(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=ue();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=qi(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Oi).withRetryCount(Li).withRetryInterval(dS,cS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;it(t).then(r=>{r||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:r,videoElement:s}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&s.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}`),r({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},hS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var x;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const bS=[x.PAUSED,x.PLAYING,x.READY],SS=[x.PAUSED,x.PLAYING,x.READY];class gS{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(x.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new xe,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new pa,this._dashCb=s=>{var n,o,l,d;switch(s.name){case"buffering":{const u=s.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${s.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=s.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=vi(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,S=Object.assign({},h.video);if(!p)continue;const g={id:f,quality:p,bitrate:m,size:S};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)===x.MANIFEST_READY&&this.videoState.setState(x.MANIFEST_READY);break}case"qualitySwitch":{const u=s.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}=s;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(s.shiftDuration),this.zeroTime$.next(s.zeroTime);break}}},this.syncPlayback=()=>{var s;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(x.STOPPED));return}if(!o){if(SS.includes(n)){const c=(s=this.params.desiredState.videoTrack.getTransition())===null||s===void 0?void 0:s.to;a.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===B.Requested&&bS.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case x.STOPPED:this.videoState.startTransitionTo(x.MANIFEST_READY),this.dash.attachSource(Ct(this.params.source.url));return;case x.MANIFEST_READY:this.videoState.startTransitionTo(x.READY),this.prepare();break;case x.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(x.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(x.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(x.PAUSED)})}return;case x.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(x.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case x.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(x.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(x.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=We(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.hostname$.next(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=Je(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===x.READY&&this.videoState.setState(x.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(x.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(x.PLAYING)},t)).add(r.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(s=>-s/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:r.timeUpdate$}).subscribe(({zeroTime:s,position:n})=>this.params.output.liveTime$.next(s+n*1e3),t)).add(mt(this.video,this.params.desiredState.isLooped,t)).add(ze(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(tt(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&a.videoQualityToHeight(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case x.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case x.MANIFEST_READY:case x.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 x.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case x.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}createLiveDashPlayer(){const e=new mS({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,r,s,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=(s=(r=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||r===void 0?void 0:r.to)!==null&&s!==void 0?s:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=pi(l.map(({track:f})=>f),{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()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===x.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ct(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}}var zl=i=>{var e,t;const r=i.get("X-Delivery-Type"),s=i.get("X-Reused"),n=r===null?exports.HttpConnectionType.HTTP1:(e=r)!==null&&e!==void 0?e:void 0,o=s===null?void 0:(t={1:!0,0:!1}[s])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},dt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const yS=i=>{const e=document.createElement("a");return e.href=i,e.origin},TS=i=>{const e=document.createElement("a");return e.href=i,e.host};class Wl{constructor(e,t=[],r,s,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=r,this._progressCb=s,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,r,s,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(r=this._errorCb)===null||r===void 0||r.call(this,`Http${(s=this._xhr)===null||s===void 0?void 0:s.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=ci(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 r;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(r=this._errorCb)===null||r===void 0||r.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let s;this._failoverIndex>=this._failoverHosts.length?(s=this._url,this._failoverIndex=0):(s=this._url.replace(TS(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",s,!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 Zi{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(r){if(r.name==="QuotaExceededError"){this._isFull=!0;const s=this._sourceBuffer.buffered;let n=0;for(let o=0,l=s.length;o<l;o++)n+=s.end(o)-s.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",r),r}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,r,s,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=S=>{s(Zi._str2ua(S.substr(d))),d=S.length};let m=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(m=Ot(m)),this._lastXhr=new Wl(m,e.failoverHosts,S=>{this._lastXhr=void 0,p(S);const g=Date.now()-u;this._params.onBandwidthChange({size:S.length,duration:g,speed:8*S.length/(g/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),n==null||n()},S=>{if(S.length-d>l&&p(S),h===0){h=Date.now();return}f=S.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=S.length,h=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},o,(S,g,v)=>this._params.onError(S,g,v))})}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(r){throw this._params.onError("SourceBuffer","Source Buffer update error",r),r}};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=Zi._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 r=new Uint8Array(e.byteLength+t.byteLength);return r.set(e,0),r.set(t,e.byteLength),r}static _str2ua(e){const t=new Uint8Array(e.length);for(let r=0;r<e.length;r++)t[r]=e.charCodeAt(r);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 ES{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)?)?$/,r=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},s=t.exec(e),n=(s==null?void 0:s[1])==="-"?-1:1,o={years:r(s==null?void 0:s[2],n),months:r(s==null?void 0:s[3],n),weeks:r(s==null?void 0:s[4],n),days:r(s==null?void 0:s[5],n),hours:r(s==null?void 0:s[6],n),minutes:r(s==null?void 0:s[7],n),seconds:r(s==null?void 0:s[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let r=e;this._config.REQUEST_QUIC&&(r=Ot(r)),new Wl(r,t,s=>{this.attachManifest(s,t,yS(r))},void 0,s=>{this._params.onResponseHeaders(s)},(s,n,o)=>this._params.onError(s,n,o))}attachManifest(e,t,r){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,S,g,v,b,E,y,T,A,L,R,N,V,I,_;const H=u.getElementsByTagName("SegmentBase")[0],J=H&&o(H,"indexRange").split("-"),re=H&&H.getElementsByTagName("Initialization")[0],P=re&&o(re,"range").split("-");if(!P||!J){const Re=u.parentElement;if((Re==null?void 0:Re.getAttribute("contentType"))==="text"){const Ke=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,U=(r?r+"/":"")+((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),ne=(S=Re.getAttribute("lang"))!==null&&S!==void 0?S:void 0;U&&d.push({id:Ke,url:U,language:ne})}return}const D=.1,z=Number((g=u.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),ee=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let se;const fe=(b=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&b!==void 0?b:void 0;se=fe?va(fe):void 0,l.push({width:Number((E=u.attributes.getNamedItem("width"))===null||E===void 0?void 0:E.value),height:Number((y=u.attributes.getNamedItem("height"))===null||y===void 0?void 0:y.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(J[0]),indexTo:Number(J[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(A=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&A!==void 0?A:void 0,mimeType:(R=(L=u.attributes.getNamedItem("mimeType"))===null||L===void 0?void 0:L.value)!==null&&R!==void 0?R:void 0,fps:se,bufferSize:D*z/8,bufferLength:D,name:(V=(N=u.attributes.getNamedItem("okQuality"))===null||N===void 0?void 0:N.value)!==null&&V!==void 0?V:void 0,id:(_=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&_!==void 0?_: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 r=Date.now();this._stream.load(e,e.initFrom,e.indexTo,s=>{let n=e.initTo-e.initFrom+1;if(!s.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(s.buffer,0,n);const o=new DataView(s.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,s=>{this._params.onResponseHeaders(s),this._params.onIdxRequestPing(Date.now()-r)},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 r=new t;let s,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!==s&&(s=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=r.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new Zi({mediaSource:r,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),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),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,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||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 r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.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 r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var F;(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"})(F||(F={}));const $S=[F.PAUSED,F.PLAYING];class PS{constructor(e){this.videoState=new K(F.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new xe,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:r})=>{var s,n,o;const l=[];for(const d of t){const u=(n=(s=d.name)!==null&&s!==void 0?s:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&vi(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)),(r==null?void 0:r.length)>0){const d=[];for(const u of r){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(F.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.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(),r=this.videoState.getTransition(),s=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(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==F.STOPPED&&(this.videoState.startTransitionTo(F.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(F.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===B.Requested&&$S.includes(t)&&this.seek(o.position,o.forcePrecise),t){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_LOADED),this.prepare();return;case F.MANIFEST_LOADED:this.videoState.startTransitionTo(F.INITIAL_REPRESENTATION_SELECTED);return;case F.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(F.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case F.METADATA_LOADED:this.videoState.startTransitionTo(F.READY),this.dash.updateRefsForCurrentTime();return;case F.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed());return;case F.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(F.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case F.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(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:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=We(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(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Bb(this.video),this.dash=new ES({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:r})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:r}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,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,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Je(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,r));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.isAudioAvailable$,e.isAudioAvailable$),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()===F.PLAYING||this.videoState.getState()===F.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(ze(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(tt(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(Xi(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===F.READY&&this.videoState.setState(F.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(F.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).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.stateChangeEnded$,this.params.output.element$,this.elementSize$,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(),S=this.elementSize$.getValue(),g=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let v;if(!g&&a.isNonNullable(p))v=p;else{const b=dt(this.video.buffered,this.video.currentTime*1e3),E=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,y=Math.min(b/E,1);v=(d=pi(h.map(({track:T})=>T),{container:S,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:y,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:T})=>T===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return a.isNonNullable(v)?(u=h.find(({track:b})=>b.id===v))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===F.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(F.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=dt(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!s())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(he(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=zl(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,r)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,r)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Qe(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(){it(this.video).then(e=>{e||(this.videoState.setState(F.PAUSED),k(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 er;(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"})(er||(er={}));var Se;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(Se||(Se={}));var G;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(G||(G={}));var Lt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Lt||(Lt={}));var Us=(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 kS=(i,e={})=>{const r=e.timeout||1,s=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-s-1>r},timeRemaining(){return Math.max(0,1+(performance.now()-s))}})},1)},AS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Xn=AS?kS:window.requestIdleCallback;var es,ts;let Ql=!1;try{Ql=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((ts=(es=navigator.userAgent.match(/Version\/(\d+)/))===null||es===void 0?void 0:es[1])!==null&&ts!==void 0?ts:"",10)<16}catch(i){console.error(i)}class wS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return Q(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return Q(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return Q(this,void 0,void 0,function*(){return new Promise(t=>{let r;Ql&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var Zn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Jl=new TextDecoder("ascii"),Kl=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Jl.decode(r);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,i.byteLength)-e,o=new DataView(i.buffer,i.byteOffset+e,n);return{id:s,size:t,contents:o}},_S=i=>Jl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",RS=(i,e,t)=>{const r=Kl(i),s=[];let n=0;const o=()=>{const S=r.contents.getUint32(n);return n+=4,S};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let p=c/u*1e3,m=(t?t.to+1:i.byteOffset+i.byteLength)+h;for(let S=0;S<f;S++){const g=o(),v=g>>>31,b=g<<1>>>1,E=o();if(o(),v!==0)throw new Error("Unsupported multilevel sidx");const y=E/u*1e3;s.push({status:G.NONE,time:{from:p,to:p+y},byte:{from:m,to:m+b-1}}),p+=y,m+=b}return s},IS=i=>{let e=0,t=!1,r=!1;for(;e<=i.byteLength&&!t;){const s=new DataView(i.buffer,i.byteOffset+e);try{const n=Kl(s);if(r||(r=n.id==="mdat"),e+n.size<=i.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=i.byteLength&&r?new DataView(i.buffer,i.byteOffset,e):null},NS={validateData:_S,parseInit:()=>null,getIndexRange:()=>{},parseSegments:RS,parseFeedableSegmentChunk:IS};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.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 w;(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"})(w||(w={}));const eo={[$.EBML]:{type:w.Master},[$.EBMLVersion]:{type:w.UnsignedInteger},[$.EBMLReadVersion]:{type:w.UnsignedInteger},[$.EBMLMaxIDLength]:{type:w.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[$.DocType]:{type:w.String},[$.DocTypeVersion]:{type:w.UnsignedInteger},[$.DocTypeReadVersion]:{type:w.UnsignedInteger},[$.Void]:{type:w.Binary},[$.Segment]:{type:w.Master},[$.SeekHead]:{type:w.Master},[$.Seek]:{type:w.Master},[$.SeekID]:{type:w.Binary},[$.SeekPosition]:{type:w.UnsignedInteger},[$.Info]:{type:w.Master},[$.TimestampScale]:{type:w.UnsignedInteger},[$.Duration]:{type:w.Float},[$.Tracks]:{type:w.Master},[$.Chapters]:{type:w.Master},[$.Cluster]:{type:w.Master},[$.Timestamp]:{type:w.UnsignedInteger},[$.SilentTracks]:{type:w.Master},[$.SilentTrackNumber]:{type:w.UnsignedInteger},[$.Position]:{type:w.UnsignedInteger},[$.PrevSize]:{type:w.UnsignedInteger},[$.SimpleBlock]:{type:w.Binary},[$.BlockGroup]:{type:w.Master},[$.EncryptedBlock]:{type:w.Binary},[$.Attachments]:{type:w.Master},[$.Tags]:{type:w.Master},[$.Cues]:{type:w.Master},[$.CuePoint]:{type:w.Master},[$.CueTime]:{type:w.UnsignedInteger},[$.CueTrackPositions]:{type:w.Master},[$.CueTrack]:{type:w.UnsignedInteger},[$.CueClusterPosition]:{type:w.UnsignedInteger},[$.CueRelativePosition]:{type:w.UnsignedInteger},[$.CueDuration]:{type:w.UnsignedInteger},[$.CueBlockNumber]:{type:w.UnsignedInteger},[$.CueCodecState]:{type:w.UnsignedInteger},[$.CueReference]:{type:w.Master},[$.CueRefTime]:{type:w.UnsignedInteger}},Xl=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=tr(i,t),s=r in eo,n=s?eo[r].type:w.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=tr(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:s?r:"0x"+r.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},tr=(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},Ue=(i,e)=>{switch(e){case w.SignedInteger:return i.getInt8(0);case w.UnsignedInteger:return tr(i);case w.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(i);case w.UTF8:return new TextDecoder("utf-8").decode(i);case w.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case w.Master:return i;case w.Binary:return i;default:a.assertNever(e)}},mi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=Xl(r);if(!e(s))return;s.type===w.Master&&mi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},CS=i=>{if(i.getUint32(0)!==$.EBML)return!1;let e,t,r;const s=Xl(i);return mi(s.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=Ue(l,o):n===$.DocType?t=Ue(l,o):n===$.DocTypeReadVersion&&(r=Ue(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Zl=[$.Info,$.SeekHead,$.Tracks,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],DS=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],OS=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return mi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===$.SeekID){const m=Ue(f,h);u=tr(m)}else c!==$.SeekPosition&&(u=void 0);return c===$.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===$.Info?n=!0:c===$.SeekHead?o=!0:c===$.TimestampScale?r=Ue(f,h):c===$.Duration?s=Ue(f,h):c===$.SeekPosition&&u===$.Cues?d=Ue(f,h):n&&o&&Zl.includes(c)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d}},LS=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},xS=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return mi(i,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&s(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=Ue(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=Ue(u,d));break;default:t&&Zl.includes(l)&&(r=!0)}return!(t&&r)}),o&&s(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:G.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}}})},BS=i=>{let e=0,t=!1;try{mi(i,r=>r.tag===$.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):DS.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},MS={validateData:CS,parseInit:OS,getIndexRange:LS,parseSegments:xS,parseFeedableSegmentChunk:BS};class to{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new ct,this.destroyAbortController=new ct,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Ae(this,arguments,function*(){const c=this.representations.get(u);a.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new wS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},m=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:m}))),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(m=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Zn(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield C(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id);if(a.assertNonNullable(h,"No init buffer for starting representation"),a.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return yield C(void 0);let p=0;for(const m of f)m.time.from-p>0&&this.gaps.push({representation:c.id,from:p,to:m.time.from}),p=m.time.to;a.isNonNullable(c.duration)&&c.duration-p>0&&this.gaps.push({representation:c.id,from:p,to:c.duration}),yield yield C(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Ae(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield C(void 0);this.switchingToRepresentationId=u;const c=this.representations.get(u);a.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(a.isNullable(h)?yield yield C(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield C(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield C(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield C(this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal));const f=this.getCurrentPosition();a.isNonNullable(f)&&this.maintain(f)})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=r,r){case Lt.MP4:this.containerParser=NS;break;case Lt.WEBM:this.containerParser=MS;break;default:a.assertNever(r)}this.initData=new Map(s.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(s.map(u=>[u.id,u])),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 ct,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer))return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=dt(this.sourceBuffer.buffered,e),h=s?s.time.to+100:-1/0;s&&c>=s.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&Zn(this.sourceBuffer.buffered)>=this.bufferLimit){const u=dt(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(r,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&s)if(l.includes(s))u="high";else{const c=Me(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===G.FED&&!l.length&&dt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Me(r,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const S=f<=r&&p>=r,g=f>r||S||m===0&&r===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),b=this.preloadOnly&&f<=r+v||p<=r+v;return(h===G.NONE||h===G.PARTIALLY_EJECTED&&g&&b&&this.sourceBuffer&&!Us(this.sourceBuffer.buffered,r))&&g&&b});if(s===-1)return[];if(t!==Se.BYTE_RANGE)return e.slice(s,s+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=s;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===G.NONE||f.status===G.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,r="auto"){return Q(this,void 0,void 0,function*(){if(!e.length)return;let s,n,o=e;const{type:l}=t.segmentReference;switch(l){case Se.BYTE_RANGE:{s=t.segmentReference.url,n={from:Me(e,0).byte.from,to:Me(e,-1).byte.to};break}case Se.TEMPLATE:{const u=Me(e,0);s=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=G.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 Ae(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(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(s,{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:r}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=dt((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,s)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,r||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,r,s,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=G.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===G.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=G.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===Se.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const g=p?f.byte.from-r:0,v=p?f.byte.to-r:e.byteLength,b=g<s,E=v<=s;if(f.status===G.DOWNLOADING&&b&&E){f.status=G.DOWNLOADED,this.activeSegments.delete(h);const y=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(y,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&b&&(h.loadedBytes=Math.min(m,s-g),h.loadedBytes>h.feedingBytes)){const y=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?y:this.containerParser.parseFeedableSegmentChunk(y);T!=null&&T.byteLength&&(f.status=G.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(A=>{if(n.aborted)o();else if(A)h.fedBytes+=T.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=Xn(()=>hr(this.loadInit(r,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",r=!1){return Q(this,void 0,void 0,function*(){const s=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!r&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Ae(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield C(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),r&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,r=!1){return Q(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let s=0,n=1/0,o=-1/0,l=!1;const 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;s+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||s>=t)break;c.status===G.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){s=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)||s>t)break;c.status===G.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===G.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&&r){s=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===G.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)}detectGaps(e,t){if(this.sourceBuffer)for(const r of t){let s={representation:e,from:r.time.from,to:r.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=r.time.from||o>=r.time.to)){if(o<=r.time.from&&l>=r.time.to){s=void 0;break}l>r.time.from&&l<r.time.to&&(s.from=l),o<r.time.to&&o>r.time.from&&(s.to=o)}}s&&s.to-s.from>=1&&!this.gaps.some(n=>s&&n.from===s.from&&n.to===s.to)&&this.gaps.push(s)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Xn(()=>{try{this.detectGaps(e,t)}catch(r){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:r})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let r=0;r<this.sourceBuffer.buffered.length;r++){const s=Math.round(this.sourceBuffer.buffered.start(r)*1e3),n=Math.round(this.sourceBuffer.buffered.end(r)*1e3);e.push({from:s,to:n})}const t=1;for(const r of this.segments.values())for(const s of r){const{status:n}=s;if(n!==G.FED&&n!==G.PARTIALLY_EJECTED)continue;const o=Math.floor(s.time.from),l=Math.ceil(s.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?s.status=G.PARTIALLY_EJECTED:s.status=G.NONE)}}}var Rt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Rt||(Rt={}));class VS{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:r=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new ct,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Ae(this,arguments,function*(){let n=s;this.requestQuic&&(n=Ot(n));const o=yield yield C(Dt(n,{signal:this.abortAllController.signal}).catch(Kt));return o?(this.onHeadersReceived(o.headers),yield C(o.text())):yield C(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?Rt.HEADER:Rt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return Ae(this,arguments,function*(){let S=s;const g=new Headers;if(o)switch(n){case Rt.HEADER:{g.append("Range",`bytes=${o.from}-${o.to}`);break}case Rt.PARAM:{const P=new URL(S,location.href);P.searchParams.append("bytes",`${o.from}-${o.to}`),S=P.toString();break}default:a.assertNever(n)}this.requestQuic&&(S=Ot(S));let v=this.abortAllController.signal;if(u){const P=new ct;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{P.abort()}catch(D){Kt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{P.abort()}catch(D){Kt(D)}v=P.signal}const b=a.now(),E=yield yield C(Dt(S,{priority:d,headers:g,signal:v}).catch(Kt)),y=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(y-b),!E)return yield C(null);if(!E.ok||!E.body)return yield C(Promise.reject(new Error(`Fetch error ${E.status}: ${E.statusText}`)));this.onHeadersReceived(E.headers);const T=parseInt((f=E.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const P=yield yield C(E.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(P.byteLength,a.now()-y),l==null||l(new DataView(P),P.byteLength),yield C(P)}if(!l&&!c)return yield C(E.arrayBuffer());const[A,L]=E.body.tee(),R=A.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(L));let N=0;const V=new ArrayBuffer(T),I=new Uint8Array(V),_=new DataView(V);let H=!1;const J=P=>{H=!0,Kt(P)},re=a.abortable(v,function({done:P,value:D}){return Ae(this,arguments,function*(){if(N===0&&this.lastRequestFirstBytes$.next(a.now()-b),v.aborted)return yield C(void 0);!P&&D&&(I.set(D,N),N+=D.byteLength,l==null||l(_,N),yield yield C(R==null?void 0:R.read().then(re,J)))})}.bind(this));return yield yield C(R==null?void 0:R.read().then(re,J)),yield C(H?null:V)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return Ae(this,arguments,function*(){if(s.type!==Se.BYTE_RANGE)return yield C(null);const{from:d,to:u}=s.initRange;let c=d,h=u,f=!1,p,m;s.indexRange&&(p=s.indexRange.from,m=s.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(m,u))),c=Math.min(c,0);const S=yield yield C(this.fetch(s.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!S)return yield C(null);const g=new DataView(S,d-c,u-c+1);if(!n.validateData(g))throw new Error("Invalid media file");const v=n.parseInit(g),b=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(v);if(!b)throw new ReferenceError("No way to load representation index");let E;if(f)E=new DataView(S,b.from-c,b.to-b.from+1);else{const T=yield yield C(this.fetch(s.url,{range:b,priority:o,measureThroughput:!1}));if(!T)return yield C(null);E=new DataView(T)}const y=n.parseSegments(E,v,b);return yield C({dataView:new DataView(S),segments:y})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Ae(this,arguments,function*(){if(s.type!==Se.TEMPLATE)return yield C(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield C(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield C(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:G.NONE,size:void 0}));return yield C({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=zl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(r)}fetchRepresentation(e,t,r="auto"){var s,n;return Q(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case Se.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case Se.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Kt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var FS=Ge,US=ai,jS=ce,HS=jS("match"),GS=function(i){var e;return FS(i)&&((e=i[HS])!==void 0?!!e:US(i)=="RegExp")},qS=di,YS=String,zS=function(i){if(qS(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return YS(i)},WS=Ye,QS=function(){var i=WS(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},JS=me,KS=Le,XS=rr,ZS=QS,io=RegExp.prototype,eg=function(i){var e=i.flags;return e===void 0&&!("flags"in io)&&!KS(i,"flags")&&XS(io,i)?JS(ZS,i):e},ba=ye,tg=or,ig=Math.floor,is=ba("".charAt),rg=ba("".replace),rs=ba("".slice),sg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,ag=/\$([$&'`]|\d{1,2})/g,ng=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,d=ag;return s!==void 0&&(s=tg(s),d=sg),rg(n,d,function(u,c){var h;switch(is(c,0)){case"$":return"$";case"&":return i;case"`":return rs(e,0,t);case"'":return rs(e,o);case"<":h=s[rs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=ig(f/10);return p===0?u:p<=l?r[p-1]===void 0?is(c,1):r[p-1]+is(c,1):u}h=r[f-1]}return h===void 0?"":h})},og=_e,lg=me,Sa=ye,ro=Hs,ug=ae,dg=ni,cg=GS,Pt=zS,hg=nr,fg=eg,pg=ng,vg=ce,mg=vg("replace"),bg=TypeError,eu=Sa("".indexOf),Sg=Sa("".replace),so=Sa("".slice),gg=Math.max,ao=function(i,e,t){return t>i.length?-1:e===""?t:eu(i,e,t)};og({target:"String",proto:!0},{replaceAll:function(e,t){var r=ro(this),s,n,o,l,d,u,c,h,f,p=0,m=0,S="";if(!dg(e)){if(s=cg(e),s&&(n=Pt(ro(fg(e))),!~eu(n,"g")))throw bg("`.replaceAll` does not allow non-global regexes");if(o=hg(e,mg),o)return lg(o,e,r,t);if(s)return Sg(Pt(r),e,t)}for(l=Pt(r),d=Pt(e),u=ug(t),u||(t=Pt(t)),c=d.length,h=gg(1,c),p=ao(l,d,0);p!==-1;)f=u?Pt(t(d,p,l)):pg(d,l,p,[],void 0,t),S+=so(l,m,p)+f,m=p+c,p=ao(l,d,p+h);return m<l.length&&(S+=so(l,m)),S}});var yg=ha,Tg=yg("String","replaceAll"),Eg=Tg,$g=Eg,Pg=$g,kg=Pg,no=kg;const oo=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},r=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),s=(r==null?void 0:r[1])==="-"?-1:1,n={days:e(r==null?void 0:r[5],s),hours:e(r==null?void 0:r[6],s),minutes:e(r==null?void 0:r[7],s),seconds:e(r==null?void 0:r[8],s)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},ss=(i,e)=>{let t=i;t=no(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=no(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Ag=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,m,S,g,v,b,E,y,T,A,L,R,N,V,I,_,H,J,re,P,D,z,ee,se,fe,Re,Ke,U,ne;const Ee=new DOMParser().parseFromString(i,"application/xml"),Be={video:[],audio:[],text:[]},rt=Ee.children[0],Xe=rt.getElementsByTagName("Period")[0],bt=Xe.children;let Ie;const Vt=rt.getAttribute("mediaPresentationDuration"),ga=Xe.getAttribute("duration");if(Vt)Ie=oo(Vt);else if(ga){const $e=oo(ga);a.isNonNullable($e)&&(Ie=$e)}let ou=0;const vr=(r=(t=rt.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],lu=vr.includes(er.WEBM_AS_IN_FFMPEG)||vr.includes(er.WEBM_AS_IN_SPEC)?Lt.WEBM:Lt.MP4;for(const $e of bt){const bi=$e.getAttribute("mimeType"),uu=$e.getAttribute("codecs"),ya=(s=$e.getAttribute("contentType"))!==null&&s!==void 0?s:bi==null?void 0:bi.split("/")[0],du=(o=(n=$e.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Ta=$e.querySelectorAll("Representation"),cu=$e.querySelector("SegmentTemplate");if(ya===oe.TEXT){for(const te of Ta){const st=te.getAttribute("id")||"",Si=$e.getAttribute("lang"),St=(u=(d=(l=te.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",mr=new URL(St,e).toString();Be[oe.TEXT].push({id:st,lang:Si,kind:oe.TEXT,url:mr})}continue}for(const te of Ta){const st=(c=te.getAttribute("mimeType"))!==null&&c!==void 0?c:bi,Si=(f=(h=te.getAttribute("codecs"))!==null&&h!==void 0?h:uu)!==null&&f!==void 0?f:"",St=(m=(p=te.getAttribute("contentType"))!==null&&p!==void 0?p:st==null?void 0:st.split("/")[0])!==null&&m!==void 0?m:ya,mr=(g=(S=$e.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&g!==void 0?g:[],hu=parseInt((v=te.getAttribute("width"))!==null&&v!==void 0?v:"",10),Ea=parseInt((b=te.getAttribute("height"))!==null&&b!==void 0?b:"",10),$a=parseInt((E=te.getAttribute("bandwidth"))!==null&&E!==void 0?E:"",10)/1e3,Pa=(y=te.getAttribute("frameRate"))!==null&&y!==void 0?y:"",fu=(T=te.getAttribute("quality"))!==null&&T!==void 0?T:void 0,pu=Pa?va(Pa):void 0,vu=(A=te.getAttribute("id"))!==null&&A!==void 0?A:(ou++).toString(10),mu=St==="video"?`${Ea}p`:St==="audio"?`${$a}Kbps`:Si,bu=`${vu}@${mu}`,Su=(N=(R=(L=te.querySelector("BaseURL"))===null||L===void 0?void 0:L.textContent)===null||R===void 0?void 0:R.trim())!==null&&N!==void 0?N:"",ka=new URL(Su,e).toString(),gu=[...vr,...du,...mr];let br;const yu=te.querySelector("SegmentBase"),at=(V=te.querySelector("SegmentTemplate"))!==null&&V!==void 0?V:cu;if(yu){const Ft=(_=(I=te.querySelector("SegmentBase Initialization"))===null||I===void 0?void 0:I.getAttribute("range"))!==null&&_!==void 0?_:"",[Ut,gr]=Ft.split("-").map(nt=>parseInt(nt,10)),jt={from:Ut,to:gr},Ht=(H=te.querySelector("SegmentBase"))===null||H===void 0?void 0:H.getAttribute("indexRange"),[yr,gi]=Ht?Ht.split("-").map(nt=>parseInt(nt,10)):[],Gt=Ht?{from:yr,to:gi}:void 0;br={type:Se.BYTE_RANGE,url:ka,initRange:jt,indexRange:Gt}}else if(at){const Ft={representationId:(J=te.getAttribute("id"))!==null&&J!==void 0?J:void 0,bandwidth:(re=te.getAttribute("bandwidth"))!==null&&re!==void 0?re:void 0},Ut=parseInt((P=at.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),gr=(D=at.getAttribute("initialization"))!==null&&D!==void 0?D:"",jt=at.getAttribute("media"),Ht=(ee=parseInt((z=at.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&ee!==void 0?ee:1,yr=ss(gr,Ft);if(!jt)throw new ReferenceError("No media attribute in SegmentTemplate");const gi=(se=at.querySelectorAll("SegmentTimeline S"))!==null&&se!==void 0?se:[],Gt=[];if(gi.length){let nt=Ht,ot=0;for(const qt of gi){const gt=parseInt((fe=qt.getAttribute("d"))!==null&&fe!==void 0?fe:"",10)*1e3,Yt=parseInt((Re=qt.getAttribute("r"))!==null&&Re!==void 0?Re:"",10)||0,zt=(U=parseInt((Ke=qt.getAttribute("t"))!==null&&Ke!==void 0?Ke:"",10))!==null&&U!==void 0?U:void 0;for(let Aa=0;Aa<Yt+1;Aa++){const Tu=ss(jt,Object.assign(Object.assign({},Ft),{segmentNumber:nt.toString(10),segmentTime:zt.toString(10)})),Eu=zt?zt/Ut:ot;ot+=gt/Ut;const $u=ot;nt++,Gt.push({time:{from:Eu,to:$u},url:Tu})}}}else if(a.isNonNullable(Ie)){const ot=parseInt((ne=at.getAttribute("duration"))!==null&&ne!==void 0?ne:"",10)/Ut*1e3,qt=Math.ceil(Ie/ot);let gt=0;for(let Yt=1;Yt<qt;Yt++){const zt=ss(jt,Object.assign(Object.assign({},Ft),{segmentNumber:Yt.toString(10),segmentTime:gt.toString(10)}));Gt.push({time:{from:gt,to:gt+ot},url:zt}),gt+=ot}}br={type:Se.TEMPLATE,baseUrl:ka,initUrl:yr,segments:Gt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!St||!st)continue;const Sr={video:oe.VIDEO,audio:oe.AUDIO,text:oe.TEXT}[St];Sr&&Be[Sr].push({id:bu,kind:Sr,segmentReference:br,profiles:gu,duration:Ie,bitrate:$a,mime:st,codecs:Si,width:hu,height:Ea,fps:pu,quality:fu})}}return{duration:Ie,container:lu,representations:Be}},wg=["timeupdate","progress","play","seeked","stalled","waiting"];var be;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(be||(be={}));let _g=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new K(be.NONE),this.currentVideoRepresentation$=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.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new ct,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Ae(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(be.MANIFEST_READY);const s=yield yield C(this.fetcher.fetchManifest(r).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!s)return yield C(void 0);let n;try{n=Ag(s!=null?s:"",r)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield C(void 0);const o=({kind:l,mime:d,codecs:u})=>{var c,h,f;return Boolean(((c=t.canPlayType)===null||c===void 0?void 0:c.call(t,d))&&((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0?void 0:f.call(h,`${d}; codecs="${u}"`))||l===oe.TEXT)};this.manifest=Object.assign(Object.assign({},n),{representations:ci(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))}),this.manifest.representations.video.length?this.state$.setState(be.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return Ae(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.state$.startTransitionTo(be.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new to(oe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new to(oe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));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.subscription.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.subscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.source.readyState!=="open"&&(yield yield C(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(r)?yield yield C(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield C(this.videoBufferManager.startWith(t)),this.state$.setState(be.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumGap(),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 VS({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(be.RUNNING),this.subscription.add(a.merge(...wg.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&&Us(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return Q(this,void 0,void 0,function*(){const r={[oe.VIDEO]:this.videoBufferManager,[oe.AUDIO]:this.audioBufferManager,[oe.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Us(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(be.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.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}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const r of this.bufferManagers)for(const s of r.gaps)r.playingRepresentation$.getValue()===s.representation&&s.from<=e&&s.to>e&&(this.element.duration*1e3-s.to<this.tuning.endGapTolerance?t.push(1/0):t.push(s.to));if(t.length){const r=Math.max(...t);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const Rg=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?vi(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},Ig=({id:i,bitrate:e})=>({id:i,bitrate:e}),Ng=({id:i,lang:e,url:t,isAuto:r})=>({id:i,url:t,isAuto:r,type:"internal",language:e}),Cg=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=Me(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:Me(i,-1)};class Dg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new xe,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new tS,this.textTracks=[],this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===B.Requested&&(s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&t!==X.STOPPED&&r!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),r===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(X.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case X.STOPPED:this.videoState.startTransitionTo(X.READY),this.prepare();return;case X.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new _g({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=Je(this.video),s=u=>{e.error$.next({id:"DashVKProvider",category:a.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.isAudioAvailable$,e.isAudioAvailable$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(mt(this.video,t.isLooped,s)),this.subscription.add(ze(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(tt(this.video,t.playbackRate,r.playbackRateState$,s)),n(Xi(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===be.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[],this.textTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((g,v)=>v.bitrate-g.bitrate),p=Array.from(h.video).sort((g,v)=>v.bitrate-g.bitrate),m=Array.from(h.text);if(!this.params.tuning.isAudioDisabled)for(const g of f){const v=Ig(g);v&&this.audioTracks.push({track:v,representation:g})}for(const g of p){const v=Rg(g);if(v){this.videoTracks.push({track:v,representation:g});const b=!this.params.tuning.isAudioDisabled&&Cg(f,p,g);b&&this.audioRepresentations.set(g.id,b)}}for(const g of m){const v=Ng(g);v&&this.textTracks.push({track:v,representation:g})}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===be.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==be.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(oe.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(oe.AUDIO,f.id).catch(o)}},s)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}selectVideoRepresentation(){var e,t,r,s,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:v}})=>v===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=dt(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,p=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(r=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&r!==void 0?r:0,c&&(n=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.bitrate)!==null&&n!==void 0?n:0),S=pi(this.videoTracks.map(({track:v})=>v),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:p,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),g=l?S!=null?S:u:u!=null?u:S;return g&&((o=this.videoTracks.find(({track:v})=>v===g))===null||o===void 0?void 0:o.representation)}prepare(){return Q(this,void 0,void 0,function*(){this.player.initManifest(this.video,this.params.source.url)})}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}playIfAllowed(){it(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(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}))}}const Og=5e3,Ce={};var j;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(j||(j={}));const Xt=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Lg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(j.INITIALIZING),this.textTracksManager=new xe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==j.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case j.STOPPED:break;case j.READY:case j.PLAYING:case j.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case j.STOPPED:this.prepare();break;case j.READY:case j.PLAYING:case j.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case j.PLAYING:break;case j.STOPPED:this.prepare();break;case j.READY:case j.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case j.PAUSED:break;case j.STOPPED:this.prepare();break;case j.READY:this.videoState.setState(j.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case j.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=We(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),Og);hr(import("hls.js").then(s=>{e||(Ce.Hls=s.default,Ce.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Ce.Hls,"hls.js not loaded"),this.hls=new Ce.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(j.STOPPED)}subscribe(){a.assertNonNullable(Ce.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=Je(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,r));n(s.timeUpdate$,t.position$),n(s.durationChange$,t.duration$),n(s.ended$,t.endedEvent$),n(s.looped$,t.loopedEvent$),n(s.error$,t.error$),n(s.isBuffering$,t.isBuffering$),n(s.currentBuffer$,t.currentBuffer$),n(s.loadStart$,t.firstBytesEvent$),n(s.playing$,t.firstFrameEvent$),n(s.canplay$,t.canplay$),n(s.seeked$,t.seekedEvent$),n(s.isAudioAvailable$,t.isAudioAvailable$),n(s.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(ze(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(tt(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Xt(this.hls,Ce.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:a.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(j.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(j.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===j.READY&&this.videoState.setState(j.READY),this.videoState.getState()===j.PLAYING&&this.playIfAllowed()},r)),n(Xt(this.hls,Ce.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:S,height:g}=h,v=(p=vi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:S,height:g});if(!v)return c;const b=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,E={id:m.toString(),quality:v,bitrate:h.bitrate/1e3,size:{width:S,height:g},fps:b};return this.trackLevels.set(m,{track:E,level:h}),c.push(E),c},[]))),t.availableVideoTracks$),n(Xt(this.hls,Ce.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const c=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI||"",m=h.lang,S="internal";c.push({id:f,url:p,language:m,type:S})}e.internalTextTracks.startTransitionTo(c)}}),n(Xt(this.hls,Ce.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>he(u))),t.hostname$),this.subscription.add(we(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:r}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Xt(this.hls,Ce.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,r),this.subscription.add(we(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,m=this.hls.levels[p];!m||h.bitrate>m.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l.pipe(a.map(u=>u==null?void 0:u.id)),onError:r})),n(s.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){this.videoState.startTransitionTo(j.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return Q(this,void 0,void 0,function*(){this.videoState.startTransitionTo(j.PLAYING),(yield it(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState(j.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(j.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(j.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const lo="X-Playback-Duration";var uo=i=>Q(void 0,void 0,void 0,function*(){const e=yield Dt(i,{method:"HEAD"});return e.headers.has(lo)?parseInt(e.headers.get(lo),10):void 0});const xg=i=>{let e=null;if(i.QUALITY&&(e=vi(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=a.videoSizeToQuality({width:t,height:r})}return e!=null?e:null},tu=(i,e=i)=>Q(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Dt(i)).text()).split(`
|
|
8
|
+
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=ci(u[1].split(",").map(v=>v.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=xg(c);let p;c.BANDWIDTH&&(p=parseInt(c.BANDWIDTH,10)/1e3||void 0),!p&&c["AVERAGE-BANDWIDTH"]&&(p=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const m=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let S;if(c.RESOLUTION){const[v,b]=c.RESOLUTION.split("x").map(E=>parseInt(E,10));v&&b&&(S={width:v,height:b})}const g=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:g,bandwidth:p,size:S,fps:m})}return o});var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(q||(q={}));class Bg{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new K(q.STOPPED),this.textTracksManager=new xe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new pa,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){s!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(q.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===B.Requested){this.videoState.startTransitionTo(q.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case q.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case q.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),tu(Ct(this.params.source.url),this.params.source.url).then(s=>{this.manifests$.next([r,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},s=Je(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.ended$,e.endedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(ze(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(tt(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===q.READY&&this.videoState.setState(q.READY),this.videoState.getState()===q.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(he(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===q.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===B.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Ct(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),uo(t).then(r=>{var s;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const n=(s=this.params.source.maxSeekBackTime)!==null&&s!==void 0?s:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{Dt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();uo(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){it(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class Mg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(W.STOPPED),this.textTracksManager=new xe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const r=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(r===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(W.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===B.Requested&&this.seek(u.position),r){case W.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(he(this.params.source.url)),tu(this.params.source.url).then(r=>{this.manifests$.next([t,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:r,videoTrack:s}=this.params.desiredState,n=r.getState(),o=s.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:s.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&s.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},s=Je(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(ze(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(tt(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY),this.videoState.getState()===W.PLAYING&&this.playIfAllowed()},r).add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(he(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===B.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Qe(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){it(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class Vg{constructor(e){this.subscription=new a.Subscription,this.videoState=new K(Z.STOPPED),this.trackUrls={},this.textTracksManager=new xe,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&this.seek(l.position),t){case Z.READY:r===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=Je(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,r));n(s.timeUpdate$,e.position$),n(s.durationChange$,e.duration$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.loadedMetadata$,e.firstBytesEvent$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.seeked$,e.seekedEvent$),n(s.isAudioAvailable$,e.isAudioAvailable$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(ze(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(tt(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&a.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Qe(this.video)}prepare(){var e,t;const r=(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();a.assertNonNullable(r,"MpegProvider: track is not selected");let{url:s}=this.trackUrls[r];a.assertNonNullable(s,`MpegProvider: No url for ${r}`),this.params.tuning.requestQuick&&(s=Ot(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(he(s))}playIfAllowed(){it(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const co=["stun:videostun.mycdn.me:80"],Fg=1e3,Ug=3,as=()=>null;class jg{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=as,this.externalStopCallback=as,this.externalErrorCallback=as,this.options=this.normalizeOptions(t);const r=e.split("/");this.serverUrl=r.slice(0,r.length-1).join("/"),this.streamKey=r[r.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return Q(this,void 0,void 0,function*(){try{const t=yield this.createOffer();this.peerConnection&&(yield this.peerConnection.setLocalDescription(t)),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}})}handleLogin(){return Q(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:co}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=yield this.createOffer();yield this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}})}handleAnswer(e){return Q(this,void 0,void 0,function*(){try{this.peerConnection&&(yield this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e})))}catch(t){this.handleRTCError(t)}})}handleCandidate(e){return Q(this,void 0,void 0,function*(){if(e)try{this.peerConnection&&(yield this.peerConnection.addIceCandidate(e))}catch(t){this.handleRTCError(t)}})}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:a.ErrorCategory.WTF,message:e.message})}onPeerConnectionStream(e){return Q(this,void 0,void 0,function*(){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))})}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}createOffer(){return Q(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),r=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(r))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Fg)}normalizeOptions(e={}){const t={stunServerList:co,maxRetryNumber:Ug,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Y||(Y={}));class Hg{constructor(e){this.videoState=new K(Y.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case Y.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=We(e.container),this.liveStreamClient=new jg(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Qe(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=Je(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(s.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(s.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===Y.READY&&this.videoState.setState(Y.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ze(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Y.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Y.READY:break;case Y.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Y.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(he(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:a.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Y.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){it(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class ho{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return Boolean(this.current.done)}}var ns,os,ls,us,ds,cs,xi,hs,Bi,fs,Mi,ps,Vi,vs,Fi,ms,Ui,bs;const iu=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Ze=document.createElement("video"),Gg='video/mp4; codecs="avc1.42000a,mp4a.40.2"',qg='video/mp4; codecs="hev1.1.6.L93.B0"',ru='video/webm; codecs="vp09.00.10.08"',su='video/webm; codecs="av01.0.00M.08"',Yg='audio/mp4; codecs="mp4a.40.2"',zg='audio/webm; codecs="opus"',Pe={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((os=(ns=window.SourceBuffer)===null||ns===void 0?void 0:ns.prototype)===null||os===void 0?void 0:os.appendBuffer)),hls:Boolean(((ls=Ze.canPlayType)===null||ls===void 0?void 0:ls.call(Ze,"application/x-mpegurl"))||((us=Ze.canPlayType)===null||us===void 0?void 0:us.call(Ze,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection),ws:Boolean(window.WebSocket)},pe={mp4:Boolean((ds=Ze.canPlayType)===null||ds===void 0?void 0:ds.call(Ze,"video/mp4")),webm:Boolean((cs=Ze.canPlayType)===null||cs===void 0?void 0:cs.call(Ze,"video/webm")),cmaf:!0},Oe={h264:Boolean((hs=(xi=window.MediaSource)===null||xi===void 0?void 0:xi.isTypeSupported)===null||hs===void 0?void 0:hs.call(xi,Gg)),h265:Boolean((fs=(Bi=window.MediaSource)===null||Bi===void 0?void 0:Bi.isTypeSupported)===null||fs===void 0?void 0:fs.call(Bi,qg)),vp9:Boolean((ps=(Mi=window.MediaSource)===null||Mi===void 0?void 0:Mi.isTypeSupported)===null||ps===void 0?void 0:ps.call(Mi,ru)),av1:Boolean((vs=(Vi=window.MediaSource)===null||Vi===void 0?void 0:Vi.isTypeSupported)===null||vs===void 0?void 0:vs.call(Vi,su)),aac:Boolean((ms=(Fi=window.MediaSource)===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||ms===void 0?void 0:ms.call(Fi,Yg)),opus:Boolean((bs=(Ui=window.MediaSource)===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||bs===void 0?void 0:bs.call(Ui,zg))},kt=(Oe.h264||Oe.h265)&&Oe.aac;var Ve;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Ve||(Ve={}));let ut;const Wg=()=>Q(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:su})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:ru})}))]);ut={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{Wg()}catch(i){console.error(i)}const pr=Pe.hls&&pe.mp4,Qg=()=>Object.keys(Oe).filter(i=>Oe[i]),Jg=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Pe.mse&&pe.mp4&&kt;case exports.VideoFormat.DASH_SEP:return Pe.mse&&pe.mp4&&kt;case exports.VideoFormat.DASH_WEBM:return Pe.mse&&pe.webm&&Oe.vp9&&Oe.opus;case exports.VideoFormat.DASH_WEBM_AV1:return Pe.mse&&pe.webm&&Oe.av1&&Oe.opus;case exports.VideoFormat.DASH_LIVE:return Pe.mse&&pe.mp4&&kt;case exports.VideoFormat.DASH_LIVE_CMAF:return Pe.mse&&pe.mp4&&kt&&pe.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Pe.mse&&pe.mp4&&kt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return pr||e&&Pe.mse&&pe.mp4&&kt;case exports.VideoFormat.MPEG:return pe.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Pe.webrtc&&Pe.ws&&Oe.h264&&(pe.mp4||pe.webm);default:return a.assertNever(t)}}),Ss=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case Ve.VP9:return[e,t];case Ve.AV1:return[t,e];case Ve.NONE:return[];case Ve.SMOOTH:return ut?ut[t].smooth?[t,e]:ut[e].smooth?[e,t]:[t,e]:[e,t];case Ve.POWER_EFFICIENT:return ut?ut[t].powerEfficient?[t,e]:ut[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(i)}return[e,t]},Kg=(i=Ve.VP9)=>iu?[exports.VideoFormat.MPEG,...Ss(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:pr?[...Ss(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ss(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Xg=()=>iu?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:pr?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],fo=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Zg=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const po={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},ey={cacheDuration:12e4},ty={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},iy={maxPausedTime:3e4},vo={maxPausedTime:3e4};class ry{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Jg([...Xg(),...Kg(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:r,formatsToAvoid:s}=this.params.tuning;let n=[];r?n=[r]:s.length?n=[...t.filter(l=>!s.includes(l)),...t.filter(l=>s.includes(l))]:n=t,this.screenFormatsIterator=new ho(n);const o=[...fo(!0),...fo(!1)];this.chromecastFormatsIterator=new ho(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),s=r.state!==B.None;this.params.desiredState.seekState.setState({state:B.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:r,desiredState:s}=this.params,n=this.providerOutput,o={container:r,source:null,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new PS(Object.assign(Object.assign({},o),{source:l,config:ey}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new Qn(Object.assign(Object.assign({},o),{source:l,format:e,config:vo})):new Dg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Qn(Object.assign(Object.assign({},o),{source:l,format:e,config:vo}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),pr||!this.params.tuning.useHlsJs?new Mg(Object.assign(Object.assign({},o),{source:l})):new Lg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bg(Object.assign(Object.assign({},o),{source:l,config:iy}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Vg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new gS(Object.assign(Object.assign({},o),{source:l,config:ty}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Hg({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Pb({connection:l,meta:n,container:r,source:t,format:e,desiredState:s,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case le.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const r=s=>{const n=new URL(s);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:r(e.url)})}return ci(Object.entries(e).map(([s,n])=>[s,r(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,r=0;return e.add(a.merge(this.providerOutput.error$,Zg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:po.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const n=this.current$.getValue().destination;if(n===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(le.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=s.category===a.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<po.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:le.SCREEN)}})),e}}const js=(i,e,t)=>t*e+(1-t)*i,au=(i,e)=>i.reduce((t,r)=>t+r,0)/e,sy=(i,e,t,r)=>{let s=0,n=t;const o=au(i,e),l=e<r?e:r;for(let d=0;d<l;d++)i[n]>o?s++:s--,n=(i.length+n-1)%i.length;return Math.abs(s)===l};class nu{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new De(`raw_${r}`),this.smoothedSeries$=new De(`smoothed_${r}`),this.reportedSeries$=new De(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class ay extends nu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=js(this.slow,e,this.params.emaAlphaSlow),this.fast=js(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ny extends nu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=au(this.pastMeasures,this.takenMeasures);this.emaSmoothed=js(this.emaSmoothed,e,this.params.emaAlpha);const r=sy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class mo{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new ay({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ny({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}}const oy=5e3,bo="one_video_throughput",So="one_video_rtt",He=window.navigator.connection,go=()=>{const i=He==null?void 0:He.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},yo=()=>{const i=He==null?void 0:He.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},To=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ii{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ii.load(bo)||(e.useBrowserEstimation?go():void 0)||oy,n=(r=(t=ii.load(So))!==null&&t!==void 0?t:e.useBrowserEstimation?yo():void 0)!==null&&r!==void 0?r:0;if(this.throughput$=new a.ValueSubject(s),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(To(s,n,e.rttPenaltyRequestSize)),this.throughput=mo.getSmoothedValue(s,-1,e),this.rtt=mo.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=go();d&&this.throughput.next(d);const u=yo();a.isNonNullable(u)&&this.rtt.next(u)};He&&"onchange"in He&&this.subscription.add(a.fromEvent(He,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(bo,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(So,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(a.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(a.map(({throughput:o,rtt:l})=>To(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,r=a.now();const s=new a.Subscription;switch(this.subscription.add(s),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:s.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,r=a.now()}));break;case 1:case 0:s.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,r=a.now()}));break}s.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-r;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),s.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let r=0;const s=a.now();let n=0,o=a.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=({done:u,value:c})=>Q(this,void 0,void 0,function*(){u?(this.addRawSpeed(r,a.now()-s,1),this.concurrentDownloads.delete(e)):c&&(r+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&a.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,a.now()-o,this.concurrentDownloads.size),n=0,o=a.now()),yield t==null?void 0:t.read().then(d,l))});this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,r=1){if(ii.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=a.safeStorage.get(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const Eo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,webmCodec:Ve.VP9,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},ly=i=>{const e={};for(const t of Object.keys(Eo)){const r=Eo[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?t==="configName"?e[t]=[...s,...r]:e[t]=s:typeof r=="object"&&typeof s=="object"?e[t]=Object.assign(Object.assign({},r),s):e[t]=s!=null?s:r}return e};var $o=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===B.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===B.None))),uy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};class dy{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:B.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),internalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:Xb},this.initLogs(),this.tuning=ly(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Cu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ii(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,r,s)=>{const n=Reflect.get(t,r,s);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(r)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,r,s;return this.config=e,this.domContainer=uy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new ry({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.setState(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(r=>r.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===B.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===B.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:B.Applying})):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:l})=>l).sort((l,d)=>a.isInvariantQuality(l)?1:a.isInvariantQuality(d)?-1:a.isHigher(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.pipe(a.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(a.combine({isLive:e.providerOutput.isLive$,position:$o({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(a.map(({isLive:o,position:l})=>o&&l>-a.ACTIVE_LIVE_VALID_DELAY),a.filterChanged()).subscribe(this.info.atLiveEdge$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add($o({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||r.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=pi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),Kb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Jb(r)),this.providerContainer.current$.subscribe(({type:r})=>Di("provider",r)),t.duration$.subscribe(r=>Di("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Di("tracks",r)),this.events.fatalError$.subscribe(new De("fatalError")),this.events.managedError$.subscribe(new De("managedError")),t.position$.subscribe(new De("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new De("quality")),this.info.currentBuffer$.subscribe(new De("buffer")),t.isBuffering$.subscribe(new De("isBuffering"))].forEach(r=>this.subscription.add(r)),Di("codecs",Qg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>Q(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}}const cy=`@vkontakte/videoplayer-core@${Po}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return a.VideoQuality}});exports.Player=dy;exports.SDK_VERSION=cy;exports.VERSION=Po;
|