@vkontakte/videoplayer-core 2.0.83-dev.65744ed.0 → 2.0.83
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +5 -63
- package/es2015.esm.js +5 -63
- package/es2018.cjs.js +5 -63
- package/es2018.esm.js +5 -63
- package/esnext.cjs.js +5 -63
- package/esnext.esm.js +5 -63
- package/evergreen.esm.js +5 -63
- package/index.d.ts +0 -9
- package/package.json +1 -1
package/es2015.cjs.js
CHANGED
|
@@ -1,66 +1,8 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.83
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.83
|
|
3
|
+
* Fri, 21 Apr 2023 09:48:43 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-83/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var ku=Object.create;var Da=Object.defineProperty;var _u=Object.getOwnPropertyDescriptor;var wu=Object.getOwnPropertyNames;var Ru=Object.getPrototypeOf,Iu=Object.prototype.hasOwnProperty;var Du=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wu(e))!Iu.call(i,r)&&r!==t&&Da(i,r,{get:()=>e[r],enumerable:!(s=_u(e,r))||s.enumerable});return i};var Ca=(i,e,t)=>(t=i!=null?ku(Ru(i)):{},Du(e||!i||!i.__esModule?Da(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Cu=require("lodash/debounce.js");const Nu="2.0.83-dev.65744ed.0",xu="es2015.cjs.js";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_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 fe;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(fe||(fe={}));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 C;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(C||(C={}));function J(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(s.next(c))}catch(h){o(h)}}function d(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(l,d)}u((s=s.apply(i,e||[])).next())})}function R(i){return this instanceof R?(this.v=i,this):new R(i)}function Ae(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){s[f]&&(r[f]=function(m){return new Promise(function(v,p){n.push([f,m,v,p])>1||l(f,m)})})}function l(f,m){try{d(s[f](m))}catch(v){h(n[0][3],v)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,m){f(m),n.shift(),n.length&&l(n[0][0],n[0][1])}}var Ou=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Lu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=Boolean(window.__onGCastApiAvailable);r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Ou("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,n;(n=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([s.getCastState()])).pipe(a.filterChanged(),a.map(Bu),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=s.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const 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 Na=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Ee=function(i){try{return!!i()}catch(e){return!0}},Mu=Ee,cs=!Mu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),wo=cs,Ro=Function.prototype,kr=Ro.call,Vu=wo&&Ro.bind.bind(kr,kr),$e=wo?Vu:function(i){return function(){return kr.apply(i,arguments)}},Io=$e,Fu=Io({}.toString),Uu=Io("".slice),ci=function(i){return Uu(Fu(i),8,-1)},ju=$e,Hu=Ee,Gu=ci,Rs=Object,Yu=ju("".split),qu=Hu(function(){return!Rs("z").propertyIsEnumerable(0)})?function(i){return Gu(i)=="String"?Yu(i,""):Rs(i)}:Rs,hi=function(i){return i==null},zu=hi,Wu=TypeError,Qr=function(i){if(zu(i))throw Wu("Can't call method on "+i);return i},Qu=qu,Ju=Qr,fi=function(i){return Qu(Ju(i))},Ku=function(){},Mt={},ki=function(i){return i&&i.Math==Math&&i},le=ki(typeof globalThis=="object"&&globalThis)||ki(typeof window=="object"&&window)||ki(typeof self=="object"&&self)||ki(typeof Na=="object"&&Na)||function(){return this}()||Function("return this")(),_r=typeof document=="object"&&document.all,Xu=typeof _r=="undefined"&&_r!==void 0,Do={all:_r,IS_HTMLDDA:Xu},Co=Do,Zu=Co.all,re=Co.IS_HTMLDDA?function(i){return typeof i=="function"||i===Zu}:function(i){return typeof i=="function"},ed=le,td=re,xa=ed.WeakMap,id=td(xa)&&/native code/.test(String(xa)),Oa=re,No=Do,sd=No.all,Ge=No.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Oa(i)||i===sd}:function(i){return typeof i=="object"?i!==null:Oa(i)},rd=Ee,Ye=!rd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ft={},ad=le,La=Ge,wr=ad.document,nd=La(wr)&&La(wr.createElement),Jr=function(i){return nd?wr.createElement(i):{}},od=Ye,ld=Ee,ud=Jr,xo=!od&&!ld(function(){return Object.defineProperty(ud("div"),"a",{get:function(){return 7}}).a!=7}),dd=Ye,cd=Ee,Oo=dd&&cd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),hd=Ge,fd=String,pd=TypeError,qe=function(i){if(hd(i))return i;throw pd(fd(i)+" is not an object")},md=cs,_i=Function.prototype.call,me=md?_i.bind(_i):function(){return _i.apply(_i,arguments)},Kr={},Is=Kr,Ds=le,vd=re,Ba=function(i){return vd(i)?i:void 0},pt=function(i,e){return arguments.length<2?Ba(Is[i])||Ba(Ds[i]):Is[i]&&Is[i][e]||Ds[i]&&Ds[i][e]},bd=$e,hs=bd({}.isPrototypeOf),fs=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Lo=le,Cs=fs,Ma=Lo.process,Va=Lo.Deno,Fa=Ma&&Ma.versions||Va&&Va.version,Ua=Fa&&Fa.v8,Pe,Zi;Ua&&(Pe=Ua.split("."),Zi=Pe[0]>0&&Pe[0]<4?1:+(Pe[0]+Pe[1]));!Zi&&Cs&&(Pe=Cs.match(/Edge\/(\d+)/),(!Pe||Pe[1]>=74)&&(Pe=Cs.match(/Chrome\/(\d+)/),Pe&&(Zi=+Pe[1])));var Bo=Zi,ja=Bo,Sd=Ee,Mo=!!Object.getOwnPropertySymbols&&!Sd(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&ja&&ja<41}),gd=Mo,Vo=gd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",yd=pt,Td=re,Ed=hs,$d=Vo,Pd=Object,Fo=$d?function(i){return typeof i=="symbol"}:function(i){var e=yd("Symbol");return Td(e)&&Ed(e.prototype,Pd(i))},Ad=String,ps=function(i){try{return Ad(i)}catch(e){return"Object"}},kd=re,_d=ps,wd=TypeError,mt=function(i){if(kd(i))return i;throw wd(_d(i)+" is not a function")},Rd=mt,Id=hi,ms=function(i,e){var t=i[e];return Id(t)?void 0:Rd(t)},Ns=me,xs=re,Os=Ge,Dd=TypeError,Cd=function(i,e){var t,s;if(e==="string"&&xs(t=i.toString)&&!Os(s=Ns(t,i))||xs(t=i.valueOf)&&!Os(s=Ns(t,i))||e!=="string"&&xs(t=i.toString)&&!Os(s=Ns(t,i)))return s;throw Dd("Can't convert object to primitive value")},es={},Nd={get exports(){return es},set exports(i){es=i}},Uo=!0,Ha=le,xd=Object.defineProperty,Od=function(i,e){try{xd(Ha,i,{value:e,configurable:!0,writable:!0})}catch(t){Ha[i]=e}return e},Ld=le,Bd=Od,Ga="__core-js_shared__",Md=Ld[Ga]||Bd(Ga,{}),Xr=Md,Ya=Xr;(Nd.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=Qr,Fd=Object,vs=function(i){return Fd(Vd(i))},Ud=$e,jd=vs,Hd=Ud({}.hasOwnProperty),Oe=Object.hasOwn||function(e,t){return Hd(jd(e),t)},Gd=$e,Yd=0,qd=Math.random(),zd=Gd(1 .toString),jo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+zd(++Yd+qd,36)},Wd=le,Qd=es,qa=Oe,Jd=jo,Kd=Mo,Xd=Vo,_t=Wd.Symbol,Ls=Qd("wks"),Zd=Xd?_t.for||_t:_t&&_t.withoutSetter||Jd,ue=function(i){return qa(Ls,i)||(Ls[i]=Kd&&qa(_t,i)?_t[i]:Zd("Symbol."+i)),Ls[i]},ec=me,za=Ge,Wa=Fo,tc=ms,ic=Cd,sc=ue,rc=TypeError,ac=sc("toPrimitive"),nc=function(i,e){if(!za(i)||Wa(i))return i;var t=tc(i,ac),s;if(t){if(e===void 0&&(e="default"),s=ec(t,i,e),!za(s)||Wa(s))return s;throw rc("Can't convert object to primitive value")}return e===void 0&&(e="number"),ic(i,e)},oc=nc,lc=Fo,Zr=function(i){var e=oc(i,"string");return lc(e)?e:e+""},uc=Ye,dc=xo,cc=Oo,wi=qe,Qa=Zr,hc=TypeError,Bs=Object.defineProperty,fc=Object.getOwnPropertyDescriptor,Ms="enumerable",Vs="configurable",Fs="writable";ft.f=uc?cc?function(e,t,s){if(wi(e),t=Qa(t),wi(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Fs in s&&!s[Fs]){var r=fc(e,t);r&&r[Fs]&&(e[t]=s.value,s={configurable:Vs in s?s[Vs]:r[Vs],enumerable:Ms in s?s[Ms]:r[Ms],writable:!1})}return Bs(e,t,s)}:Bs:function(e,t,s){if(wi(e),t=Qa(t),wi(s),dc)try{return Bs(e,t,s)}catch(r){}if("get"in s||"set"in s)throw hc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var bs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},pc=Ye,mc=ft,vc=bs,pi=pc?function(i,e,t){return mc.f(i,e,vc(1,t))}:function(i,e,t){return i[e]=t,i},bc=es,Sc=jo,Ja=bc("keys"),ea=function(i){return Ja[i]||(Ja[i]=Sc(i))},ta={},gc=id,Ho=le,yc=Ge,Tc=pi,Us=Oe,js=Xr,Ec=ea,$c=ta,Ka="Object already initialized",Rr=Ho.TypeError,Pc=Ho.WeakMap,ts,ui,is,Ac=function(i){return is(i)?ui(i):ts(i,{})},kc=function(i){return function(e){var t;if(!yc(e)||(t=ui(e)).type!==i)throw Rr("Incompatible receiver, "+i+" required");return t}};if(gc||js.state){var De=js.state||(js.state=new Pc);De.get=De.get,De.has=De.has,De.set=De.set,ts=function(i,e){if(De.has(i))throw Rr(Ka);return e.facade=i,De.set(i,e),e},ui=function(i){return De.get(i)||{}},is=function(i){return De.has(i)}}else{var yt=Ec("state");$c[yt]=!0,ts=function(i,e){if(Us(i,yt))throw Rr(Ka);return e.facade=i,Tc(i,yt,e),e},ui=function(i){return Us(i,yt)?i[yt]:{}},is=function(i){return Us(i,yt)}}var Go={set:ts,get:ui,has:is,enforce:Ac,getterFor:kc},_c=cs,Yo=Function.prototype,Xa=Yo.apply,Za=Yo.call,qo=typeof Reflect=="object"&&Reflect.apply||(_c?Za.bind(Xa):function(){return Za.apply(Xa,arguments)}),wc=ci,Rc=$e,zo=function(i){if(wc(i)==="Function")return Rc(i)},ia={},Wo={},Qo={}.propertyIsEnumerable,Jo=Object.getOwnPropertyDescriptor,Ic=Jo&&!Qo.call({1:2},1);Wo.f=Ic?function(e){var t=Jo(this,e);return!!t&&t.enumerable}:Qo;var Dc=Ye,Cc=me,Nc=Wo,xc=bs,Oc=fi,Lc=Zr,Bc=Oe,Mc=xo,en=Object.getOwnPropertyDescriptor;ia.f=Dc?en:function(e,t){if(e=Oc(e),t=Lc(t),Mc)try{return en(e,t)}catch(s){}if(Bc(e,t))return xc(!Cc(Nc.f,e,t),e[t])};var Vc=Ee,Fc=re,Uc=/#|\.prototype\./,mi=function(i,e){var t=Hc[jc(i)];return t==Yc?!0:t==Gc?!1:Fc(e)?Vc(e):!!e},jc=mi.normalize=function(i){return String(i).replace(Uc,".").toLowerCase()},Hc=mi.data={},Gc=mi.NATIVE="N",Yc=mi.POLYFILL="P",Ko=mi,tn=zo,qc=mt,zc=cs,Wc=tn(tn.bind),Ss=function(i,e){return qc(i),e===void 0?i:zc?Wc(i,e):function(){return i.apply(e,arguments)}},Ri=le,Qc=qo,Jc=zo,Kc=re,Xc=ia.f,Zc=Ko,Tt=Kr,eh=Ss,Et=pi,sn=Oe,th=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Qc(i,this,arguments)};return e.prototype=i.prototype,e},_e=function(i,e){var t=i.target,s=i.global,r=i.stat,n=i.proto,o=s?Ri:r?Ri[t]:(Ri[t]||{}).prototype,l=s?Tt:Tt[t]||Et(Tt,t,{})[t],d=l.prototype,u,c,h,f,m,v,p,b,S;for(f in e)u=Zc(s?f:t+(r?".":"#")+f,i.forced),c=!u&&o&&sn(o,f),v=l[f],c&&(i.dontCallGetSet?(S=Xc(o,f),p=S&&S.value):p=o[f]),m=c&&p?p:e[f],!(c&&typeof v==typeof m)&&(i.bind&&c?b=eh(m,Ri):i.wrap&&c?b=th(m):n&&Kc(m)?b=Jc(m):b=m,(i.sham||m&&m.sham||v&&v.sham)&&Et(b,"sham",!0),Et(l,f,b),n&&(h=t+"Prototype",sn(Tt,h)||Et(Tt,h,{}),Et(Tt[h],f,m),i.real&&d&&(u||!d[f])&&Et(d,f,m)))},Ir=Ye,ih=Oe,Xo=Function.prototype,sh=Ir&&Object.getOwnPropertyDescriptor,sa=ih(Xo,"name"),rh=sa&&function(){}.name==="something",ah=sa&&(!Ir||Ir&&sh(Xo,"name").configurable),nh={EXISTS:sa,PROPER:rh,CONFIGURABLE:ah},Zo={},oh=Math.ceil,lh=Math.floor,uh=Math.trunc||function(e){var t=+e;return(t>0?lh:oh)(t)},dh=uh,ra=function(i){var e=+i;return e!==e||e===0?0:dh(e)},ch=ra,hh=Math.max,fh=Math.min,ph=function(i,e){var t=ch(i);return t<0?hh(t+e,0):fh(t,e)},mh=ra,vh=Math.min,bh=function(i){return i>0?vh(mh(i),9007199254740991):0},Sh=bh,aa=function(i){return Sh(i.length)},gh=fi,yh=ph,Th=aa,rn=function(i){return function(e,t,s){var r=gh(e),n=Th(r),o=yh(s,n),l;if(i&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in r)&&r[o]===t)return i||o||0;return!i&&-1}},Eh={includes:rn(!0),indexOf:rn(!1)},$h=$e,Hs=Oe,Ph=fi,Ah=Eh.indexOf,kh=ta,an=$h([].push),_h=function(i,e){var t=Ph(i),s=0,r=[],n;for(n in t)!Hs(kh,n)&&Hs(t,n)&&an(r,n);for(;e.length>s;)Hs(t,n=e[s++])&&(~Ah(r,n)||an(r,n));return r},el=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],wh=_h,Rh=el,Ih=Object.keys||function(e){return wh(e,Rh)},Dh=Ye,Ch=Oo,Nh=ft,xh=qe,Oh=fi,Lh=Ih;Zo.f=Dh&&!Ch?Object.defineProperties:function(e,t){xh(e);for(var s=Oh(t),r=Lh(t),n=r.length,o=0,l;n>o;)Nh.f(e,l=r[o++],s[l]);return e};var Bh=pt,tl=Bh("document","documentElement"),Mh=qe,Vh=Zo,nn=el,Fh=ta,Uh=tl,jh=Jr,Hh=ea,on=">",ln="<",Dr="prototype",Cr="script",il=Hh("IE_PROTO"),Gs=function(){},sl=function(i){return ln+Cr+on+i+ln+"/"+Cr+on},un=function(i){i.write(sl("")),i.close();var e=i.parentWindow.Object;return i=null,e},Gh=function(){var i=jh("iframe"),e="java"+Cr+":",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},Ii,Wi=function(){try{Ii=new ActiveXObject("htmlfile")}catch(e){}Wi=typeof document!="undefined"?document.domain&&Ii?un(Ii):Gh():un(Ii);for(var i=nn.length;i--;)delete Wi[Dr][nn[i]];return Wi()};Fh[il]=!0;var rl=Object.create||function(e,t){var s;return e!==null?(Gs[Dr]=Mh(e),s=new Gs,Gs[Dr]=null,s[il]=e):s=Wi(),t===void 0?s:Vh.f(s,t)},Yh=Ee,qh=!Yh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),zh=Oe,Wh=re,Qh=vs,Jh=ea,Kh=qh,dn=Jh("IE_PROTO"),Nr=Object,Xh=Nr.prototype,al=Kh?Nr.getPrototypeOf:function(i){var e=Qh(i);if(zh(e,dn))return e[dn];var t=e.constructor;return Wh(t)&&e instanceof t?t.prototype:e instanceof Nr?Xh:null},Zh=pi,na=function(i,e,t,s){return s&&s.enumerable?i[e]=t:Zh(i,e,t),i},ef=Ee,tf=re,sf=Ge,rf=rl,cn=al,af=na,nf=ue,xr=nf("iterator"),nl=!1,je,Ys,qs;[].keys&&(qs=[].keys(),"next"in qs?(Ys=cn(cn(qs)),Ys!==Object.prototype&&(je=Ys)):nl=!0);var of=!sf(je)||ef(function(){var i={};return je[xr].call(i)!==i});of?je={}:je=rf(je);tf(je[xr])||af(je,xr,function(){return this});var ol={IteratorPrototype:je,BUGGY_SAFARI_ITERATORS:nl},lf=ue,uf=lf("toStringTag"),ll={};ll[uf]="z";var oa=String(ll)==="[object z]",df=oa,cf=re,Qi=ci,hf=ue,ff=hf("toStringTag"),pf=Object,mf=Qi(function(){return arguments}())=="Arguments",vf=function(i,e){try{return i[e]}catch(t){}},vi=df?Qi:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=vf(e=pf(i),ff))=="string"?t:mf?Qi(e):(s=Qi(e))=="Object"&&cf(e.callee)?"Arguments":s},bf=oa,Sf=vi,gf=bf?{}.toString:function(){return"[object "+Sf(this)+"]"},yf=oa,Tf=ft.f,Ef=pi,$f=Oe,Pf=gf,Af=ue,hn=Af("toStringTag"),la=function(i,e,t,s){if(i){var r=t?i:i.prototype;$f(r,hn)||Tf(r,hn,{configurable:!0,value:e}),s&&!yf&&Ef(r,"toString",Pf)}},kf=ol.IteratorPrototype,_f=rl,wf=bs,Rf=la,If=Mt,Df=function(){return this},Cf=function(i,e,t,s){var r=e+" Iterator";return i.prototype=_f(kf,{next:wf(+!s,t)}),Rf(i,r,!1,!0),If[r]=Df,i},Nf=_e,xf=me,ul=nh,Of=Cf,Lf=al,Bf=la,fn=na,Mf=ue,pn=Mt,dl=ol,Vf=ul.PROPER;ul.CONFIGURABLE;dl.IteratorPrototype;var Di=dl.BUGGY_SAFARI_ITERATORS,zs=Mf("iterator"),mn="keys",Ci="values",vn="entries",Ff=function(){return this},Uf=function(i,e,t,s,r,n,o){Of(t,e,s);var l=function(S){if(S===r&&f)return f;if(!Di&&S in c)return c[S];switch(S){case mn:return function(){return new t(this,S)};case Ci:return function(){return new t(this,S)};case vn:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[zs]||c["@@iterator"]||r&&c[r],f=!Di&&h||l(r),m=e=="Array"&&c.entries||h,v,p,b;if(m&&(v=Lf(m.call(new i)),v!==Object.prototype&&v.next&&(Bf(v,d,!0,!0),pn[d]=Ff)),Vf&&r==Ci&&h&&h.name!==Ci&&(u=!0,f=function(){return xf(h,this)}),r)if(p={values:l(Ci),keys:n?f:l(mn),entries:l(vn)},o)for(b in p)(Di||u||!(b in c))&&fn(c,b,p[b]);else Nf({target:e,proto:!0,forced:Di||u},p);return o&&c[zs]!==f&&fn(c,zs,f,{name:r}),pn[e]=f,p},jf=function(i,e){return{value:i,done:e}},Hf=fi,ua=Ku,bn=Mt,cl=Go,Gf=ft.f,Yf=Uf,Ni=jf,qf=Uo,zf=Ye,hl="Array Iterator",Wf=cl.set,Qf=cl.getterFor(hl);Yf(Array,"Array",function(i,e){Wf(this,{type:hl,target:Hf(i),index:0,kind:e})},function(){var i=Qf(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Ni(void 0,!0)):t=="keys"?Ni(s,!1):t=="values"?Ni(e[s],!1):Ni([s,e[s]],!1)},"values");var Sn=bn.Arguments=bn.Array;ua();ua();ua();if(!qf&&zf&&Sn.name!=="values")try{Gf(Sn,"name",{value:"values"})}catch(i){}var Jf=ue,Kf=Mt,Xf=Jf("iterator"),Zf=Array.prototype,ep=function(i){return i!==void 0&&(Kf.Array===i||Zf[Xf]===i)},tp=vi,gn=ms,ip=hi,sp=Mt,rp=ue,ap=rp("iterator"),fl=function(i){if(!ip(i))return gn(i,ap)||gn(i,"@@iterator")||sp[tp(i)]},np=me,op=mt,lp=qe,up=ps,dp=fl,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=me,yn=qe,pp=ms,mp=function(i,e,t){var s,r;yn(i);try{if(s=pp(i,"return"),!s){if(e==="throw")throw t;return t}s=fp(s,i)}catch(n){r=!0,s=n}if(e==="throw")throw t;if(r)throw s;return yn(s),t},vp=Ss,bp=me,Sp=qe,gp=ps,yp=ep,Tp=aa,Tn=hs,Ep=hp,$p=fl,En=mp,Pp=TypeError,Ji=function(i,e){this.stopped=i,this.result=e},$n=Ji.prototype,da=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=vp(e,s),u,c,h,f,m,v,p,b=function(y){return u&&En(u,"normal",y),new Ji(!0,y)},S=function(y){return r?(Sp(y),l?d(y[0],y[1],b):d(y[0],y[1])):l?d(y,b):d(y)};if(n)u=i.iterator;else if(o)u=i;else{if(c=$p(i),!c)throw Pp(gp(i)+" is not iterable");if(yp(c)){for(h=0,f=Tp(i);f>h;h++)if(m=S(i[h]),m&&Tn($n,m))return m;return new Ji(!1)}u=Ep(i,c)}for(v=n?i.next:u.next;!(p=bp(v,u)).done;){try{m=S(p.value)}catch(y){En(u,"throw",y)}if(typeof m=="object"&&m&&Tn($n,m))return m}return new Ji(!1)},Ap=Zr,kp=ft,_p=bs,wp=function(i,e,t){var s=Ap(e);s in i?kp.f(i,s,_p(0,t)):i[s]=t},Rp=_e,Ip=da,Dp=wp;Rp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Ip(e,function(s,r){Dp(t,s,r)},{AS_ENTRIES:!0}),t}});var Cp=Kr,Np=Cp.Object.fromEntries,xp={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},Op=xp,Lp=le,Bp=vi,Mp=pi,Pn=Mt,Vp=ue,An=Vp("toStringTag");for(var Ws in Op){var kn=Lp[Ws],Qs=kn&&kn.prototype;Qs&&Bp(Qs)!==An&&Mp(Qs,An,Ws),Pn[Ws]=Pn.Array}var Fp=Np,Up=Fp,jp=Up,Hp=jp,bi=Hp,Gp=ci,gs=typeof process!="undefined"&&Gp(process)=="process",Yp=pt,qp=ft,zp=ue,Wp=Ye,_n=zp("species"),Qp=function(i){var e=Yp(i),t=qp.f;Wp&&e&&!e[_n]&&t(e,_n,{configurable:!0,get:function(){return this}})},Jp=hs,Kp=TypeError,Xp=function(i,e){if(Jp(e,i))return i;throw Kp("Incorrect invocation")},Zp=$e,em=re,Or=Xr,tm=Zp(Function.toString);em(Or.inspectSource)||(Or.inspectSource=function(i){return tm(i)});var pl=Or.inspectSource,im=$e,sm=Ee,ml=re,rm=vi,am=pt,nm=pl,vl=function(){},om=[],bl=am("Reflect","construct"),ca=/^\s*(?:class|function)\b/,lm=im(ca.exec),um=!ca.exec(vl),Zt=function(e){if(!ml(e))return!1;try{return bl(vl,om,e),!0}catch(t){return!1}},Sl=function(e){if(!ml(e))return!1;switch(rm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return um||!!lm(ca,nm(e))}catch(t){return!0}};Sl.sham=!0;var dm=!bl||sm(function(){var i;return Zt(Zt.call)||!Zt(Object)||!Zt(function(){i=!0})||i})?Sl:Zt,cm=dm,hm=ps,fm=TypeError,pm=function(i){if(cm(i))return i;throw fm(hm(i)+" is not a constructor")},wn=qe,mm=pm,vm=hi,bm=ue,Sm=bm("species"),gl=function(i,e){var t=wn(i).constructor,s;return t===void 0||vm(s=wn(t)[Sm])?e:mm(s)},gm=$e,ym=gm([].slice),Tm=TypeError,Em=function(i,e){if(i<e)throw Tm("Not enough arguments");return i},$m=fs,yl=/(?:ipad|iphone|ipod).*applewebkit/i.test($m),pe=le,Pm=qo,Am=Ss,Rn=re,km=Oe,Tl=Ee,In=tl,_m=ym,Dn=Jr,wm=Em,Rm=yl,Im=gs,Lr=pe.setImmediate,Br=pe.clearImmediate,Dm=pe.process,Js=pe.Dispatch,Cm=pe.Function,Cn=pe.MessageChannel,Nm=pe.String,Ks=0,ri={},Nn="onreadystatechange",di,ot,Xs,Zs;Tl(function(){di=pe.location});var ha=function(i){if(km(ri,i)){var e=ri[i];delete ri[i],e()}},er=function(i){return function(){ha(i)}},xn=function(i){ha(i.data)},On=function(i){pe.postMessage(Nm(i),di.protocol+"//"+di.host)};(!Lr||!Br)&&(Lr=function(e){wm(arguments.length,1);var t=Rn(e)?e:Cm(e),s=_m(arguments,1);return ri[++Ks]=function(){Pm(t,void 0,s)},ot(Ks),Ks},Br=function(e){delete ri[e]},Im?ot=function(i){Dm.nextTick(er(i))}:Js&&Js.now?ot=function(i){Js.now(er(i))}:Cn&&!Rm?(Xs=new Cn,Zs=Xs.port2,Xs.port1.onmessage=xn,ot=Am(Zs.postMessage,Zs)):pe.addEventListener&&Rn(pe.postMessage)&&!pe.importScripts&&di&&di.protocol!=="file:"&&!Tl(On)?(ot=On,pe.addEventListener("message",xn,!1)):Nn in Dn("script")?ot=function(i){In.appendChild(Dn("script"))[Nn]=function(){In.removeChild(this),ha(i)}}:ot=function(i){setTimeout(er(i),0)});var El={set:Lr,clear:Br},$l=function(){this.head=null,this.tail=null};$l.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 Pl=$l,xm=fs,Om=/ipad|iphone|ipod/i.test(xm)&&typeof Pebble!="undefined",Lm=fs,Bm=/web0s(?!.*chrome)/i.test(Lm),ht=le,Ln=Ss,Mm=ia.f,tr=El.set,Vm=Pl,Fm=yl,Um=Om,jm=Bm,ir=gs,Bn=ht.MutationObserver||ht.WebKitMutationObserver,Mn=ht.document,Vn=ht.process,xi=ht.Promise,Fn=Mm(ht,"queueMicrotask"),Mr=Fn&&Fn.value,$t,sr,rr,Oi,Un;if(!Mr){var Li=new Vm,Bi=function(){var i,e;for(ir&&(i=Vn.domain)&&i.exit();e=Li.get();)try{e()}catch(t){throw Li.head&&$t(),t}i&&i.enter()};!Fm&&!ir&&!jm&&Bn&&Mn?(sr=!0,rr=Mn.createTextNode(""),new Bn(Bi).observe(rr,{characterData:!0}),$t=function(){rr.data=sr=!sr}):!Um&&xi&&xi.resolve?(Oi=xi.resolve(void 0),Oi.constructor=xi,Un=Ln(Oi.then,Oi),$t=function(){Un(Bi)}):ir?$t=function(){Vn.nextTick(Bi)}:(tr=Ln(tr,ht),$t=function(){tr(Bi)}),Mr=function(i){Li.head||$t(),Li.add(i)}}var Hm=Mr,Gm=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}}},Ym=le,Vt=Ym.Promise,Al=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",qm=Al,zm=gs,Wm=!qm&&!zm&&typeof window=="object"&&typeof document=="object",Qm=le,ai=Vt,Jm=re,Km=Ko,Xm=pl,Zm=ue,ev=Wm,tv=Al,ar=Bo,jn=ai&&ai.prototype,iv=Zm("species"),Vr=!1,kl=Jm(Qm.PromiseRejectionEvent),sv=Km("Promise",function(){var i=Xm(ai),e=i!==String(ai);if(!e&&ar===66||!(jn.catch&&jn.finally))return!0;if(!ar||ar<51||!/native code/.test(i)){var t=new ai(function(n){n(1)}),s=function(n){n(function(){},function(){})},r=t.constructor={};if(r[iv]=s,Vr=t.then(function(){})instanceof s,!Vr)return!0}return!e&&(ev||tv)&&!kl}),Si={CONSTRUCTOR:sv,REJECTION_EVENT:kl,SUBCLASSING:Vr},Ft={},Hn=mt,rv=TypeError,av=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw rv("Bad Promise constructor");e=s,t=r}),this.resolve=Hn(e),this.reject=Hn(t)};Ft.f=function(i){return new av(i)};var nv=_e,ss=gs,Ze=le,gi=me,ov=na,lv=la,uv=Qp,dv=mt,Fr=re,cv=Ge,hv=Xp,fv=gl,_l=El.set,pa=Hm,pv=Gm,mv=fa,vv=Pl,wl=Go,Ur=Vt,ma=Si,Rl=Ft,ys="Promise",Il=ma.CONSTRUCTOR,bv=ma.REJECTION_EVENT;ma.SUBCLASSING;var nr=wl.getterFor(ys),Sv=wl.set,gv=Ur&&Ur.prototype,wt=Ur,or=gv,Dl=Ze.TypeError,jr=Ze.document,va=Ze.process,Hr=Rl.f,yv=Hr,Tv=!!(jr&&jr.createEvent&&Ze.dispatchEvent),Cl="unhandledrejection",Ev="rejectionhandled",Gn=0,Nl=1,$v=2,ba=1,xl=2,Mi,Yn,Pv,Ol=function(i){var e;return cv(i)&&Fr(e=i.then)?e:!1},Ll=function(i,e){var t=e.value,s=e.state==Nl,r=s?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{r?(s||(e.rejection===xl&&kv(e),e.rejection=ba),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===i.promise?o(Dl("Promise-chain cycle")):(u=Ol(d))?gi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Bl=function(i,e){i.notified||(i.notified=!0,pa(function(){for(var t=i.reactions,s;s=t.get();)Ll(s,i);i.notified=!1,e&&!i.rejection&&Av(i)}))},Ml=function(i,e,t){var s,r;Tv?(s=jr.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Ze.dispatchEvent(s)):s={promise:e,reason:t},!bv&&(r=Ze["on"+i])?r(s):i===Cl&&pv("Unhandled promise rejection",t)},Av=function(i){gi(_l,Ze,function(){var e=i.facade,t=i.value,s=qn(i),r;if(s&&(r=mv(function(){ss?va.emit("unhandledRejection",t,e):Ml(Cl,e,t)}),i.rejection=ss||qn(i)?xl:ba,r.error))throw r.value})},qn=function(i){return i.rejection!==ba&&!i.parent},kv=function(i){gi(_l,Ze,function(){var e=i.facade;ss?va.emit("rejectionHandled",e):Ml(Ev,e,i.value)})},Rt=function(i,e,t){return function(s){i(e,s,t)}},Dt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=$v,Bl(i,!0))},Gr=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 s=Ol(e);s?pa(function(){var r={done:!1};try{gi(s,e,Rt(Gr,r,i),Rt(Dt,r,i))}catch(n){Dt(r,n,i)}}):(i.value=e,i.state=Nl,Bl(i,!1))}catch(r){Dt({done:!1},r,i)}}};Il&&(wt=function(e){hv(this,or),dv(e),gi(Mi,this);var t=nr(this);try{e(Rt(Gr,t),Rt(Dt,t))}catch(s){Dt(t,s)}},or=wt.prototype,Mi=function(e){Sv(this,{type:ys,done:!1,notified:!1,parent:!1,reactions:new vv,rejection:!1,state:Gn,value:void 0})},Mi.prototype=ov(or,"then",function(e,t){var s=nr(this),r=Hr(fv(this,wt));return s.parent=!0,r.ok=Fr(e)?e:!0,r.fail=Fr(t)&&t,r.domain=ss?va.domain:void 0,s.state==Gn?s.reactions.add(r):pa(function(){Ll(r,s)}),r.promise}),Yn=function(){var i=new Mi,e=nr(i);this.promise=i,this.resolve=Rt(Gr,e),this.reject=Rt(Dt,e)},Rl.f=Hr=function(i){return i===wt||i===Pv?new Yn(i):yv(i)});nv({global:!0,constructor:!0,wrap:!0,forced:Il},{Promise:wt});lv(wt,ys,!1,!0);uv(ys);var _v=ue,Vl=_v("iterator"),Fl=!1;try{var wv=0,zn={next:function(){return{done:!!wv++}},return:function(){Fl=!0}};zn[Vl]=function(){return this},Array.from(zn,function(){throw 2})}catch(i){}var Rv=function(i,e){if(!e&&!Fl)return!1;var t=!1;try{var s={};s[Vl]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Iv=Vt,Dv=Rv,Cv=Si.CONSTRUCTOR,Ul=Cv||!Dv(function(i){Iv.all(i).then(void 0,function(){})}),Nv=_e,xv=me,Ov=mt,Lv=Ft,Bv=fa,Mv=da,Vv=Ul;Nv({target:"Promise",stat:!0,forced:Vv},{all:function(e){var t=this,s=Lv.f(t),r=s.resolve,n=s.reject,o=Bv(function(){var l=Ov(t.resolve),d=[],u=0,c=1;Mv(e,function(h){var f=u++,m=!1;c++,xv(l,t,h).then(function(v){m||(m=!0,d[f]=v,--c||r(d))},n)}),--c||r(d)});return o.error&&n(o.value),s.promise}});var Fv=_e,Uv=Si.CONSTRUCTOR,Wn=Vt;Wn&&Wn.prototype;Fv({target:"Promise",proto:!0,forced:Uv,real:!0},{catch:function(i){return this.then(void 0,i)}});var jv=_e,Hv=me,Gv=mt,Yv=Ft,qv=fa,zv=da,Wv=Ul;jv({target:"Promise",stat:!0,forced:Wv},{race:function(e){var t=this,s=Yv.f(t),r=s.reject,n=qv(function(){var o=Gv(t.resolve);zv(e,function(l){Hv(o,t,l).then(s.resolve,r)})});return n.error&&r(n.value),s.promise}});var Qv=_e,Jv=me,Kv=Ft,Xv=Si.CONSTRUCTOR;Qv({target:"Promise",stat:!0,forced:Xv},{reject:function(e){var t=Kv.f(this);return Jv(t.reject,void 0,e),t.promise}});var Zv=qe,eb=Ge,tb=Ft,jl=function(i,e){if(Zv(i),eb(e)&&e.constructor===i)return e;var t=tb.f(i),s=t.resolve;return s(e),t.promise},ib=_e,sb=pt,rb=Uo,ab=Vt,nb=Si.CONSTRUCTOR,ob=jl,lb=sb("Promise"),ub=!nb;ib({target:"Promise",stat:!0,forced:rb},{resolve:function(e){return ob(ub&&this===lb?ab:this,e)}});var db=_e,Yr=Vt,cb=Ee,hb=pt,fb=re,pb=gl,Qn=jl,mb=Yr&&Yr.prototype,vb=!!Yr&&cb(function(){mb.finally.call({then:function(){}},function(){})});db({target:"Promise",proto:!0,real:!0,forced:vb},{finally:function(i){var e=pb(this,hb("Promise")),t=fb(i);return this.then(t?function(s){return Qn(e,i()).then(function(){return s})}:i,t?function(s){return Qn(e,i()).then(function(){throw s})}:i)}});var bb=pt,Sa=bb,Sb=Sa,gb=Sb("Promise","finally"),yb=gb,Tb=yb,Eb=Tb,$b=Eb,Ts=$b,Ct;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(Ct||(Ct={}));var Nt=(i,e=0,t=Ct.OFFSET_P)=>{switch(t){case Ct.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case Ct.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}default:a.assertNever(t)}return i},P=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.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 ke={[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}},Ki=(i,e)=>ke[i].height>ke[e].height,Pb=(i,e)=>ke[i].height>=ke[e].height,ni=(i,e)=>ke[i].height<ke[e].height,Ab=(i,e)=>ke[i].height<=ke[e].height,kb=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:ni(e,t)?1:-1)[0],_b=Object.keys(ke).sort((i,e)=>ni(i,e)?-1:1),vt=({width:i,height:e})=>{const t=Math.min(i,e),s=Math.max(i,e);return _b.find(r=>{const n=ke[r];return n.width>=s&&n.height>=t})},wb=i=>ke[i].height,rs=i=>i===exports.VideoQuality.INVARIANT;class Q{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,s=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:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===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:s,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.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,Db=5,Cb=500,Jn=7e3;class Nb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new Q(O.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&s!==O.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case O.PLAYING:case O.PAUSED:case O.READY:break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case O.PLAYING:break;case O.PAUSED:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.READY:this.videoState.startTransitionTo(O.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case O.PLAYING:this.videoState.startTransitionTo(O.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case O.PAUSED:break;case O.READY:this.videoState.startTransitionTo(O.PAUSED),this.videoState.setState(O.PAUSED);break;case O.STOPPED:this.videoState.startTransitionTo(O.READY),this.prepare();break;default:a.assertNever(s)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(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(r=>`stateChangeStarted$ ${JSON.stringify(r)}`)),this.videoState.stateChangeEnded$.pipe(a.map(r=>`stateChangeEnded$ ${JSON.stringify(r)}`))).subscribe(r=>this.log({message:`[videoState] ${r}`})));const t=(r,n)=>this.subscription.add(r.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const r=new a.Subject;e.add(r.pipe(a.debounce(Cb)).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===C.Applying||Math.abs(l-n)>Ib)&&r.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Db&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(O.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(O.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PAUSED||e===O.PLAYING)&&(this.videoState.setState(O.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===O.PLAYING||e===O.PAUSED)&&(this.videoState.setState(O.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===O.READY&&this.videoState.setState(O.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==O.STOPPED&&this.videoState.setState(O.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=s[e];a.assertNonNullable(c);const h=kb(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=Nt(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===C.Applying||s.state===C.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(Jn).subscribe(()=>n(`timeout(${Jn})`)))});Ts(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}class Kn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,n=s.length;r<n;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,n=s.length;r<n;r++){const o=s[r];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class Hl extends Kn{constructor(){super(),this.listeners||Kn.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 Gl=class{constructor(){Object.defineProperty(this,"signal",{value:new Hl,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Gl.prototype[Symbol.toStringTag]="AbortController",Hl.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 xb(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!Yl({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(m){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((m,v)=>{c.addEventListener("abort",()=>v(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Es=Yl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),ql=Es?xb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,xt=Es?ql.fetch:window.fetch;Es?ql.Request:window.Request;const dt=Es?Gl:window.AbortController,ei=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class oi{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:s}=e.request,r=(t=this.dashJsRequestQueue.get(s))!==null&&t!==void 0?t:[];r.push(e),this.dashJsRequestQueue.set(s,r)}executeNextRequests(){return J(this,void 0,void 0,function*(){for(const[e,t]of this.dashJsRequestQueue.entries()){const s=this.activeRequests.get(e);if(s){t.length&&this.onBigRequestProgress(s);const r=t[0];if(!r||!r.request.range)continue;const[n,o]=ei(r.request);if(n>=s.from&&o<=s.to)continue;this.activeRequests.delete(e)}if(t.length){const r=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,r)}}})}abort(e){var t;if(e){const{request:s}=e,r=((t=this.dashJsRequestQueue.get(s.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(s.url);r&&n&&n.abortController.abort()}else for(const{abortController:s}of this.activeRequests.values())s.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const s=t.map(ei),r=s[0][0];let n=s[0][1];for(let f=1;f<s.length&&n<this.params.minDataSize;f++){const m=s[f][1];m-r<=2*this.params.minDataSize&&(n=Math.max(n,m))}r===0?n=Math.max(n,r+this.params.minInitSize):n=Math.max(n,r+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${r}-${n}`);const l=o.toString(),d=new dt,u=d.signal,c={url:e,from:r,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var m,v;throw(v=(m=this.params).onError)===null||v===void 0||v.call(m,{id:"BigRequestParsing",category:a.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return xt(l,{signal:u}).then(f=>{var m,v,p;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[b,S]=f.body.tee();(v=(m=this.params).onDownloadStream)===null||v===void 0||v.call(m,S);const y=b.getReader(),k=parseInt((p=f.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||n-r+1;c.data=new ArrayBuffer(k);const E=new Uint8Array(c.data),T=({done:_,value:F})=>J(this,void 0,void 0,function*(){_?this.onBigRequestProgress(c):F&&(E.set(F,c.loaded),c.loaded+=F.byteLength,this.onBigRequestProgress(c),yield y==null?void 0:y.read().then(T,oi.suppressStreamErrors).catch(h))});y==null||y.read().then(T,oi.suppressStreamErrors).catch(h)},oi.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:s,loaded:r,data:n,response:o}){var l,d,u,c,h,f,m,v;if(!this.activeRequests.has(e)||!n)return;const p=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const b of p){const{request:S}=b,[y,k]=ei(S),E=y>=t&&k<=t+r,T=t>=y&&t+r<k,_=n.slice(y-t,Math.min(k-t+1,r));if((E||T)&&(S.requestStartDate=(d=S.requestStartDate)!==null&&d!==void 0?d:new Date,S.firstByteDate=(u=S.firstByteDate)!==null&&u!==void 0?u:new Date,S.bytesLoaded=_.byteLength,S.bytesTotal=s-t),E){S.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(x=>x!==b)),(h=b.success)===null||h===void 0||h.call(b,_,"",e);const F=o?Array.from(o.headers.entries()).map(([x,I])=>`${x}: ${I}`).join(`\r
|
|
7
|
-
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(S,e,(m=o==null?void 0:o.status)!==null&&m!==void 0?m:200,F,[])}else T&&((v=b.progress)===null||v===void 0||v.call(b,{loaded:r,total:s-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:s},r){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:r}),!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]=ei(c.request);(h>=t&&h<s||f>t&&f<=s)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(r)))}if(this.activeRequests.delete(e),r)throw r}onBigRequestAbort({url:e,from:t,to:s}){var r,n;if(!this.activeRequests.has(e))return;const o=(r=this.dashJsRequestQueue.get(e))!==null&&r!==void 0?r:[];for(const l of o){const[d,u]=ei(l.request);(d>=t&&d<s||u>t&&u<=s)&&((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 as{constructor(e,t,s){this.baseLoader=e,this.config=s,this.bigRequest=t,t.setMetrics(s.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(as.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;as.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Ob=(i,e)=>t=>({create:s=>{const r=i(t).create(s);return new as(r,e,s)}}),Lb=(i,e)=>{const t=new oi(e);return i.extend("SchemeLoaderFactory",function(){const{parent:s}=this,r=s.getLoader;return{getLoader:n=>{const o=r(n);return Ob(o,t)}}},!0),()=>t.destroy()};var Bb=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&s&&(e==null||e())}}},!0)},Mb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,s=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,m,v,p;const b=bi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(k=>k.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const k=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(m=E!=null?E:k*1e3)!==null&&m!==void 0?m:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const S=(v=b["x-delivery-type"])!==null&&v!==void 0?v:exports.HttpConnectionType.HTTP1,y=(p={1:!0,0:!1}[b["x-reused"]])!==null&&p!==void 0?p:void 0;s.next(S),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const m=f.onload,v=f.progress;f.onload=function(...p){return d(this),m(...p)},f.progress=function(...p){return u(this),v(...p)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},Ot=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Vb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Ot}),!0),Fb=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,n]=s.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(s.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),s.request.url=o.toString(),s.request.range=void 0}t(s)}}},!0)};const xe=(i,e,t,{equal:s=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=i.getState();s(c,h)&&i.setState(c)},n)),s(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},bt=(i,e,t)=>xe(e,()=>i.loop,s=>{a.isNonNullable(s)&&(i.loop=s)},{onError:t}),ze=(i,e,t,s)=>xe(e,()=>({muted:i.muted,volume:i.volume}),r=>{a.isNonNullable(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),et=(i,e,t,s)=>xe(e,()=>i.playbackRate,r=>{a.isNonNullable(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Ub=i=>["__",i.language,i.label].join("|"),jb=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class Le{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,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(xe(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{a.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="external"))),onError:r})),this.subscription.add(xe(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:r})),this.subscription.add(xe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();this.select(s)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),a.filterChanged((s,r)=>s.length===r.length&&s.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),a.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),a.filterChanged()).subscribe(this.current$));const t=s=>{var r,n;return this.applyCueSettings((n=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(s=>{var r,n;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const m=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;m&&m.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Le.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id!==""?e.id:Ub(e);return this.externalTracks.has(r)?{id:r,type:"external",language:t,label:s,url:this.externalTracks.get(r).url}:{id:r,type:"internal",language:t,label:s}}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(s=>s.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"),s=>s.getAttribute("id")===e);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var We=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var zl=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const qr=3;class Hb{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<qr&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||qr))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?s(t,n):l?s(r,e):r<e&&n>t?(s(t,n),s(r,e)):s(r,n))})}destroy(){this._buffer=[]}}var Wl=(i,e,t=qr)=>{let s=0,r=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,r=l,!t)return{from:s,to:r};for(let d=n-1;d>=0;d--)i.end(d)+t>=s&&(s=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=r&&(r=i.end(d))}}return{from:s,to:r}};const Gb=50,Yb=i=>i.webkitAudioDecodedByteCount!=="undefined"?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!=="undefined"?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,Qe=i=>{const e=v=>a.fromEvent(i,v).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=a.merge(...t.map(v=>a.fromEvent(i,v))).pipe(a.map(v=>v.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Wl(i.buffered,i.currentTime))),n=zl()?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(Gb),a.map(()=>Yb(i))),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var v;const p=i.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(v=i.error)!==null&&v!==void 0?v:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let m;return c.subscribe(v=>{i.loop&&a.isNonNullable(m)&&a.isNonNullable(v)&&m>=i.duration-f&&v<=f&&h.next(m),m=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$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:l,isAudioAvailable$:o,playbackRateState$:d}},ya=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var qb=_e,zb=vs,Wb=aa,Qb=ra;qb({target:"Array",proto:!0},{at:function(e){var t=zb(this),s=Wb(t),r=Qb(e),n=r>=0?r:s+r;return n<0||n>=s?void 0:t[n]}});var Jb=Sa,Kb=Jb("Array","at"),Xb=Kb,Zb=Xb,eS=Zb,tS=eS,Fe=tS;let Ta=!1,Ue={};const iS=i=>{Ta=i},sS=()=>{Ue={}},rS=i=>{i(Ue)},Vi=(i,e)=>{var t;Ta&&(Ue.meta=(t=Ue.meta)!==null&&t!==void 0?t:{},Ue.meta[i]=e)};class Ce{constructor(e){this.name=e}next(e){var t,s;if(!Ta)return;Ue.series=(t=Ue.series)!==null&&t!==void 0?t:{};const r=(s=Ue.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),Ue.series[this.name]=r}}const aS=new Ce("best_bitrate"),nS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class oS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const yi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,m;const v=s.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,p=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*s.containerSizeFactor,height:e.height*v*s.containerSizeFactor},b=p&&vt(p),S=s.considerPlaybackRate&&a.isNonNullable(l)?l:1,y=i.filter(D=>!rs(D.quality)).sort((D,w)=>Ki(D.quality,w.quality)?-1:1),k=(h=Fe(y,-1))===null||h===void 0?void 0:h.quality,E=(f=Fe(y,0))===null||f===void 0?void 0:f.quality,T=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&ni(r.max,r.min)||a.isNonNullable(r.min)&&E&&Ki(r.min,E)||a.isNonNullable(r.max)&&k&&ni(r.max,k),_=S*nS(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),x=y.filter(D=>{const w=b?ni(D.quality,b):!0,G=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(D.bitrate)?t-n>=D.bitrate*_:!0,K=s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!rs(d.quality)&&(o!=null?o:0)<s.minBufferToSwitchUp&&Ki(D.quality,d.quality),te=T||(a.isNullable(r.max)||Ab(D.quality,r.max))&&(a.isNullable(r.min)||Pb(D.quality,r.min));return w&&G&&!K&&te})[0];x&&x.bitrate&&aS.next(x.bitrate);const I=(m=x!=null?x:y[Math.ceil((y.length-1)/2)])!==null&&m!==void 0?m:i[0],U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=s.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const D=u.last;return u==null||u.recordSwitch(D),D}return u==null||u.recordSwitch(I),I};var ce=i=>new URL(i).hostname;const lS=300,ns=(i,e=lS)=>new a.Observable(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(Cu(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()}),uS=5e3,ti={};var L;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const se=(i,e)=>new a.Observable(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class Xn{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(L.DOWNLOADING_LIB),this.textTracksManager=new Le,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 t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===L.DOWNLOADING_LIB||t===L.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&t!==L.STOPPED&&s!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),s){case exports.PlaybackState.STOPPED:{switch(t){case L.STOPPED:break;case L.PLAYING:case L.PAUSED:case L.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case L.STOPPED:this.prepare();break;case L.PLAYING:case L.PAUSED:case L.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case L.PLAYING:break;case L.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 L.READY:this.play();break;case L.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case L.PLAYING:this.pause(),this.liveOffset.pause();break;case L.PAUSED:break;case L.READY:this.videoState.setState(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case L.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(s)}},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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),uS);Ts(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ti.MediaPlayer=r.MediaPlayer,ti.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(ti.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(ti.Debug,"dashjs not loaded"),this.player=ti.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(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_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Lb(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(L.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=p=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:p})},r=(p,b)=>this.subscription.add(p.subscribe(b,s));r(ns(this.video),this.elementSize$),r(se(this.player,"error").pipe(a.map(p=>{const b=typeof p.error=="object"?p.error.code:p.error,S=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${b}`,message:S}})),e.error$),r(se(this.player,"playbackError").pipe(a.map(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const n=se(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:p})=>p==="video"),a.map(({newQuality:p})=>{var b;return(b=this.videoTracks.find(({bitrateInfo:S})=>S.qualityIndex===p))===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:p})=>p===L.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(xe(t.videoTrack,()=>{var p,b;const S=this.player.getQualityFor("video");return(b=(p=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===S))===null||p===void 0?void 0:p.track)===null||b===void 0?void 0:b.id},p=>{var b;if(a.isNullable(p))return;const S=(b=this.videoTracks.find(({track:y})=>y.id===p))===null||b===void 0?void 0:b.bitrateInfo;S&&this.player.setQualityFor("video",S.qualityIndex)},{changed$:n.pipe(a.map(p=>p==null?void 0:p.id)),onError:s}))},s)),this.subscription.add(xe(t.autoVideoTrackSwitching,()=>{var p,b,S;return(S=(b=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||S===void 0?void 0:S.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:s})),r(se(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:p})=>p==="video"),a.map(({state:p})=>p==="bufferStalled")),e.isBuffering$),r(se(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:b}})=>{var S,y;const k=this.player.getDashMetrics(),E=k.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),T=(S=k.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,_=(y={1:!0,0:!1}[E])!==null&&y!==void 0?y:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(_),e.hostname$.next(ce(b))}),r(se(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:b,availableFrom:S}}})=>{this.isLive$.next(b),this.availableFrom$.next(S.getTime()),b||e.duration$.next(p),this.videoTracks=[];const y=this.player.getQualityFor("video");let k;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),_=vt(E),F=E.bitrate/1e3,x={width:E.width,height:E.height},I=this.frameRatesByFrameHeight[E.height];if(_){const U={id:T,quality:_,bitrate:F,size:x,fps:I};this.videoTracks.push({track:U,bitrateInfo:E}),E.qualityIndex===y&&(k=U)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),k&&e.currentVideoTrack$.next(k),this.videoState.setState(L.STREAM_INITIALIZED),this.videoState.startTransitionTo(L.READY)}),r(se(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const b=p.requestEndDate.getTime()-p.firstByteDate.getTime(),S=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(S,b)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=yi(this.videoTracks.map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),S=this.videoTracks.find(({track:y})=>y===b);S!=null&&S.bitrateInfo&&this.player.setQualityFor("video",S==null?void 0:S.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:p})=>p),a.map(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const o=se(this.player,"playbackTimeUpdated").pipe(a.map(({time:p})=>p!=null?p:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:p,currentTime:b})=>this.params.output.liveTime$.next(p+b*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(se(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(se(this.player,"playbackEnded"),e.endedEvent$),r(se(this.player,"playbackProgress").pipe(a.map(()=>Wl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(se(this.player,"playbackPlaying"),()=>{this.videoState.setState(L.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),r(se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(se(this.player,"playbackPaused"),()=>{this.videoState.setState(L.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),r(se(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===L.READY&&this.videoState.setState(L.READY)}),r(this.isLive$,e.isLive$),r(ns(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Mb(this.player);r(c,this.params.output.httpConnectionType$),r(h,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(a.once()),e.firstBytesEvent$),r(se(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(p=>p<60))}),({isLive:p,isShort:b})=>{const S=!p&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:S}}})}),r(o.pipe(a.filter(p=>p>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(se(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(se(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),this.subscription.add(bt(this.video,t.isLooped,s));const{volumeState$:f,looped$:m,playbackRateState$:v}=Qe(this.video);this.subscription.add(ze(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(m.subscribe(e.loopedEvent$)),this.subscription.add(et(this.video,t.playbackRate,v,s))}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(L.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(L.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Nt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Ct.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(L.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(L.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(s){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Ti=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}},tt=i=>J(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return i.muted=!1,console.warn(s),!1}}return!0});function oe(){return a.now()}function Ql(i){return oe()-i}function Zn(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=o=>s.test(o);return{resolve:(o,l,d=!1)=>{r(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function dS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Xi(i,e,t,s){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,m="arraybuffer",v=7e3,p=2e3,b=()=>{if(d)return;a.assertNonNullable(c);const w=Ql(c);let G;if(w<p){G=p-w,setTimeout(b,G);return}p*=2,p>v&&(p=v),o&&o.abort(),o=new r,_()};const S=w=>(n=w,D),y=w=>(h=w,D),k=()=>(m="json",D),E=()=>{if(!d){if(--u>=0){b(),s&&s();return}d=!0,h&&h(),t&&t()}},T=w=>(f=w,D),_=()=>{c=oe(),o=new r,o.open("get",i);let w=0,G,K=0;const te=()=>(a.assertNonNullable(c),Math.max(c,Math.max(G||0,K||0)));if(n&&o.addEventListener("progress",$=>{const N=oe();n.updateChunk&&$.loaded>w&&(n.updateChunk(te(),$.loaded-w),w=$.loaded,G=N)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const N=o.response.byteLength-w;N&&n.updateChunk&&n.updateChunk(te(),N)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=m,o.send(),D},D={withBitrateReporting:S,withParallel:T,withJSONResponse:k,withRetryCount:w=>(u=w,D),withRetryInterval:(w,G)=>(a.isNonNullable(w)&&(p=w),a.isNonNullable(G)&&(v=G),D),withTimeout:w=>(l=w,D),withFinally:y,send:_,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return D}const cS=100,hS=2e3,fS=500;let pS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-fS;if(t-e>hS){let s=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&s>0){const n=r*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>cS&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class mS{constructor(e,t,s,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=oe(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=oe()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Xi(t,n,()=>r("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=oe()}_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=oe();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=r,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Fi=1e4,Ui=3,vS=300,bS=2e3,SS=6e4,gS=10,yS=1,TS=500;class ES{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 pS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Zn(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=Zn(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;Boolean(e.error)&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!r||n.bitrate>r.bitrate)&&(r=n):(!s||s.bitrate>n.bitrate)&&(s=n));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{dS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new mS(Ui,Fi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,_)=>{d&&d.abort(),d=Xi(this.urlResolver.resolve(E,!1),T,_,()=>this._retryCallback()).withTimeout(Fi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ui).withFinally(()=>{d=null}).send()},m=(E,T,_)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,_,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},v=E=>{const T=s.playbackRate;s.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),s.playbackRate=E)},p=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)v(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){v(1);return}const _=oe()-1e4;let F=0;for(let I=0;I<this.bufferStates.length;I++){const U=this.bufferStates[I];E=Math.min(E,U.buf),U.ts<_&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${E} drop=${F} jitter=${this.sourceJitter}`);let x=E-yS;this.sourceJitter>=0?x-=this.sourceJitter/2:this.sourceJitter-=1,x>3?v(1.15):x>1?v(1.1):x>.3?v(1.05):v(1)}},S=E=>{let T;const _=()=>T&&T.start?T.start.length:0,F=$=>T.start[$]/1e3,x=$=>T.dur[$]/1e3,I=$=>T.fragIndex+$,U=($,N)=>({chunkIdx:I($),startTS:F($),dur:x($),discontinuity:N}),D=()=>{let $=0;if(T&&T.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,ee=N;this.sourceJitter>1&&(ee+=this.sourceJitter-1);let ie=T.dur.length-1;for(;ie>=0&&(ee-=T.dur[ie],!(ee<=0));--ie);$=Math.min(ie,T.dur.length-1-z),$=Math.max($,0)}return U($,!0)},w=$=>{const N=_();if(!(N<=0)){if(a.isNonNullable($)){for(let z=0;z<N;z++)if(F(z)>$)return U(z)}return D()}},G=$=>{const N=_(),z=$?$.chunkIdx+1:0,ee=z-T.fragIndex;if(!(N<=0)){if(!$||ee<0||ee-N>gS)return t(`Resync: offset=${ee} bChunks=${N} chunk=`+JSON.stringify($)),D();if(!(ee>=N))return U(z-T.fragIndex,!1)}},K=($,N,z)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve($,!0,this.lowLatency),N,z,()=>this._retryCallback()).withTimeout(Fi).withRetryCount(Ui).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,N)=>{K(E,z=>{if(!h())return;T=z;const ee=Boolean(T.lowLatency);ee!==this.lowLatency&&p(ee);let ie=0;for(let he=0;he<T.dur.length;++he)ie+=T.dur[he];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/T.dur.length)),r({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,$(w(N))},()=>this._handleNetworkError())},nextChunk:G}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:_}=this.params;let F=S(e.jidxUrl),x,I,U,D,w=0,G,K,te;const $=()=>{G&&(clearTimeout(G),G=void 0);const j=Math.max(TS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=w+j,de=oe(),ve=Math.min(1e4,ae-de);w=de;const it=()=>{u||h()&&F.seek(()=>{h()&&(w=oe(),N(),$())})};ve>0?G=window.setTimeout(()=>{this.paused?$():it()},ve):it()},N=()=>{let j;for(;j=F.nextChunk(D);)D=j,we(j);const ae=F.nextChunk(U);if(ae){if(U&&ae.discontinuity){_("Detected discontinuity; restarting playback"),this.paused?$():(y(),this._initPlayerWith(e));return}he(ae)}else $()},z=(j,ae)=>{if(!h()||!this.sourceBuffer)return;let de,ve,it;const Re=Je=>{window.setTimeout(()=>{h()&&z(j,ae)},Je)};if(this.sourceBuffer.updating)_("Source buffer is updating; delaying appendBuffer"),Re(100);else{const Je=oe(),st=T.currentTime;!this.paused&&T.buffered.length>1&&K===st&&Je-te>500&&(_("Stall suspected; trying to fix"),this._fixupStall()),K!==st&&(K=st,te=Je);const Ht=this._getBufferSizeSec();if(Ht>30)_(`Buffered ${Ht} seconds; delaying appendBuffer`),Re(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Je,buf:Ht}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(St){if(St.name==="QuotaExceededError")_("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(de=this.sourceBuffer.buffered.start(0),ve=st,ve-de>4&&this.sourceBuffer.remove(de,ve-3)),Re(1e3);else throw St}}},ee=()=>{I&&x&&(_([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(U)]),z(I,function(){I=null,N()}))},ie=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),he=j=>{h()&&m(ie(j),(ae,de)=>{if(h()){if(de/=1e3,I=ae,U=j,o=j.startTS,de){const ve=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}ee()}},()=>this._handleNetworkError())},we=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(j),!1)))},jt=j=>{h()&&(e.cachedHeader=j,z(j,()=>{x=!0,ee()}))};n=!0,F.seek(j=>{if(h()){if(w=oe(),!j){$();return}D=j,!a.isNullable(E)||j.startTS>E?he(j):(U=j,N())}},E),e.cachedHeader?jt(e.cachedHeader):f(e.headerUrl,jt,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,m,v;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(m=this._getBufferSizeSec(),v=h/this.bitrate,m>10&&v>.8||m>15&&v>.5||m>20&&v>.3)){e(`Not switching: buffer=${Math.floor(m)}; 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,m)=>{const v=oe();if(this.chunkRateEstimator.addInterval(f,v,m)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:v-f,speed:b}),!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&&Ql(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const m=n.updateChunk(h,f);return m&&u(),m},notifySwitch:h=>{const f=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Fi).withRetryCount(Ui).withRetryInterval(vS,bS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;tt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},SS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var B;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const $S=[B.PAUSED,B.PLAYING,B.READY],PS=[B.PAUSED,B.PLAYING,B.READY];class AS{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(B.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Le,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ga,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),m=(o=Ti(h.name))!==null&&o!==void 0?o:vt(h.video),v=h.bitrate/1e3,p=Object.assign({},h.video);if(!m)continue;const b={id:f,quality:m,bitrate:v,size:p};c.push({track:b,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)===B.MANIFEST_READY&&this.videoState.setState(B.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{var r;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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(B.STOPPED));return}if(!o){if(PS.includes(n)){const c=(r=this.params.desiredState.videoTrack.getTransition())===null||r===void 0?void 0:r.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===C.Requested&&$S.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_READY),this.dash.attachSource(Nt(this.params.source.url));return;case B.MANIFEST_READY:this.videoState.startTransitionTo(B.READY),this.prepare();break;case B.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(B.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(B.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(B.PAUSED)})}return;case B.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(B.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case B.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.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(B.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=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=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(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 s=Qe(this.video);this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===B.READY&&this.videoState.setState(B.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(B.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(bt(this.video,this.params.desiredState.isLooped,t)).add(ze(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(et(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:r}})=>{const n=r&&wb(r);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var n;switch(r.to){case B.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case B.MANIFEST_READY:case B.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 B.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case B.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new ES({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:(n=yi(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 s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=-e,s=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(s),this.dash.reinit(Nt(this.params.source.url,s))}}var Jl=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},ut=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,n=i.end(s)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const kS=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 Kl{constructor(e,t=[],s,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,n,o,l,d,u;if(a.assertNonNullable(this._xhr),((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=bi(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(_S(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class os{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const m=p=>{r(os._str2ua(p.substr(d))),d=p.length};let v=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(v=Ot(v)),this._lastXhr=new Kl(v,e.failoverHosts,p=>{this._lastXhr=void 0,m(p);const b=Date.now()-u;this._params.onBandwidthChange({size:p.length,duration:b,speed:8*p.length/(b/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),n==null||n()},p=>{if(p.length-d>l&&m(p),h===0){h=Date.now();return}f=p.length-c;const b=Date.now()-h;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,c=p.length,h=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},o,(p,b,S)=>this._params.onError(p,b,S))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=os._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class wS{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},r=t.exec(e),n=(r==null?void 0:r[1])==="-"?-1:1,o={years:s(r==null?void 0:r[2],n),months:s(r==null?void 0:r[3],n),weeks:s(r==null?void 0:r[4],n),days:s(r==null?void 0:r[5],n),hours:s(r==null?void 0:r[6],n),minutes:s(r==null?void 0:r[7],n),seconds:s(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Ot(s)),new Kl(s,t,r=>{this.attachManifest(r,t,kS(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,m,v,p,b,S,y,k,E,T,_,F,x,I,U,D,w;const G=u.getElementsByTagName("SegmentBase")[0],K=G&&o(G,"indexRange").split("-"),te=G&&G.getElementsByTagName("Initialization")[0],$=te&&o(te,"range").split("-");if(!$||!K){const we=u.parentElement;if((we==null?void 0:we.getAttribute("contentType"))==="text"){const jt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(s?s+"/":"")+((v=(m=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||m===void 0?void 0:m[0])===null||v===void 0?void 0:v.data),ae=(p=we.getAttribute("lang"))!==null&&p!==void 0?p:void 0;j&&d.push({id:jt,url:j,language:ae})}return}const N=.1,z=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),ee=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const he=(y=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&y!==void 0?y:void 0;ie=he?ya(he):void 0,l.push({width:Number((k=u.attributes.getNamedItem("width"))===null||k===void 0?void 0:k.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(_=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&_!==void 0?_:void 0,mimeType:(x=(F=u.attributes.getNamedItem("mimeType"))===null||F===void 0?void 0:F.value)!==null&&x!==void 0?x:void 0,fps:ie,bufferSize:N*z/8,bufferLength:N,name:(U=(I=u.attributes.getNamedItem("okQuality"))===null||I===void 0?void 0:I.value)!==null&&U!==void 0?U:void 0,id:(w=(D=u.attributes.getNamedItem("id"))===null||D===void 0?void 0:D.value)!==null&&w!==void 0?w:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");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(this._representations)}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const m=u+(o.getUint32(n,!1)&2147483647),v=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:v/l,fromOffset:u,toOffset:m-1}),u=m,d=v}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const m=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),m)}const c=this._appendVector[String(u.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const m=this._buffer.getByTime(this._video.currentTime);if(!m){this._onDashCallback("buffering");return}h=m.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==m.to&&(n=m.to,window.setTimeout(()=>{try{const v=this._buffer.getNextWithGap(m);v&&(this._video.currentTime=v.from)}catch(v){throw this._params.onError("GapSyncError",`Seek Error ${String(v)}`,v),v}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new os({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||l(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<s.to+n){const o=this._findRef(r.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<s.length;n++){const o=s[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=s[s.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var M;(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"})(M||(M={}));const RS=[M.PAUSED,M.PLAYING];class IS{constructor(e){this.videoState=new Q(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Le,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=t=>{var s,r,n;const o=[];for(const l of t){const d=(r=(s=l.name)!==null&&s!==void 0?s:l.id)!==null&&r!==void 0?r:l.height.toString(10),u=(n=l.name&&Ti(l.name))!==null&&n!==void 0?n:vt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const m={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:m,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:n})=>n===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==M.STOPPED&&(this.videoState.startTransitionTo(M.STOPPED),this.dash.destroy(),this.video.setAttribute("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(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!s)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===C.Requested&&RS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:r===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Hb(this.video),this.dash=new wS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Qe(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(bt(this.video,t.isLooped,s)),this.subscription.add(ze(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),o(ns(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.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(),m=this.params.desiredState.videoTrack.getState(),v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),b=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!b&&a.isNonNullable(m))S=m;else{const y=ut(this.video.buffered,this.video.currentTime*1e3),k=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/k,1);S=(d=yi(h.map(({track:T})=>T),{container:p,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,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(S)?(u=h.find(({track:y})=>y.id===S))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,s)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?l.height<=d.height:l===d)).subscribe(l=>{const d=ut(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(ce(l.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Jl(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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(){tt(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var ge;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ge||(ge={}));var ls;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ls||(ls={}));var ye;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ye||(ye={}));var H;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(H||(H={}));var Lt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Lt||(Lt={}));var us;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(us||(us={}));var zr=(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 s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},CS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",eo=CS?DS:window.requestIdleCallback;var lr,ur;let Xl=!1;try{Xl=zl()&&parseInt((ur=(lr=navigator.userAgent.match(/Version\/(\d+)/))===null||lr===void 0?void 0:lr[1])!==null&&ur!==void 0?ur:"",10)<16}catch(i){console.error(i)}class NS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return J(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return J(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return J(this,void 0,void 0,function*(){return new Promise(t=>{let s;Xl&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask)}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"&&s==="remove"||this.error$.next({id:`BufferTaskQueue:${s}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var to=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Be{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const r=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,r}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class Zl extends Be{}class xS extends Be{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class OS extends Be{parseChildrenBoxes(){return Ut(this.content)}}class LS extends Be{constructor(e){super(e),this.data=this.content}}class Ei extends Be{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class BS extends Ei{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class MS extends Be{parseChildrenBoxes(){return Ut(this.content)}}class VS extends Be{parseChildrenBoxes(){return Ut(this.content)}}var lt;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(lt||(lt={}));class FS extends Ei{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=lt.MONOSCOPIC;break;case 1:this.stereoMode=lt.TOP_BOTTOM;break;case 2:this.stereoMode=lt.LEFT_RIGHT;break;case 3:this.stereoMode=lt.STEREO_CUSTOM;break;case 4:this.stereoMode=lt.RIGHT_LEFT;break}this.cursor+=1}}class US extends Ei{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class jS extends Ei{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class HS extends Be{parseChildrenBoxes(){return Ut(this.content)}}class GS extends Ei{constructor(e){super(e),this.creationTime=this.readUint32(),this.modificationTime=this.readUint32(),this.trackId=this.readUint32(),this.cursor+=4,this.duration=this.readUint32(),this.cursor+=8,this.layer=this.readUint16(),this.alternateGroup=this.readUint16(),this.cursor+=2,this.cursor+=2,this.matrix=[[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()],[this.readUint32(),this.readUint32(),this.readUint32()]],this.width=this.readUint32(),this.height=this.readUint32()}}class YS extends Be{parseChildrenBoxes(){return Ut(this.content)}}class qS extends Be{parseChildrenBoxes(){return Ut(this.content)}}const zS={ftyp:xS,moov:OS,mdat:LS,sidx:BS,trak:MS,mdia:HS,tkhd:GS,minf:YS,sv3d:VS,st3d:FS,prhd:US,proj:qS,equi:jS,unknown:Zl};class WS{createBox(e,t){const s=zS[e];return s?new s(t):new Zl(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return $s.createBox(s,new DataView(e.buffer,e.byteOffset))}}const $s=new WS;function si(i,e){const t=new TextDecoder("ascii");let s=i.byteOffset,r=[];for(;s<i.byteLength;){const n=t.decode(new DataView(i.buffer,s,1));if(n===e[r.length]?r.push(n):r=[],r.length===4&&r.join("")===e){const l=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+l>i.byteLength?null:$s.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function QS(i,e){const t=[];let s=i.byteOffset;for(;s<i.byteLength;){const r=si(new DataView(i.buffer,s,i.byteLength),e);if(r)t.push(r),s+=r.source.byteOffset+r.source.byteLength;else break}return t}function Ut(i){const e=[];let t=0;for(;t<i.byteLength;){const s=$s.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const JS=new TextDecoder("ascii"),KS=i=>JS.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",XS=i=>{const e=$s.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:H.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},ZS=i=>{const e=QS(i,"mdat");if(e.length){const t=e.reduce((s,r)=>s+r.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},eg=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(si(i,"sv3d")){e.is3dVideo=!0;const s=si(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=si(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=si(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},tg={validateData:KS,parseInit:eg,getIndexRange:()=>{},parseSegments:XS,parseFeedableSegmentChunk:ZS};var g;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(g||(g={}));var A;(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"})(A||(A={}));const io={[g.EBML]:{type:A.Master},[g.EBMLVersion]:{type:A.UnsignedInteger},[g.EBMLReadVersion]:{type:A.UnsignedInteger},[g.EBMLMaxIDLength]:{type:A.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[g.DocType]:{type:A.String},[g.DocTypeVersion]:{type:A.UnsignedInteger},[g.DocTypeReadVersion]:{type:A.UnsignedInteger},[g.Void]:{type:A.Binary},[g.Segment]:{type:A.Master},[g.SeekHead]:{type:A.Master},[g.Seek]:{type:A.Master},[g.SeekID]:{type:A.Binary},[g.SeekPosition]:{type:A.UnsignedInteger},[g.Info]:{type:A.Master},[g.TimestampScale]:{type:A.UnsignedInteger},[g.Duration]:{type:A.Float},[g.Tracks]:{type:A.Master},[g.TrackEntry]:{type:A.Master},[g.Video]:{type:A.Master},[g.Projection]:{type:A.Master},[g.ProjectionType]:{type:A.UnsignedInteger},[g.ProjectionPrivate]:{type:A.Master},[g.Chapters]:{type:A.Master},[g.Cluster]:{type:A.Master},[g.Timestamp]:{type:A.UnsignedInteger},[g.SilentTracks]:{type:A.Master},[g.SilentTrackNumber]:{type:A.UnsignedInteger},[g.Position]:{type:A.UnsignedInteger},[g.PrevSize]:{type:A.UnsignedInteger},[g.SimpleBlock]:{type:A.Binary},[g.BlockGroup]:{type:A.Master},[g.EncryptedBlock]:{type:A.Binary},[g.Attachments]:{type:A.Master},[g.Tags]:{type:A.Master},[g.Cues]:{type:A.Master},[g.CuePoint]:{type:A.Master},[g.CueTime]:{type:A.UnsignedInteger},[g.CueTrackPositions]:{type:A.Master},[g.CueTrack]:{type:A.UnsignedInteger},[g.CueClusterPosition]:{type:A.UnsignedInteger},[g.CueRelativePosition]:{type:A.UnsignedInteger},[g.CueDuration]:{type:A.UnsignedInteger},[g.CueBlockNumber]:{type:A.UnsignedInteger},[g.CueCodecState]:{type:A.UnsignedInteger},[g.CueReference]:{type:A.Master},[g.CueRefTime]:{type:A.UnsignedInteger}},eu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=ds(i,t),r=s in io,n=r?io[s].type:A.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=ds(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let m;return f+h>i.byteLength?m=new DataView(i.buffer,i.byteOffset+f):m=new DataView(i.buffer,i.byteOffset+f,h),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:m,valueSize:h}},ds=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ne=(i,e)=>{switch(e){case A.SignedInteger:return i.getInt8(0);case A.UnsignedInteger:return ds(i);case A.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case A.String:return new TextDecoder("ascii").decode(i);case A.UTF8:return new TextDecoder("utf-8").decode(i);case A.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case A.Master:return i;case A.Binary:return i;default:a.assertNever(e)}},Bt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=eu(s);if(!e(r))return;r.type===A.Master&&Bt(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},ig=i=>{if(i.getUint32(0)!==g.EBML)return!1;let e,t,s;const r=eu(i);return Bt(r.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=Ne(l,o):n===g.DocType?t=Ne(l,o):n===g.DocTypeReadVersion&&(s=Ne(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},tu=[g.Info,g.SeekHead,g.Tracks,g.TrackEntry,g.Video,g.Projection,g.ProjectionType,g.ProjectionPrivate,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],sg=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],rg=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Bt(i,({tag:f,type:m,value:v,valueSize:p})=>{if(f===g.SeekID){const b=Ne(v,m);u=ds(b)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=v.byteOffset,t=v.byteOffset+p):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?s=Ne(v,m):f===g.Duration?r=Ne(v,m):f===g.SeekPosition&&u===g.Cues?d=Ne(v,m):f===g.Tracks?Bt(v,({tag:b,type:S,value:y})=>b===g.ProjectionType?(c=Ne(y,S)===1,!1):!0):n&&o&&tu.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},ag=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ng=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Bt(i,({tag:l,type:d,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&r(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=Ne(u,d));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=Ne(u,d));break;default:t&&tu.includes(l)&&(s=!0)}return!(t&&s)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:H.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}}})},og=i=>{let e=0,t=!1;try{Bt(i,s=>s.tag===g.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):sg.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},lg={validateData:ig,parseInit:rg,getIndexRange:ag,parseSegments:ng,parseFeedableSegmentChunk:og};class so{constructor(e,t,s,r,{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.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new dt,this.destroyAbortController=new dt,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 NS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},p=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:p}))),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(p=>{if(!this.sourceBuffer)return;const b=Math.min(this.bufferLimit,to(this.sourceBuffer.buffered)*.8);this.bufferLimit=b,this.pruneBuffer(this.getCurrentPosition(),p)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(p=>this.error$.next(p))),yield yield R(this.loadInit(c,"high",!0));const h=this.initData.get(c.id),f=this.segments.get(c.id),m=this.parsedInitData.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 R(void 0);let v=0;for(const p of f)p.time.from-v>0&&this.gaps.push({representation:c.id,from:v,to:p.time.from}),v=p.time.to;a.isNonNullable(c.duration)&&c.duration-v>0&&this.gaps.push({representation:c.id,from:v,to:c.duration}),yield yield R(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.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 R(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 R(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield R(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield R(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=s,s){case Lt.MP4:this.containerParser=tg;break;case Lt.WEBM:this.containerParser=lg;break;default:a.assertNever(s)}this.initData=new Map(r.map(u=>[u.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.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 dt,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),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=ut(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&to(this.sourceBuffer.buffered)>=this.bufferLimit){const u=ut(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=Fe(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===H.FED&&!l.length&&ut(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Fe(s,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&this.mediaSource.readyState==="open"&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:m}},v)=>{const p=f<=s&&m>=s,b=f>s||p||v===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+S||m<=s+S;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&b&&y&&this.sourceBuffer&&!zr(this.sourceBuffer.buffered,s))&&b&&y});if(r===-1)return[];if(t!==ye.BYTE_RANGE)return e.slice(r,r+1);const n=e;let o=0,l=0;const d=[],u=this.preloadOnly?0:this.tuning.dash.segmentRequestSize,c=this.preloadOnly?this.forwardBufferTarget:0;for(let h=r;h<n.length&&(o<=u||l<=c);h++){const f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,s="auto"){return J(this,void 0,void 0,function*(){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case ye.BYTE_RANGE:{r=t.segmentReference.url,n={from:Fe(e,0).byte.from,to:Fe(e,-1).byte.to};break}case ye.TEMPLATE:{const u=Fe(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=H.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 R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,u=>{for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=ut((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=H.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const m of this.representations.values())if(m.id!==t)for(const v of(f=this.segments.get(m.id))!==null&&f!==void 0?f:[])v.status===H.FED&&v.time.from===h.segment.time.from&&v.time.to===h.segment.time.to&&(v.status=H.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,m=u===ye.BYTE_RANGE,v=m?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!m||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const b=m?f.byte.from-s:0,S=m?f.byte.to-s:e.byteLength,y=b<r,k=S<=r;if(f.status===H.DOWNLOADING&&y&&k){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+b,v);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(v,r-b),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===v?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(_=>{if(n.aborted)o();else if(_)h.fedBytes+=T.byteLength,h.fedBytes===v&&l(h);else{if(h.feedingBytes<v)return;o()}}))}}}abortSegment(e){e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.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[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=eo(()=>Ts(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return J(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Ae(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>{if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,c),this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,s=!1){return J(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let r=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;r+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===H.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){r=0,n=1/0,o=-1/0;for(const u of this.segments.values())for(const c of u){if(c.time.from<e+Math.min(this.forwardBufferTarget,this.bufferLimit)||r>t)break;c.status===H.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 m of f)if(m.status===H.NONE&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===H.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 s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>=1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=eo(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:n})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:n}=r;if(n!==H.FED&&n!==H.PARTIALLY_EJECTED)continue;const o=Math.floor(r.time.from),l=Math.ceil(r.time.to),d=e.some(c=>c.from-t<=o&&c.to+t>=l),u=e.filter(c=>o>=c.from-t&&o<=c.to+t||l>=c.from-t&&l<=c.to+t);d||(u.length===1?r.status=H.PARTIALLY_EJECTED:r.status=H.NONE)}}}var It;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(It||(It={}));class ug{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new dt,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(r){return Ae(this,arguments,function*(){let n=r;this.requestQuic&&(n=Ot(n));const o=yield yield R(xt(n,{signal:this.abortAllController.signal}).catch(ii));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(r,{rangeMethod:n=this.compatibilityMode?It.HEADER:It.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,m,v;return Ae(this,arguments,function*(){let p=r;const b=new Headers;if(o)switch(n){case It.HEADER:{b.append("Range",`bytes=${o.from}-${o.to}`);break}case It.PARAM:{const $=new URL(p,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),p=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(p=Ot(p));let S=this.abortAllController.signal;if(u){const $=new dt;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(N){ii(N)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(N){ii(N)}S=$.signal}const y=a.now(),k=yield yield R(xt(p,{priority:d,headers:b,signal:S}).catch(ii)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!k)return yield R(null);if(!k.ok||!k.body)return yield R(Promise.reject(new Error(`Fetch error ${k.status}: ${k.statusText}`)));this.onHeadersReceived(k.headers);const T=parseInt((f=k.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield yield R(k.arrayBuffer());return(m=this.throughputEstimator)===null||m===void 0||m.addRawSpeed($.byteLength,a.now()-E),l==null||l(new DataView($),$.byteLength),yield R($)}if(!l&&!c)return yield R(k.arrayBuffer());const[_,F]=k.body.tee(),x=_.getReader();c&&((v=this.throughputEstimator)===null||v===void 0||v.trackStream(F));let I=0;const U=new ArrayBuffer(T),D=new Uint8Array(U),w=new DataView(U);let G=!1;const K=$=>{G=!0,ii($)},te=a.abortable(S,function({done:$,value:N}){return Ae(this,arguments,function*(){if(I===0&&this.lastRequestFirstBytes$.next(a.now()-y),S.aborted)return yield R(void 0);$?l==null||l(w,I):N&&(D.set(N,I),I+=N.byteLength,l==null||l(w,I),yield yield R(x==null?void 0:x.read().then(te,K)))})}.bind(this));return yield yield R(x==null?void 0:x.read().then(te,K)),yield R(G?null:U)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return Ae(this,arguments,function*(){if(r.type!==ye.BYTE_RANGE)return yield R(null);const{from:d,to:u}=r.initRange;let c=d,h=u,f=!1,m,v;r.indexRange&&(m=r.indexRange.from,v=r.indexRange.to,f=u+1===m,f&&(c=Math.min(m,d),h=Math.max(v,u))),c=Math.min(c,0);const p=yield yield R(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!p)return yield R(null);const b=new DataView(p,d-c,u-c+1);if(!n.validateData(b))throw new Error("Invalid media file");const S=n.parseInit(b),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!y)throw new ReferenceError("No way to load representation index");let k;if(f)k=new DataView(p,y.from-c,y.to-y.from+1);else{const T=yield yield R(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!T)return yield R(null);k=new DataView(T)}const E=n.parseSegments(k,S,y);return yield R({init:S,dataView:new DataView(p),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return Ae(this,arguments,function*(){if(r.type!==ye.TEMPLATE)return yield R(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:H.NONE,size:void 0}));return yield R({init:{},segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Jl(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,n;return J(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case ye.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case ye.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const ii=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var dg=Ge,cg=ci,hg=ue,fg=hg("match"),pg=function(i){var e;return dg(i)&&((e=i[fg])!==void 0?!!e:cg(i)=="RegExp")},mg=vi,vg=String,bg=function(i){if(mg(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return vg(i)},Sg=qe,gg=function(){var i=Sg(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},yg=me,Tg=Oe,Eg=hs,$g=gg,ro=RegExp.prototype,Pg=function(i){var e=i.flags;return e===void 0&&!("flags"in ro)&&!Tg(i,"flags")&&Eg(ro,i)?yg($g,i):e},Ea=$e,Ag=vs,kg=Math.floor,dr=Ea("".charAt),_g=Ea("".replace),cr=Ea("".slice),wg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Rg=/\$([$&'`]|\d{1,2})/g,Ig=function(i,e,t,s,r,n){var o=t+i.length,l=s.length,d=Rg;return r!==void 0&&(r=Ag(r),d=wg),_g(n,d,function(u,c){var h;switch(dr(c,0)){case"$":return"$";case"&":return i;case"`":return cr(e,0,t);case"'":return cr(e,o);case"<":h=r[cr(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var m=kg(f/10);return m===0?u:m<=l?s[m-1]===void 0?dr(c,1):s[m-1]+dr(c,1):u}h=s[f-1]}return h===void 0?"":h})},Dg=_e,Cg=me,$a=$e,ao=Qr,Ng=re,xg=hi,Og=pg,Pt=bg,Lg=ms,Bg=Pg,Mg=Ig,Vg=ue,Fg=Vg("replace"),Ug=TypeError,iu=$a("".indexOf),jg=$a("".replace),no=$a("".slice),Hg=Math.max,oo=function(i,e,t){return t>i.length?-1:e===""?t:iu(i,e,t)};Dg({target:"String",proto:!0},{replaceAll:function(e,t){var s=ao(this),r,n,o,l,d,u,c,h,f,m=0,v=0,p="";if(!xg(e)){if(r=Og(e),r&&(n=Pt(ao(Bg(e))),!~iu(n,"g")))throw Ug("`.replaceAll` does not allow non-global regexes");if(o=Lg(e,Fg),o)return Cg(o,e,s,t);if(r)return jg(Pt(s),e,t)}for(l=Pt(s),d=Pt(e),u=Ng(t),u||(t=Pt(t)),c=d.length,h=Hg(1,c),m=oo(l,d,0);m!==-1;)f=u?Pt(t(d,m,l)):Mg(d,l,m,[],void 0,t),p+=no(l,v,m)+f,v=m+c,m=oo(l,d,m+h);return v<l.length&&(p+=no(l,v)),p}});var Gg=Sa,Yg=Gg("String","replaceAll"),qg=Yg,zg=qg,Wg=zg,Qg=Wg,lo=Qg;const uo=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},hr=(i,e)=>{let t=i;t=lo(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(s)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=lo(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Jg=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,m,v,p,b,S,y,k,E,T,_,F,x,I,U,D,w,G,K,te,$,N,z,ee,ie,he,we;const j=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},de=j.children[0],ve=de.getElementsByTagName("Period")[0],it=ve.children;let Re;const Je=de.getAttribute("mediaPresentationDuration"),st=ve.getAttribute("duration");if(Je)Re=uo(Je);else if(st){const Ie=uo(st);a.isNonNullable(Ie)&&(Re=Ie)}let Ht=0;const St=(s=(t=de.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],lu=St.includes(ls.WEBM_AS_IN_FFMPEG)||St.includes(ls.WEBM_AS_IN_SPEC)?Lt.WEBM:Lt.MP4;for(const Ie of it){const $i=Ie.getAttribute("mimeType"),uu=Ie.getAttribute("codecs"),Pa=(r=Ie.getAttribute("contentType"))!==null&&r!==void 0?r:$i==null?void 0:$i.split("/")[0],du=(o=(n=Ie.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],cu=Ie.querySelectorAll("Representation"),hu=Ie.querySelector("SegmentTemplate");if(Pa!=="text")for(const ne of cu){const Gt=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:$i,Aa=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:uu)!==null&&u!==void 0?u:"",Pi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Gt==null?void 0:Gt.split("/")[0])!==null&&h!==void 0?h:Pa,fu=(m=(f=Ie.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&m!==void 0?m:[],pu=parseInt((v=ne.getAttribute("width"))!==null&&v!==void 0?v:"",10),ka=parseInt((p=ne.getAttribute("height"))!==null&&p!==void 0?p:"",10),_a=parseInt((b=ne.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,wa=(S=ne.getAttribute("frameRate"))!==null&&S!==void 0?S:"",mu=(y=ne.getAttribute("quality"))!==null&&y!==void 0?y:void 0,vu=wa?ya(wa):void 0,bu=(k=ne.getAttribute("id"))!==null&&k!==void 0?k:(Ht++).toString(10),Su=Pi==="video"?`${ka}p`:Pi==="audio"?`${_a}Kbps`:Aa,gu=`${bu}@${Su}`,yu=(_=(T=(E=ne.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&_!==void 0?_:"",Ra=new URL(yu,e).toString(),Tu=[...St,...du,...fu];let As;const Eu=ne.querySelector("SegmentBase"),rt=(F=ne.querySelector("SegmentTemplate"))!==null&&F!==void 0?F:hu;if(Eu){const Yt=(I=(x=ne.querySelector("SegmentBase Initialization"))===null||x===void 0?void 0:x.getAttribute("range"))!==null&&I!==void 0?I:"",[qt,_s]=Yt.split("-").map(at=>parseInt(at,10)),zt={from:qt,to:_s},Wt=(U=ne.querySelector("SegmentBase"))===null||U===void 0?void 0:U.getAttribute("indexRange"),[ws,Ai]=Wt?Wt.split("-").map(at=>parseInt(at,10)):[],Qt=Wt?{from:ws,to:Ai}:void 0;As={type:ye.BYTE_RANGE,url:Ra,initRange:zt,indexRange:Qt}}else if(rt){const Yt={representationId:(D=ne.getAttribute("id"))!==null&&D!==void 0?D:void 0,bandwidth:(w=ne.getAttribute("bandwidth"))!==null&&w!==void 0?w:void 0},qt=parseInt((G=rt.getAttribute("timescale"))!==null&&G!==void 0?G:"",10),_s=(K=rt.getAttribute("initialization"))!==null&&K!==void 0?K:"",zt=rt.getAttribute("media"),Wt=($=parseInt((te=rt.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&$!==void 0?$:1,ws=hr(_s,Yt);if(!zt)throw new ReferenceError("No media attribute in SegmentTemplate");const Ai=(N=rt.querySelectorAll("SegmentTimeline S"))!==null&&N!==void 0?N:[],Qt=[];if(Ai.length){let at=Wt,nt=0;for(const Jt of Ai){const gt=parseInt((z=Jt.getAttribute("d"))!==null&&z!==void 0?z:"",10)*1e3,Kt=parseInt((ee=Jt.getAttribute("r"))!==null&&ee!==void 0?ee:"",10)||0,Xt=(he=parseInt((ie=Jt.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&he!==void 0?he:void 0;for(let Ia=0;Ia<Kt+1;Ia++){const $u=hr(zt,Object.assign(Object.assign({},Yt),{segmentNumber:at.toString(10),segmentTime:Xt.toString(10)})),Pu=Xt?Xt/qt:nt;nt+=gt/qt;const Au=nt;at++,Qt.push({time:{from:Pu,to:Au},url:$u})}}}else if(a.isNonNullable(Re)){const nt=parseInt((we=rt.getAttribute("duration"))!==null&&we!==void 0?we:"",10)/qt*1e3,Jt=Math.ceil(Re/nt);let gt=0;for(let Kt=1;Kt<Jt;Kt++){const Xt=hr(zt,Object.assign(Object.assign({},Yt),{segmentNumber:Kt.toString(10),segmentTime:gt.toString(10)}));Qt.push({time:{from:gt,to:gt+nt},url:Xt}),gt+=nt}}As={type:ye.TEMPLATE,baseUrl:Ra,initUrl:ws,segments:Qt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Pi||!Gt)continue;const ks={video:ge.VIDEO,audio:ge.AUDIO,text:ge.TEXT}[Pi];ks&&ae[ks].push({id:gu,kind:ks,segmentReference:As,profiles:Tu,duration:Re,bitrate:_a,mime:Gt,codecs:Aa,width:pu,height:ka,fps:vu,quality:mu})}}return{duration:Re,container:lu,representations:ae}},Kg=["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 Xg=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new Q(Se.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new dt,this.initManifest=a.abortable(this.destroyController.signal,function(t,s){return Ae(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Se.MANIFEST_READY);const r=yield yield R(this.fetcher.fetchManifest(s).catch(l=>this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l})));if(!r)return yield R(void 0);let n;try{n=Jg(r!=null?r:"",s)}catch(l){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return yield R(void 0);const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest=Object.assign(Object.assign({},n),{representations:bi(Object.entries(n.representations).map(([l,d])=>[l,d.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,s){return Ae(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 r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0};this.videoBufferManager=new so(ge.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new so(ge.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),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.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState(Se.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.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 ug({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(...Kg.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&&zr(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return J(this,void 0,void 0,function*(){const s={[ge.VIDEO]:this.videoBufferManager,[ge.AUDIO]:this.audioBufferManager,[ge.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),zr(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(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(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const s of this.bufferManagers)for(const r of s.gaps)s.playingRepresentation$.getValue()===r.representation&&r.from<=e&&r.to>e&&(this.element.duration*1e3-r.to<this.tuning.endGapTolerance?t.push(1/0):t.push(r.to));if(t.length){const s=Math.max(...t);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};const Zg=135,ey=76;class ty{constructor(){this.fov={x:Zg,y:ey},this.rotation={x:0,y:0,z:0}}}const At=10,co=175;class iy{constructor(e,t={}){this.rotating=!1,this.torqueLossTS=0,this.hold=!1,this.options=t,this.camera=e,this.torqueLossTS=performance.now(),this.rotationSpeed={x:0,y:0,z:0},this.rotationMoment={x:0,y:0,z:0}}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.rotation.x+e,this.camera.rotation.y+t,this.camera.rotation.z+s)}pointCameraTo(e=0,t=0,s=0){this.camera.rotation.x=e,this.camera.rotation.y=this.limitCameraRotationY(t),this.camera.rotation.z=s}setRotationSpeed(e,t,s){e===void 0&&(e=this.rotationSpeed.x),t===void 0&&(t=this.rotationSpeed.y),s===void 0&&(s=this.rotationSpeed.z),this.rotationSpeed.x=e,this.rotationSpeed.y=t,this.rotationSpeed.z=s,this.torqueLossTS=performance.now()}startRotation(){this.rotating=!0}stopRotation(e=!1){e&&this.setRotationSpeed(0,0,0),this.rotating=!1,this.torqueLossTS=performance.now()}limitCameraRotationY(e){return Math.max(-co,Math.min(e,co))}temporalFn(e){const t=100-5e-4*(e-this.torqueLossTS);return Math.sign(t)*Math.sqrt(Math.abs(t))/10}tick(e){if(!this.lastTick){this.lastTick=e;return}const s=(e-this.lastTick)/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*s*At,this.rotationSpeed.y*s*At,this.rotationSpeed.z*s*At);else{let r=0,n=0,o=0;const l=this.temporalFn(e);this.rotationSpeed.x&&(this.rotationSpeed.x=Math.sign(this.rotationSpeed.x)*Math.max(Math.abs(this.rotationSpeed.x)-l,0),r=this.rotationSpeed.x*s*At),this.rotationSpeed.y&&(this.rotationSpeed.y=Math.sign(this.rotationSpeed.y)*Math.max(Math.abs(this.rotationSpeed.y)-l,0),n=this.rotationSpeed.y*s*At),this.rotationSpeed.z&&(this.rotationSpeed.z=Math.sign(this.rotationSpeed.z)*Math.max(Math.abs(this.rotationSpeed.z)-l,0),o=this.rotationSpeed.z*s*At),this.turnCamera(r,n,o)}this.rotationSpeed.x===0&&this.rotationSpeed.y===0&&this.rotationSpeed.z===0&&this.stopRotation(),this.lastTick=e}}const sy=`
|
|
8
|
-
attribute vec2 a_vertex;
|
|
9
|
-
attribute vec2 a_texel;
|
|
10
|
-
|
|
11
|
-
varying vec2 v_texel;
|
|
12
|
-
|
|
13
|
-
void main(void) {
|
|
14
|
-
// direct vertex drawing
|
|
15
|
-
gl_Position = vec4(a_vertex, 0.0, 1.0);
|
|
16
|
-
// save texel vector to pass to fragment shader
|
|
17
|
-
v_texel = a_texel;
|
|
18
|
-
}
|
|
19
|
-
`,ry=`
|
|
20
|
-
#ifdef GL_ES
|
|
21
|
-
precision highp float;
|
|
22
|
-
precision highp int;
|
|
23
|
-
#else
|
|
24
|
-
precision mediumhp float;
|
|
25
|
-
#endif
|
|
26
|
-
|
|
27
|
-
varying vec2 v_texel; // [0..1, 0..1]
|
|
28
|
-
|
|
29
|
-
uniform sampler2D u_texture;
|
|
30
|
-
uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
|
|
31
|
-
|
|
32
|
-
const float PI = 3.14159265358979323846264;
|
|
33
|
-
const float PI_2 = PI * 0.5;
|
|
34
|
-
const float PI2 = PI * 2.0;
|
|
35
|
-
|
|
36
|
-
void main(void) {
|
|
37
|
-
// center point of output projection
|
|
38
|
-
float lambda0 = u_focus.x / 360.0; // [-0.5, 0.5]
|
|
39
|
-
float phi0 = u_focus.y / 180.0; // [-0.5, 0.5]
|
|
40
|
-
|
|
41
|
-
float x = PI2 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
|
|
42
|
-
float y = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
|
|
43
|
-
|
|
44
|
-
float p = sqrt(x * x + y * y); // rou
|
|
45
|
-
float c = atan(p);
|
|
46
|
-
float cos_c = cos(c);
|
|
47
|
-
float sin_c = sin(c);
|
|
48
|
-
|
|
49
|
-
// geo coordinates of projection
|
|
50
|
-
float lambda = lambda0 + atan(
|
|
51
|
-
x * sin_c,
|
|
52
|
-
p * cos(phi0) * cos_c - y * sin(phi0) * sin_c
|
|
53
|
-
);
|
|
54
|
-
float phi = asin(cos_c * sin(phi0) + (y * sin_c * cos(phi0)) / p);
|
|
55
|
-
|
|
56
|
-
// reprojected texture coordinates
|
|
57
|
-
vec2 tc = vec2(
|
|
58
|
-
mod(lambda / PI2 - 0.5, 1.0), // [0..1]
|
|
59
|
-
mod(phi / PI - 0.5, 1.0) // [0..1]
|
|
60
|
-
);
|
|
61
|
-
|
|
62
|
-
// sample using new coordinates
|
|
63
|
-
gl_FragColor = texture2D(u_texture, tc);
|
|
64
|
-
}
|
|
65
|
-
`;class ay{constructor(e,t,s={}){this.videoInitialized=!1,this.lastCameraRotationX=0,this.lastCameraRotationY=0,this.lastCameraRotationT=0,this.lastCameraRotationDX=0,this.lastCameraRotationDY=0,this.mouseDown=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.options=s,this.canvas=document.createElement("canvas");const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.canvas.classList.add("player-scene3d"),this.container.appendChild(this.canvas),this.camera=new ty,this.cameraRotationManager=new iy(this.camera),this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.onMouseDownHandlerFn=this.mouseDownHandler.bind(this),this.onMouseMoveHandlerFn=this.mouseMoveHandler.bind(this),this.onMouseUpHandlerFn=this.mouseUpHandler.bind(this),this.mouseLeaveHandlerFn=this.mouseLeaveHandler.bind(this),this.initControls(),this.renderFn=this.render.bind(this)}play(){this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",()=>{this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.videoInitialized=!0,this.doPlay()})}stop(){this.active=!1}startCameraRotation(e,t,s){this.cameraRotationManager.setRotationSpeed(e,t,s),this.cameraRotationManager.startRotation()}stopCameraRotation(e=!1){this.cameraRotationManager.stopRotation(e)}destroy(e){this.stop(),this.container.removeEventListener("mousedown",this.onMouseDownHandlerFn),this.container.removeEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.removeEventListener("mouseup",this.onMouseUpHandlerFn),this.canvas.remove(),e==null||e()}doPlay(){this.active=!0,requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateViewportSize(),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(n,-this.camera.rotation.x,-this.camera.rotation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(sy,this.gl.VERTEX_SHADER),s=this.createShader(ry,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.rotation.x/360,t=.5-this.camera.rotation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,n=e-s,o=t-r,l=e+s,d=t-r,u=e+s,c=t+r,h=e-s,f=t+r;return[n,o,l,d,u,c,h,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateViewportSize(){this.frameWidth=this.sourceVideoElement.videoWidth||this.sourceVideoElement.width,this.frameHeight=this.sourceVideoElement.videoHeight||this.sourceVideoElement.height,this.viewportWidth=this.sourceVideoElement.offsetWidth,this.viewportHeight=this.sourceVideoElement.offsetHeight,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}initControls(){this.container.addEventListener("mousedown",this.onMouseDownHandlerFn),this.container.addEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.addEventListener("mouseup",this.onMouseUpHandlerFn),this.container.addEventListener("mouseleave",this.mouseLeaveHandlerFn)}mouseDownHandler(e){e.target===this.canvas&&(this.cameraRotationManager.stopRotation(!0),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationT=e.timeStamp,this.mouseDown=!0)}mouseMoveHandler(e){if(this.mouseDown){const t=e.offsetX-this.lastCameraRotationX,s=this.lastCameraRotationY-e.offsetY;this.cameraRotationManager.pointCameraTo(this.camera.rotation.x+t,this.camera.rotation.y+s),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationDX=t,this.lastCameraRotationDY=s,this.lastCameraRotationT=e.timeStamp}}mouseUpHandler(e){this.mouseDown=!1;const t=e.timeStamp-this.lastCameraRotationT;this.cameraRotationManager.setRotationSpeed(this.lastCameraRotationDX*40/t,this.lastCameraRotationDY*40/t)}mouseLeaveHandler(){this.mouseDown=!1,this.lastCameraRotationX=this.lastCameraRotationY=0}}var X;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const ny=({id:i,width:e,height:t,bitrate:s,fps:r,quality:n})=>{var o;const l=(o=n?Ti(n):void 0)!==null&&o!==void 0?o:vt({width:e,height:t});return l&&{id:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},oy=({id:i,bitrate:e})=>({id:i,bitrate:e}),ly=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Fe(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Fe(i,-1)};class uy{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Le,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new oS,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(n.state===C.Requested&&(r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&t!==X.STOPPED&&s!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),s===exports.PlaybackState.STOPPED){t!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.player.stop(),this.video.setAttribute("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),P(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:s===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case X.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}}},this.init3DScene=t=>{this.scene3D||(this.scene3D=new ay(this.params.container,this.video,t),this.scene3D.play())},this.destroy3DScene=()=>{this.scene3D&&this.scene3D.destroy(()=>{this.scene3D=null})},this.params=e,this.video=We(this.params.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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Xg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=Qe(this.video),r=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,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.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.isAudioAvailable$,e.isAudioAvailable$),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(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(bt(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(et(this.video,t.playbackRate,s.playbackRateState$,r)),n(ns(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Se.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((p,b)=>b.bitrate-p.bitrate),m=Array.from(h.video).sort((p,b)=>b.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of f){const b=oy(p);b&&this.audioTracks.push({track:b,representation:p})}for(const p of m){const b=ny(p);if(b){this.videoTracks.push({track:b,representation:p});const S=!this.params.tuning.isAudioDisabled&&ly(f,m,p);S&&this.audioRepresentations.set(p.id,S)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const v=this.selectVideoRepresentation();a.assertNonNullable(v),this.player.initRepresentations(v.id,(c=this.audioRepresentations.get(v.id))===null||c===void 0?void 0:c.id)}else u===Se.REPRESENTATIOS_READY&&(this.videoState.setState(X.READY),this.player.initBuffer())},r));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!==Se.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ge.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ge.AUDIO,f.id).catch(o)}},r)),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$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{if(u)if(u.is3dVideo)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){}else this.destroy3DScene(),e.is3DVideo$.next(!1)},r)),this.params.desiredState.cameraRotation.stateChangeEnded$.subscribe(()=>{if(this.scene3D){const u=this.params.desiredState.cameraRotation.getState();u?this.scene3D.startCameraRotation(u.x,u.y,u.z):this.scene3D.stopCameraRotation(!1)}}),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,r))}selectVideoRepresentation(){var e,t,s,r,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks.find(({track:{id:S}})=>S===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=ut(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),v=Math.max(u&&!l&&(s=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&s!==void 0?s:0,c&&(n=(r=this.audioRepresentations.get(c.id))===null||r===void 0?void 0:r.bitrate)!==null&&n!==void 0?n:0),p=yi(this.videoTracks.map(({track:S})=>S),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:v,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),b=l?p!=null?p:u:u!=null?u:p;return b&&((o=this.videoTracks.find(({track:S})=>S===b))===null||o===void 0?void 0:o.representation)}prepare(){return J(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.destroy3DScene(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const dy=5e3,Me={};var V;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const ji=(i,e)=>new a.Observable(t=>{const s=(r,n)=>t.next(n);return i.on(e,s),()=>i.off(e,s)});class cy{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(V.INITIALIZING),this.textTracksManager=new Le,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==V.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&this.seek(n.position),s){case exports.PlaybackState.STOPPED:switch(t){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(s)}},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(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.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),dy);Ts(import("hls.js/dist/hls.min.js").then(r=>{e||(Me.Hls=r.default,Me.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(Me.Hls,"hls.js not loaded"),this.hls=new Me.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(Me.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,s=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=Qe(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,s));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(bt(this.video,e.isLooped,s)),this.subscription.add(ze(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ji(this.hls,Me.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(r.playing$.subscribe(()=>{this.videoState.setState(V.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(V.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},s)),n(ji(this.hls,Me.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,m;const v=h.name||h.height.toString(10),{width:p,height:b}=h,S=(m=Ti((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&m!==void 0?m:vt({width:p,height:b});if(!S)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,k={id:v.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:p,height:b},fps:y};return this.trackLevels.set(v,{track:k,level:h}),c.push(k),c},[]))),t.availableVideoTracks$),n(ji(this.hls,Me.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ce(u))),t.hostname$),this.subscription.add(xe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:s}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=ji(this.hls,Me.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,s),this.subscription.add(xe(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),m=this.hls.currentLevel,v=this.hls.levels[m];!v||h.bitrate>v.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:s})),n(r.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,s))}prepare(){this.videoState.startTransitionTo(V.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return J(this,void 0,void 0,function*(){this.videoState.startTransitionTo(V.PLAYING),(yield tt(this.video))||(this.videoState.setState(V.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(V.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.setAttribute("src",""),this.video.load(),this.videoState.setState(V.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const ho="X-Playback-Duration";var fo=i=>J(void 0,void 0,void 0,function*(){const e=yield xt(i,{method:"HEAD"});return e.headers.has(ho)?parseInt(e.headers.get(ho),10):void 0});const hy=i=>{let e=null;if(i.QUALITY&&(e=Ti(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=vt({width:t,height:s})}return e!=null?e:null},su=(i,e=i)=>J(void 0,void 0,void 0,function*(){var t;const n=(yield(yield xt(i)).text()).split(`
|
|
66
|
-
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=bi(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=hy(c);let m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const v=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[S,y]=c.RESOLUTION.split("x").map(k=>parseInt(k,10));S&&y&&(p={width:S,height:y})}const b=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:b,bandwidth:m,size:p,fps:v})}return o});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class fy{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new Q(Y.STOPPED),this.textTracksManager=new Le,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ga,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{const r=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){r!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===C.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case Y.READY:n===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Y.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),su(Nt(this.params.source.url),this.params.source.url).then(r=>{this.manifests$.next([s,...r])},r=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:r})),this.params.output.isLive$.next(!0),this.params.output.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:s,videoTrack:r}=this.params.desiredState,n=s.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=Qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,s));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),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(et(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.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(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===C.Requested&&this.seek(l.position)},s)),this.subscription.add(r.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)},s)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),s)),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$,s));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,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Nt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),fo(t).then(s=>{var r;if(!a.isNullable(s))this.maxSeekBackTime$.next(s);else{const n=(r=this.params.source.maxSeekBackTime)!==null&&r!==void 0?r:this.maxSeekBackTime$.getValue();if(a.isNullable(n)||!isFinite(n))try{xt(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();fo(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(W||(W={}));class py{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(W.STOPPED),this.textTracksManager=new Le,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===exports.PlaybackState.STOPPED){s!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.setAttribute("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),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===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===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===C.Requested&&this.seek(u.position),s){case W.READY:r===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case W.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=We(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.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(ce(this.params.source.url)),su(this.params.source.url).then(s=>{this.manifests$.next([t,...s])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,n=s.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=Qe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));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.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(bt(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(et(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.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()},s).add(r.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(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===C.Requested&&this.seek(l.position)},s))),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$,s));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,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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 my{constructor(e){this.subscription=new a.Subscription,this.videoState=new Q(Z.STOPPED),this.trackUrls={},this.textTracksManager=new Le,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED){t!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}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===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:d*1e3,forcePrecise:!0});return}switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&this.seek(l.position),t){case Z.READY:s===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&P(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,s],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=Qe(this.video),n=(l,d)=>this.subscription.add(l.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.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(bt(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(et(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.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()},s)),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,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const s=(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(s,"MpegProvider: track is not selected");let{url:r}=this.trackUrls[s];a.assertNonNullable(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=Ot(r)),this.video.setAttribute("src",r),this.video.load(),this.params.output.hostname$.next(ce(r))}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const po=["stun:videostun.mycdn.me:80"],vy=1e3,by=3,fr=()=>null;class Sy{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=fr,this.externalStopCallback=fr,this.externalErrorCallback=fr,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return J(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 J(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:po}]};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 J(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 J(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 J(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 J(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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),vy)}normalizeOptions(e={}){const t={stunServerList:po,maxRetryNumber:by,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class gy{constructor(e){this.videoState=new Q(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:s===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&P(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 Sy(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}subscribe(){const{output:e,desiredState:t}=this.params,s=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 r=Qe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,s));n(r.timeUpdate$,e.liveTime$),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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===q.READY&&this.videoState.setState(q.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ze(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},s)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.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,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class mo{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 yy=()=>{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")},pr,mr,vr,br,Sr,gr,Hi,yr,Gi,Tr,Yi,Er,qi,$r,zi,Pr;const ru=yy(),Ke=document.createElement("video"),Ve={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((mr=(pr=window.SourceBuffer)===null||pr===void 0?void 0:pr.prototype)===null||mr===void 0?void 0:mr.appendBuffer)),hls:Boolean(((vr=Ke.canPlayType)===null||vr===void 0?void 0:vr.call(Ke,"application/x-mpegurl"))||((br=Ke.canPlayType)===null||br===void 0?void 0:br.call(Ke,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},be={mp4:Boolean((Sr=Ke.canPlayType)===null||Sr===void 0?void 0:Sr.call(Ke,"video/mp4")),webm:Boolean((gr=Ke.canPlayType)===null||gr===void 0?void 0:gr.call(Ke,"video/webm")),cmaf:!0},Xe={h264:Boolean((yr=(Hi=window.MediaSource)===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||yr===void 0?void 0:yr.call(Hi,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Tr=(Gi=window.MediaSource)===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||Tr===void 0?void 0:Tr.call(Gi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Er=(Yi=window.MediaSource)===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||Er===void 0?void 0:Er.call(Yi,'video/webm; codecs="vp9"')),aac:Boolean(($r=(qi=window.MediaSource)===null||qi===void 0?void 0:qi.isTypeSupported)===null||$r===void 0?void 0:$r.call(qi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Pr=(zi=window.MediaSource)===null||zi===void 0?void 0:zi.isTypeSupported)===null||Pr===void 0?void 0:Pr.call(zi,'audio/webm; codecs="opus"'))},kt=(Xe.h264||Xe.h265)&&Xe.aac,Ps=Ve.hls&&be.mp4,Ty=Boolean(window.WebSocket),Ey=()=>Object.keys(Xe).filter(i=>Xe[i]),$y=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Ve.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_SEP:return Ve.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_WEBM:return Ve.mse&&be.webm&&Xe.vp9&&Xe.opus;case exports.VideoFormat.DASH_LIVE:return Ve.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_LIVE_CMAF:return Ve.mse&&be.mp4&&kt&&be.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Ve.mse&&be.mp4&&kt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Ps||e&&Ve.mse&&be.mp4&&kt;case exports.VideoFormat.MPEG:return be.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ve.webrtc&&Ty&&Xe.h264&&(be.mp4||be.webm);default:return a.assertNever(t)}}),Py=()=>ru?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Ps?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Ay=()=>ru?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Ps?[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],vo=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var ky=i=>new a.Observable(e=>{const t=new a.Subscription,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$,o=new a.Subject;let l=0,d="unknown";return t.add(s.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(l),d="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const bo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},_y={cacheDuration:12e4},wy={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Ry={maxPausedTime:3e4},So={maxPausedTime:3e4};class Iy{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),element$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=$y([...Ay(),...Py()],this.params.tuning.useHlsJs).filter(o=>a.isNonNullable(e.sources[o])),{formatsToAvoid:s}=this.params.tuning,r=s.length?[...t.filter(o=>!s.includes(o)),...t.filter(o=>s.includes(o))]:t;this.screenFormatsIterator=new mo(r);const n=[...vo(!0),...vo(!1)];this.chromecastFormatsIterator=new mo(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 s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,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,s=this.params.desiredState.seekState.getState(),r=s.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:r?s.position:t,forcePrecise:r?s.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 fe.SCREEN:return this.createScreenProvider(t);case fe.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:r,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 IS(Object.assign(Object.assign({},o),{source:l,config:_y}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new Xn(Object.assign(Object.assign({},o),{source:l,format:e,config:So})):new uy(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Xn(Object.assign(Object.assign({},o),{source:l,format:e,config:So}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),Ps||!this.params.tuning.useHlsJs?new py(Object.assign(Object.assign({},o),{source:l})):new cy(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 fy(Object.assign(Object.assign({},o),{source:l,config:Ry}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new my(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:wy}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new gy({container:s,source:l,desiredState:r,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:s,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Nb({connection:l,meta:n,container:s,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?fe.CHROMECAST:fe.SCREEN}chooseFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case fe.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.next();case fe.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case fe.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case fe.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 s=r=>{const n=new URL(r);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:s(e.url)})}return bi(Object.entries(e).map(([r,n])=>[r,s(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,s=0;return e.add(a.merge(this.providerOutput.error$,ky({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:bo.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(a.filter(({type:r})=>r!==void 0))}).pipe(a.map(r=>({id:`ProviderHangup:${r}`,category:a.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{if(this.current$.getValue().destination===fe.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=r.category===a.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=s<bo.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(s++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Te;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Te||(Te={}));const au=new Map;let ct=Te.RUNTIME;const Ar=`vk-videoplayer-dummy-key-${Math.random()}`,Dy=()=>{try{localStorage.setItem(Ar,"test"),localStorage.removeItem(Ar),ct=Te.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Ar),ct=Te.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)ct=Te.RUNTIME;else throw e}else throw i}};Dy();const Cy=i=>{var e,t;switch(ct){case Te.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Te.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Te.RUNTIME:return au.get(i);default:a.assertNever(ct)}},go=(i,e)=>{switch(ct){case Te.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Te.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Te.RUNTIME:return void au.set(i,e);default:a.assertNever(ct)}},Wr=(i,e,t)=>t*e+(1-t)*i,nu=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Ny=(i,e,t,s)=>{let r=0,n=t;const o=nu(i,e),l=e<s?e:s;for(let d=0;d<l;d++)i[n]>o?r++:r--,n=(i.length+n-1)%i.length;return Math.abs(r)===l};class ou{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 s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Ce(`raw_${s}`),this.smoothedSeries$=new Ce(`smoothed_${s}`),this.reportedSeries$=new Ce(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>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 xy extends ou{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Wr(this.slow,e,this.params.emaAlphaSlow),this.fast=Wr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Oy extends ou{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=nu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Wr(this.emaSmoothed,e,this.params.emaAlpha);const s=Ny(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class yo{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new xy({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Oy({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}}const Ly=5e3,To="one_video_throughput",Eo="one_video_rtt",He=window.navigator.connection,$o=()=>{const i=He==null?void 0:He.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},Po=()=>{const i=He==null?void 0:He.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},Ao=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class li{constructor(e){var t,s;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=li.load(To)||(e.useBrowserEstimation?$o():void 0)||Ly,n=(s=(t=li.load(Eo))!==null&&t!==void 0?t:e.useBrowserEstimation?Po():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Ao(r,n,e.rttPenaltyRequestSize)),this.throughput=yo.getSmoothedValue(r,-1,e),this.rtt=yo.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=$o();d&&this.throughput.next(d);const u=Po();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=>{go(To,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{go(Eo,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,s=a.now();const r=new a.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,s=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=a.now()}));break}r.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-s;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let s=0;const r=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})=>J(this,void 0,void 0,function*(){u?(this.addRawSpeed(s,a.now()-r,1),this.concurrentDownloads.delete(e)):c&&(s+=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,s=1){if(li.sanityCheck(e,t)){const r=e*8/t;this.throughput.next(r*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){var t;const s=Cy(e);if(a.isNonNullable(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const ko={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,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}},By=i=>{const e={};for(const t of Object.keys(ko)){const s=ko[t],r=i[t];Array.isArray(s)&&Array.isArray(r)?e[t]=r:typeof s=="object"&&typeof r=="object"?e[t]=Object.assign(Object.assign({},s),r):e[t]=r!=null?r:s}return e};var My=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var s;return t.state===C.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===C.None))),Vy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const _o=({playbackState:i,seekState:e,playbackAbort$:t,looped$:s,position$:r})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(m=>(m.from===exports.PlaybackState.PAUSED||m.from===exports.PlaybackState.STOPPED)&&m.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(m=>m.from===exports.PlaybackState.PLAYING&&m.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:m})=>{var v,p;return m.state===C.Requested&&((p=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&p!==void 0?p:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:m,to:v})=>{var p,b;return m.state===C.Applying&&v.state===C.None&&((b=(p=i.getTransition())===null||p===void 0?void 0:p.from)!==null&&b!==void 0?b:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>r.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),s).pipe(a.map(()=>r.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(m=>{o=m})).add(f.subscribe(m=>{if(a.isNullable(o)||o===m)return;const v={from:o,to:m};o=void 0,n.next(v)}))});class Fy{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Q(exports.PlaybackState.STOPPED),seekState:new Q({state:C.None}),volume:new Q({volume:1,muted:!1}),videoTrack:new Q(void 0),autoVideoTrackSwitching:new Q(!1),autoVideoTrackLimits:new Q({}),isLooped:new Q(!1),playbackRate:new Q(1),externalTextTracks:new Q([]),currentTextTrack:new Q(void 0),textTrackCuesSettings:new Q({}),cameraRotation:new Q(!1)},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),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),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.events={inited$:new a.Subject,started$:new a.Subject,willPause$:new a.Subject,willResume$: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),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:rS},this.initLogs(),this.tuning=By(e),this.chromecastInitializer=new Lu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new li(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,s,r)=>{const n=Reflect.get(t,s,r);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,m)=>{const v=typeof m;return["number","string","boolean"].includes(v)?m:m===null?null:`<${v}>`})),u=`Player.${String(s)}`,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,s,r;return this.config=e,this.domContainer=Vy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Iy({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},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(),(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:C.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 s=t.find(r=>r.quality===e);return s&&this.desiredState.videoTrack.startTransitionTo(s.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 s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>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(s=>s.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()}startCameraRotation(e,t){return this.desiredState.cameraRotation.setState({x:e,y:t,z:0}),this}stopCameraRotation(){return this.desiredState.cameraRotation.setState(!1),this}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(),s=t.state===C.None?void 0:t.position;return a.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(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$.pipe(a.filter(()=>!this.isPlaybackStarted),a.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===C.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:C.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>rs(u)?1:rs(c)?-1:Ki(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.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(d=>d?{start:d.from,end:d.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(e.providerOutput.volume$.pipe(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(My({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(d=>({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(()=>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 s=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:d})=>d===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>s.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,s).pipe(a.map(()=>{const d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||s.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(_o({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(_o({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{var u,c;const h=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=d==null?void 0:d.size)===null||u===void 0?void 0:u.width,height:(c=d==null?void 0:d.size)===null||c===void 0?void 0:c.height},{width:h==null?void 0:h.videoWidth,height:h==null?void 0:h.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(d=>{this.info.is3DVideo$.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((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(s=>s.length>0),a.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:s})=>s===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=yi(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(s=>iS(s)),this.providerContainer.current$.subscribe(({type:s})=>Vi("provider",s)),t.duration$.subscribe(s=>Vi("duration",s)),t.availableVideoTracks$.pipe(a.filter(s=>!!s.length),a.once()).subscribe(s=>Vi("tracks",s)),this.events.fatalError$.subscribe(new Ce("fatalError")),this.events.managedError$.subscribe(new Ce("managedError")),t.position$.subscribe(new Ce("position")),t.currentVideoTrack$.pipe(a.map(s=>s==null?void 0:s.quality)).subscribe(new Ce("quality")),this.info.currentBuffer$.subscribe(new Ce("buffer")),t.isBuffering$.subscribe(new Ce("isBuffering"))].forEach(s=>this.subscription.add(s)),Vi("codecs",Ey())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>J(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(r)}))});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.transitionEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);r&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const Uy=`${xu}@${Nu}`;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=Fy;exports.SDK_VERSION=Uy;
|
|
6
|
+
"use strict";var gu=Object.create;var ka=Object.defineProperty;var yu=Object.getOwnPropertyDescriptor;var Tu=Object.getOwnPropertyNames;var Eu=Object.getPrototypeOf,$u=Object.prototype.hasOwnProperty;var ku=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Tu(e))!$u.call(i,s)&&s!==t&&ka(i,s,{get:()=>e[s],enumerable:!(r=yu(e,s))||r.enumerable});return i};var Pa=(i,e,t)=>(t=i!=null?gu(Eu(i)):{},ku(e||!i||!i.__esModule?ka(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Pu=require("lodash/debounce.js");const Au="2.0.83",wu="es2015.cjs.js";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_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 fe;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(fe||(fe={}));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 C;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(C||(C={}));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 R(i){return this instanceof R?(this.v=i,this):new R(i)}function Pe(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,v){n.push([f,p,m,v])>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 R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var _u=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 Ru{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||_u("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(Iu),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 Iu=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 Aa=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Ee=function(i){try{return!!i()}catch(e){return!0}},Nu=Ee,ar=!Nu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),yo=ar,To=Function.prototype,gs=To.call,Cu=yo&&To.bind.bind(gs,gs),$e=yo?Cu:function(i){return function(){return gs.apply(i,arguments)}},Eo=$e,Du=Eo({}.toString),Ou=Eo("".slice),ni=function(i){return Ou(Du(i),8,-1)},Lu=$e,xu=Ee,Bu=ni,Er=Object,Mu=Lu("".split),Vu=xu(function(){return!Er("z").propertyIsEnumerable(0)})?function(i){return Bu(i)=="String"?Mu(i,""):Er(i)}:Er,oi=function(i){return i==null},Fu=oi,Uu=TypeError,js=function(i){if(Fu(i))throw Uu("Can't call method on "+i);return i},ju=Vu,Hu=js,li=function(i){return ju(Hu(i))},Gu=function(){},Lt={},Ti=function(i){return i&&i.Math==Math&&i},le=Ti(typeof globalThis=="object"&&globalThis)||Ti(typeof window=="object"&&window)||Ti(typeof self=="object"&&self)||Ti(typeof Aa=="object"&&Aa)||function(){return this}()||Function("return this")(),ys=typeof document=="object"&&document.all,Yu=typeof ys=="undefined"&&ys!==void 0,$o={all:ys,IS_HTMLDDA:Yu},ko=$o,qu=ko.all,se=ko.IS_HTMLDDA?function(i){return typeof i=="function"||i===qu}:function(i){return typeof i=="function"},zu=le,Wu=se,wa=zu.WeakMap,Qu=Wu(wa)&&/native code/.test(String(wa)),_a=se,Po=$o,Ju=Po.all,He=Po.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:_a(i)||i===Ju}:function(i){return typeof i=="object"?i!==null:_a(i)},Ku=Ee,Ge=!Ku(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ht={},Xu=le,Ra=He,Ts=Xu.document,Zu=Ra(Ts)&&Ra(Ts.createElement),Hs=function(i){return Zu?Ts.createElement(i):{}},ed=Ge,td=Ee,id=Hs,Ao=!ed&&!td(function(){return Object.defineProperty(id("div"),"a",{get:function(){return 7}}).a!=7}),rd=Ge,sd=Ee,wo=rd&&sd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),ad=He,nd=String,od=TypeError,Ye=function(i){if(ad(i))return i;throw od(nd(i)+" is not an object")},ld=ar,Ei=Function.prototype.call,ve=ld?Ei.bind(Ei):function(){return Ei.apply(Ei,arguments)},Gs={},$r=Gs,kr=le,ud=se,Ia=function(i){return ud(i)?i:void 0},ft=function(i,e){return arguments.length<2?Ia($r[i])||Ia(kr[i]):$r[i]&&$r[i][e]||kr[i]&&kr[i][e]},dd=$e,nr=dd({}.isPrototypeOf),or=typeof navigator!="undefined"&&String(navigator.userAgent)||"",_o=le,Pr=or,Na=_o.process,Ca=_o.Deno,Da=Na&&Na.versions||Ca&&Ca.version,Oa=Da&&Da.v8,ke,Wi;Oa&&(ke=Oa.split("."),Wi=ke[0]>0&&ke[0]<4?1:+(ke[0]+ke[1]));!Wi&&Pr&&(ke=Pr.match(/Edge\/(\d+)/),(!ke||ke[1]>=74)&&(ke=Pr.match(/Chrome\/(\d+)/),ke&&(Wi=+ke[1])));var Ro=Wi,La=Ro,cd=Ee,Io=!!Object.getOwnPropertySymbols&&!cd(function(){var i=Symbol();return!String(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&La&&La<41}),hd=Io,No=hd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",fd=ft,pd=se,vd=nr,md=No,bd=Object,Co=md?function(i){return typeof i=="symbol"}:function(i){var e=fd("Symbol");return pd(e)&&vd(e.prototype,bd(i))},Sd=String,lr=function(i){try{return Sd(i)}catch(e){return"Object"}},gd=se,yd=lr,Td=TypeError,pt=function(i){if(gd(i))return i;throw Td(yd(i)+" is not a function")},Ed=pt,$d=oi,ur=function(i,e){var t=i[e];return $d(t)?void 0:Ed(t)},Ar=ve,wr=se,_r=He,kd=TypeError,Pd=function(i,e){var t,r;if(e==="string"&&wr(t=i.toString)&&!_r(r=Ar(t,i))||wr(t=i.valueOf)&&!_r(r=Ar(t,i))||e!=="string"&&wr(t=i.toString)&&!_r(r=Ar(t,i)))return r;throw kd("Can't convert object to primitive value")},Qi={},Ad={get exports(){return Qi},set exports(i){Qi=i}},Do=!0,xa=le,wd=Object.defineProperty,_d=function(i,e){try{wd(xa,i,{value:e,configurable:!0,writable:!0})}catch(t){xa[i]=e}return e},Rd=le,Id=_d,Ba="__core-js_shared__",Nd=Rd[Ba]||Id(Ba,{}),Ys=Nd,Ma=Ys;(Ad.exports=function(i,e){return Ma[i]||(Ma[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 Cd=js,Dd=Object,dr=function(i){return Dd(Cd(i))},Od=$e,Ld=dr,xd=Od({}.hasOwnProperty),Oe=Object.hasOwn||function(e,t){return xd(Ld(e),t)},Bd=$e,Md=0,Vd=Math.random(),Fd=Bd(1 .toString),Oo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Fd(++Md+Vd,36)},Ud=le,jd=Qi,Va=Oe,Hd=Oo,Gd=Io,Yd=No,Pt=Ud.Symbol,Rr=jd("wks"),qd=Yd?Pt.for||Pt:Pt&&Pt.withoutSetter||Hd,ue=function(i){return Va(Rr,i)||(Rr[i]=Gd&&Va(Pt,i)?Pt[i]:qd("Symbol."+i)),Rr[i]},zd=ve,Fa=He,Ua=Co,Wd=ur,Qd=Pd,Jd=ue,Kd=TypeError,Xd=Jd("toPrimitive"),Zd=function(i,e){if(!Fa(i)||Ua(i))return i;var t=Wd(i,Xd),r;if(t){if(e===void 0&&(e="default"),r=zd(t,i,e),!Fa(r)||Ua(r))return r;throw Kd("Can't convert object to primitive value")}return e===void 0&&(e="number"),Qd(i,e)},ec=Zd,tc=Co,qs=function(i){var e=ec(i,"string");return tc(e)?e:e+""},ic=Ge,rc=Ao,sc=wo,$i=Ye,ja=qs,ac=TypeError,Ir=Object.defineProperty,nc=Object.getOwnPropertyDescriptor,Nr="enumerable",Cr="configurable",Dr="writable";ht.f=ic?sc?function(e,t,r){if($i(e),t=ja(t),$i(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Dr in r&&!r[Dr]){var s=nc(e,t);s&&s[Dr]&&(e[t]=r.value,r={configurable:Cr in r?r[Cr]:s[Cr],enumerable:Nr in r?r[Nr]:s[Nr],writable:!1})}return Ir(e,t,r)}:Ir:function(e,t,r){if($i(e),t=ja(t),$i(r),rc)try{return Ir(e,t,r)}catch(s){}if("get"in r||"set"in r)throw ac("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var cr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},oc=Ge,lc=ht,uc=cr,ui=oc?function(i,e,t){return lc.f(i,e,uc(1,t))}:function(i,e,t){return i[e]=t,i},dc=Qi,cc=Oo,Ha=dc("keys"),zs=function(i){return Ha[i]||(Ha[i]=cc(i))},Ws={},hc=Qu,Lo=le,fc=He,pc=ui,Or=Oe,Lr=Ys,vc=zs,mc=Ws,Ga="Object already initialized",Es=Lo.TypeError,bc=Lo.WeakMap,Ji,si,Ki,Sc=function(i){return Ki(i)?si(i):Ji(i,{})},gc=function(i){return function(e){var t;if(!fc(e)||(t=si(e)).type!==i)throw Es("Incompatible receiver, "+i+" required");return t}};if(hc||Lr.state){var Ne=Lr.state||(Lr.state=new bc);Ne.get=Ne.get,Ne.has=Ne.has,Ne.set=Ne.set,Ji=function(i,e){if(Ne.has(i))throw Es(Ga);return e.facade=i,Ne.set(i,e),e},si=function(i){return Ne.get(i)||{}},Ki=function(i){return Ne.has(i)}}else{var gt=vc("state");mc[gt]=!0,Ji=function(i,e){if(Or(i,gt))throw Es(Ga);return e.facade=i,pc(i,gt,e),e},si=function(i){return Or(i,gt)?i[gt]:{}},Ki=function(i){return Or(i,gt)}}var xo={set:Ji,get:si,has:Ki,enforce:Sc,getterFor:gc},yc=ar,Bo=Function.prototype,Ya=Bo.apply,qa=Bo.call,Mo=typeof Reflect=="object"&&Reflect.apply||(yc?qa.bind(Ya):function(){return qa.apply(Ya,arguments)}),Tc=ni,Ec=$e,Vo=function(i){if(Tc(i)==="Function")return Ec(i)},Qs={},Fo={},Uo={}.propertyIsEnumerable,jo=Object.getOwnPropertyDescriptor,$c=jo&&!Uo.call({1:2},1);Fo.f=$c?function(e){var t=jo(this,e);return!!t&&t.enumerable}:Uo;var kc=Ge,Pc=ve,Ac=Fo,wc=cr,_c=li,Rc=qs,Ic=Oe,Nc=Ao,za=Object.getOwnPropertyDescriptor;Qs.f=kc?za:function(e,t){if(e=_c(e),t=Rc(t),Nc)try{return za(e,t)}catch(r){}if(Ic(e,t))return wc(!Pc(Ac.f,e,t),e[t])};var Cc=Ee,Dc=se,Oc=/#|\.prototype\./,di=function(i,e){var t=xc[Lc(i)];return t==Mc?!0:t==Bc?!1:Dc(e)?Cc(e):!!e},Lc=di.normalize=function(i){return String(i).replace(Oc,".").toLowerCase()},xc=di.data={},Bc=di.NATIVE="N",Mc=di.POLYFILL="P",Ho=di,Wa=Vo,Vc=pt,Fc=ar,Uc=Wa(Wa.bind),hr=function(i,e){return Vc(i),e===void 0?i:Fc?Uc(i,e):function(){return i.apply(e,arguments)}},ki=le,jc=Mo,Hc=Vo,Gc=se,Yc=Qs.f,qc=Ho,yt=Gs,zc=hr,Tt=ui,Qa=Oe,Wc=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 jc(i,this,arguments)};return e.prototype=i.prototype,e},we=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?ki:s?ki[t]:(ki[t]||{}).prototype,l=r?yt:yt[t]||Tt(yt,t,{})[t],d=l.prototype,u,c,h,f,p,m,v,b,S;for(f in e)u=qc(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&Qa(o,f),m=l[f],c&&(i.dontCallGetSet?(S=Yc(o,f),v=S&&S.value):v=o[f]),p=c&&v?v:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?b=zc(p,ki):i.wrap&&c?b=Wc(p):n&&Gc(p)?b=Hc(p):b=p,(i.sham||p&&p.sham||m&&m.sham)&&Tt(b,"sham",!0),Tt(l,f,b),n&&(h=t+"Prototype",Qa(yt,h)||Tt(yt,h,{}),Tt(yt[h],f,p),i.real&&d&&(u||!d[f])&&Tt(d,f,p)))},$s=Ge,Qc=Oe,Go=Function.prototype,Jc=$s&&Object.getOwnPropertyDescriptor,Js=Qc(Go,"name"),Kc=Js&&function(){}.name==="something",Xc=Js&&(!$s||$s&&Jc(Go,"name").configurable),Zc={EXISTS:Js,PROPER:Kc,CONFIGURABLE:Xc},Yo={},eh=Math.ceil,th=Math.floor,ih=Math.trunc||function(e){var t=+e;return(t>0?th:eh)(t)},rh=ih,Ks=function(i){var e=+i;return e!==e||e===0?0:rh(e)},sh=Ks,ah=Math.max,nh=Math.min,oh=function(i,e){var t=sh(i);return t<0?ah(t+e,0):nh(t,e)},lh=Ks,uh=Math.min,dh=function(i){return i>0?uh(lh(i),9007199254740991):0},ch=dh,Xs=function(i){return ch(i.length)},hh=li,fh=oh,ph=Xs,Ja=function(i){return function(e,t,r){var s=hh(e),n=ph(s),o=fh(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}},vh={includes:Ja(!0),indexOf:Ja(!1)},mh=$e,xr=Oe,bh=li,Sh=vh.indexOf,gh=Ws,Ka=mh([].push),yh=function(i,e){var t=bh(i),r=0,s=[],n;for(n in t)!xr(gh,n)&&xr(t,n)&&Ka(s,n);for(;e.length>r;)xr(t,n=e[r++])&&(~Sh(s,n)||Ka(s,n));return s},qo=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Th=yh,Eh=qo,$h=Object.keys||function(e){return Th(e,Eh)},kh=Ge,Ph=wo,Ah=ht,wh=Ye,_h=li,Rh=$h;Yo.f=kh&&!Ph?Object.defineProperties:function(e,t){wh(e);for(var r=_h(t),s=Rh(t),n=s.length,o=0,l;n>o;)Ah.f(e,l=s[o++],r[l]);return e};var Ih=ft,zo=Ih("document","documentElement"),Nh=Ye,Ch=Yo,Xa=qo,Dh=Ws,Oh=zo,Lh=Hs,xh=zs,Za=">",en="<",ks="prototype",Ps="script",Wo=xh("IE_PROTO"),Br=function(){},Qo=function(i){return en+Ps+Za+i+en+"/"+Ps+Za},tn=function(i){i.write(Qo("")),i.close();var e=i.parentWindow.Object;return i=null,e},Bh=function(){var i=Lh("iframe"),e="java"+Ps+":",t;return i.style.display="none",Oh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Qo("document.F=Object")),t.close(),t.F},Pi,Hi=function(){try{Pi=new ActiveXObject("htmlfile")}catch(e){}Hi=typeof document!="undefined"?document.domain&&Pi?tn(Pi):Bh():tn(Pi);for(var i=Xa.length;i--;)delete Hi[ks][Xa[i]];return Hi()};Dh[Wo]=!0;var Jo=Object.create||function(e,t){var r;return e!==null?(Br[ks]=Nh(e),r=new Br,Br[ks]=null,r[Wo]=e):r=Hi(),t===void 0?r:Ch.f(r,t)},Mh=Ee,Vh=!Mh(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Fh=Oe,Uh=se,jh=dr,Hh=zs,Gh=Vh,rn=Hh("IE_PROTO"),As=Object,Yh=As.prototype,Ko=Gh?As.getPrototypeOf:function(i){var e=jh(i);if(Fh(e,rn))return e[rn];var t=e.constructor;return Uh(t)&&e instanceof t?t.prototype:e instanceof As?Yh:null},qh=ui,Zs=function(i,e,t,r){return r&&r.enumerable?i[e]=t:qh(i,e,t),i},zh=Ee,Wh=se,Qh=He,Jh=Jo,sn=Ko,Kh=Zs,Xh=ue,ws=Xh("iterator"),Xo=!1,Ue,Mr,Vr;[].keys&&(Vr=[].keys(),"next"in Vr?(Mr=sn(sn(Vr)),Mr!==Object.prototype&&(Ue=Mr)):Xo=!0);var Zh=!Qh(Ue)||zh(function(){var i={};return Ue[ws].call(i)!==i});Zh?Ue={}:Ue=Jh(Ue);Wh(Ue[ws])||Kh(Ue,ws,function(){return this});var Zo={IteratorPrototype:Ue,BUGGY_SAFARI_ITERATORS:Xo},ef=ue,tf=ef("toStringTag"),el={};el[tf]="z";var ea=String(el)==="[object z]",rf=ea,sf=se,Gi=ni,af=ue,nf=af("toStringTag"),of=Object,lf=Gi(function(){return arguments}())=="Arguments",uf=function(i,e){try{return i[e]}catch(t){}},ci=rf?Gi:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=uf(e=of(i),nf))=="string"?t:lf?Gi(e):(r=Gi(e))=="Object"&&sf(e.callee)?"Arguments":r},df=ea,cf=ci,hf=df?{}.toString:function(){return"[object "+cf(this)+"]"},ff=ea,pf=ht.f,vf=ui,mf=Oe,bf=hf,Sf=ue,an=Sf("toStringTag"),ta=function(i,e,t,r){if(i){var s=t?i:i.prototype;mf(s,an)||pf(s,an,{configurable:!0,value:e}),r&&!ff&&vf(s,"toString",bf)}},gf=Zo.IteratorPrototype,yf=Jo,Tf=cr,Ef=ta,$f=Lt,kf=function(){return this},Pf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=yf(gf,{next:Tf(+!r,t)}),Ef(i,s,!1,!0),$f[s]=kf,i},Af=we,wf=ve,tl=Zc,_f=Pf,Rf=Ko,If=ta,nn=Zs,Nf=ue,on=Lt,il=Zo,Cf=tl.PROPER;tl.CONFIGURABLE;il.IteratorPrototype;var Ai=il.BUGGY_SAFARI_ITERATORS,Fr=Nf("iterator"),ln="keys",wi="values",un="entries",Df=function(){return this},Of=function(i,e,t,r,s,n,o){_f(t,e,r);var l=function(S){if(S===s&&f)return f;if(!Ai&&S in c)return c[S];switch(S){case ln:return function(){return new t(this,S)};case wi:return function(){return new t(this,S)};case un:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Fr]||c["@@iterator"]||s&&c[s],f=!Ai&&h||l(s),p=e=="Array"&&c.entries||h,m,v,b;if(p&&(m=Rf(p.call(new i)),m!==Object.prototype&&m.next&&(If(m,d,!0,!0),on[d]=Df)),Cf&&s==wi&&h&&h.name!==wi&&(u=!0,f=function(){return wf(h,this)}),s)if(v={values:l(wi),keys:n?f:l(ln),entries:l(un)},o)for(b in v)(Ai||u||!(b in c))&&nn(c,b,v[b]);else Af({target:e,proto:!0,forced:Ai||u},v);return o&&c[Fr]!==f&&nn(c,Fr,f,{name:s}),on[e]=f,v},Lf=function(i,e){return{value:i,done:e}},xf=li,ia=Gu,dn=Lt,rl=xo,Bf=ht.f,Mf=Of,_i=Lf,Vf=Do,Ff=Ge,sl="Array Iterator",Uf=rl.set,jf=rl.getterFor(sl);Mf(Array,"Array",function(i,e){Uf(this,{type:sl,target:xf(i),index:0,kind:e})},function(){var i=jf(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,_i(void 0,!0)):t=="keys"?_i(r,!1):t=="values"?_i(e[r],!1):_i([r,e[r]],!1)},"values");var cn=dn.Arguments=dn.Array;ia();ia();ia();if(!Vf&&Ff&&cn.name!=="values")try{Bf(cn,"name",{value:"values"})}catch(i){}var Hf=ue,Gf=Lt,Yf=Hf("iterator"),qf=Array.prototype,zf=function(i){return i!==void 0&&(Gf.Array===i||qf[Yf]===i)},Wf=ci,hn=ur,Qf=oi,Jf=Lt,Kf=ue,Xf=Kf("iterator"),al=function(i){if(!Qf(i))return hn(i,Xf)||hn(i,"@@iterator")||Jf[Wf(i)]},Zf=ve,ep=pt,tp=Ye,ip=lr,rp=al,sp=TypeError,ap=function(i,e){var t=arguments.length<2?rp(i):e;if(ep(t))return tp(Zf(t,i));throw sp(ip(i)+" is not iterable")},np=ve,fn=Ye,op=ur,lp=function(i,e,t){var r,s;fn(i);try{if(r=op(i,"return"),!r){if(e==="throw")throw t;return t}r=np(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return fn(r),t},up=hr,dp=ve,cp=Ye,hp=lr,fp=zf,pp=Xs,pn=nr,vp=ap,mp=al,vn=lp,bp=TypeError,Yi=function(i,e){this.stopped=i,this.result=e},mn=Yi.prototype,ra=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=up(e,r),u,c,h,f,p,m,v,b=function(g){return u&&vn(u,"normal",g),new Yi(!0,g)},S=function(g){return s?(cp(g),l?d(g[0],g[1],b):d(g[0],g[1])):l?d(g,b):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=mp(i),!c)throw bp(hp(i)+" is not iterable");if(fp(c)){for(h=0,f=pp(i);f>h;h++)if(p=S(i[h]),p&&pn(mn,p))return p;return new Yi(!1)}u=vp(i,c)}for(m=n?i.next:u.next;!(v=dp(m,u)).done;){try{p=S(v.value)}catch(g){vn(u,"throw",g)}if(typeof p=="object"&&p&&pn(mn,p))return p}return new Yi(!1)},Sp=qs,gp=ht,yp=cr,Tp=function(i,e,t){var r=Sp(e);r in i?gp.f(i,r,yp(0,t)):i[r]=t},Ep=we,$p=ra,kp=Tp;Ep({target:"Object",stat:!0},{fromEntries:function(e){var t={};return $p(e,function(r,s){kp(t,r,s)},{AS_ENTRIES:!0}),t}});var Pp=Gs,Ap=Pp.Object.fromEntries,wp={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},_p=wp,Rp=le,Ip=ci,Np=ui,bn=Lt,Cp=ue,Sn=Cp("toStringTag");for(var Ur in _p){var gn=Rp[Ur],jr=gn&&gn.prototype;jr&&Ip(jr)!==Sn&&Np(jr,Sn,Ur),bn[Ur]=bn.Array}var Dp=Ap,Op=Dp,Lp=Op,xp=Lp,hi=xp,Bp=ni,fr=typeof process!="undefined"&&Bp(process)=="process",Mp=ft,Vp=ht,Fp=ue,Up=Ge,yn=Fp("species"),jp=function(i){var e=Mp(i),t=Vp.f;Up&&e&&!e[yn]&&t(e,yn,{configurable:!0,get:function(){return this}})},Hp=nr,Gp=TypeError,Yp=function(i,e){if(Hp(e,i))return i;throw Gp("Incorrect invocation")},qp=$e,zp=se,_s=Ys,Wp=qp(Function.toString);zp(_s.inspectSource)||(_s.inspectSource=function(i){return Wp(i)});var nl=_s.inspectSource,Qp=$e,Jp=Ee,ol=se,Kp=ci,Xp=ft,Zp=nl,ll=function(){},ev=[],ul=Xp("Reflect","construct"),sa=/^\s*(?:class|function)\b/,tv=Qp(sa.exec),iv=!sa.exec(ll),Qt=function(e){if(!ol(e))return!1;try{return ul(ll,ev,e),!0}catch(t){return!1}},dl=function(e){if(!ol(e))return!1;switch(Kp(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return iv||!!tv(sa,Zp(e))}catch(t){return!0}};dl.sham=!0;var rv=!ul||Jp(function(){var i;return Qt(Qt.call)||!Qt(Object)||!Qt(function(){i=!0})||i})?dl:Qt,sv=rv,av=lr,nv=TypeError,ov=function(i){if(sv(i))return i;throw nv(av(i)+" is not a constructor")},Tn=Ye,lv=ov,uv=oi,dv=ue,cv=dv("species"),cl=function(i,e){var t=Tn(i).constructor,r;return t===void 0||uv(r=Tn(t)[cv])?e:lv(r)},hv=$e,fv=hv([].slice),pv=TypeError,vv=function(i,e){if(i<e)throw pv("Not enough arguments");return i},mv=or,hl=/(?:ipad|iphone|ipod).*applewebkit/i.test(mv),pe=le,bv=Mo,Sv=hr,En=se,gv=Oe,fl=Ee,$n=zo,yv=fv,kn=Hs,Tv=vv,Ev=hl,$v=fr,Rs=pe.setImmediate,Is=pe.clearImmediate,kv=pe.process,Hr=pe.Dispatch,Pv=pe.Function,Pn=pe.MessageChannel,Av=pe.String,Gr=0,Zt={},An="onreadystatechange",ai,ot,Yr,qr;fl(function(){ai=pe.location});var aa=function(i){if(gv(Zt,i)){var e=Zt[i];delete Zt[i],e()}},zr=function(i){return function(){aa(i)}},wn=function(i){aa(i.data)},_n=function(i){pe.postMessage(Av(i),ai.protocol+"//"+ai.host)};(!Rs||!Is)&&(Rs=function(e){Tv(arguments.length,1);var t=En(e)?e:Pv(e),r=yv(arguments,1);return Zt[++Gr]=function(){bv(t,void 0,r)},ot(Gr),Gr},Is=function(e){delete Zt[e]},$v?ot=function(i){kv.nextTick(zr(i))}:Hr&&Hr.now?ot=function(i){Hr.now(zr(i))}:Pn&&!Ev?(Yr=new Pn,qr=Yr.port2,Yr.port1.onmessage=wn,ot=Sv(qr.postMessage,qr)):pe.addEventListener&&En(pe.postMessage)&&!pe.importScripts&&ai&&ai.protocol!=="file:"&&!fl(_n)?(ot=_n,pe.addEventListener("message",wn,!1)):An in kn("script")?ot=function(i){$n.appendChild(kn("script"))[An]=function(){$n.removeChild(this),aa(i)}}:ot=function(i){setTimeout(zr(i),0)});var pl={set:Rs,clear:Is},vl=function(){this.head=null,this.tail=null};vl.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 ml=vl,wv=or,_v=/ipad|iphone|ipod/i.test(wv)&&typeof Pebble!="undefined",Rv=or,Iv=/web0s(?!.*chrome)/i.test(Rv),ct=le,Rn=hr,Nv=Qs.f,Wr=pl.set,Cv=ml,Dv=hl,Ov=_v,Lv=Iv,Qr=fr,In=ct.MutationObserver||ct.WebKitMutationObserver,Nn=ct.document,Cn=ct.process,Ri=ct.Promise,Dn=Nv(ct,"queueMicrotask"),Ns=Dn&&Dn.value,Et,Jr,Kr,Ii,On;if(!Ns){var Ni=new Cv,Ci=function(){var i,e;for(Qr&&(i=Cn.domain)&&i.exit();e=Ni.get();)try{e()}catch(t){throw Ni.head&&Et(),t}i&&i.enter()};!Dv&&!Qr&&!Lv&&In&&Nn?(Jr=!0,Kr=Nn.createTextNode(""),new In(Ci).observe(Kr,{characterData:!0}),Et=function(){Kr.data=Jr=!Jr}):!Ov&&Ri&&Ri.resolve?(Ii=Ri.resolve(void 0),Ii.constructor=Ri,On=Rn(Ii.then,Ii),Et=function(){On(Ci)}):Qr?Et=function(){Cn.nextTick(Ci)}:(Wr=Rn(Wr,ct),Et=function(){Wr(Ci)}),Ns=function(i){Ni.head||Et(),Ni.add(i)}}var xv=Ns,Bv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},na=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Mv=le,xt=Mv.Promise,bl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Vv=bl,Fv=fr,Uv=!Vv&&!Fv&&typeof window=="object"&&typeof document=="object",jv=le,ei=xt,Hv=se,Gv=Ho,Yv=nl,qv=ue,zv=Uv,Wv=bl,Xr=Ro,Ln=ei&&ei.prototype,Qv=qv("species"),Cs=!1,Sl=Hv(jv.PromiseRejectionEvent),Jv=Gv("Promise",function(){var i=Yv(ei),e=i!==String(ei);if(!e&&Xr===66||!(Ln.catch&&Ln.finally))return!0;if(!Xr||Xr<51||!/native code/.test(i)){var t=new ei(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[Qv]=r,Cs=t.then(function(){})instanceof r,!Cs)return!0}return!e&&(zv||Wv)&&!Sl}),fi={CONSTRUCTOR:Jv,REJECTION_EVENT:Sl,SUBCLASSING:Cs},Bt={},xn=pt,Kv=TypeError,Xv=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw Kv("Bad Promise constructor");e=r,t=s}),this.resolve=xn(e),this.reject=xn(t)};Bt.f=function(i){return new Xv(i)};var Zv=we,Xi=fr,Ze=le,pi=ve,em=Zs,tm=ta,im=jp,rm=pt,Ds=se,sm=He,am=Yp,nm=cl,gl=pl.set,oa=xv,om=Bv,lm=na,um=ml,yl=xo,Os=xt,la=fi,Tl=Bt,pr="Promise",El=la.CONSTRUCTOR,dm=la.REJECTION_EVENT;la.SUBCLASSING;var Zr=yl.getterFor(pr),cm=yl.set,hm=Os&&Os.prototype,At=Os,es=hm,$l=Ze.TypeError,Ls=Ze.document,ua=Ze.process,xs=Tl.f,fm=xs,pm=!!(Ls&&Ls.createEvent&&Ze.dispatchEvent),kl="unhandledrejection",vm="rejectionhandled",Bn=0,Pl=1,mm=2,da=1,Al=2,Di,Mn,bm,wl=function(i){var e;return sm(i)&&Ds(e=i.then)?e:!1},_l=function(i,e){var t=e.value,r=e.state==Pl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===Al&&gm(e),e.rejection=da),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o($l("Promise-chain cycle")):(u=wl(d))?pi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Rl=function(i,e){i.notified||(i.notified=!0,oa(function(){for(var t=i.reactions,r;r=t.get();)_l(r,i);i.notified=!1,e&&!i.rejection&&Sm(i)}))},Il=function(i,e,t){var r,s;pm?(r=Ls.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),Ze.dispatchEvent(r)):r={promise:e,reason:t},!dm&&(s=Ze["on"+i])?s(r):i===kl&&om("Unhandled promise rejection",t)},Sm=function(i){pi(gl,Ze,function(){var e=i.facade,t=i.value,r=Vn(i),s;if(r&&(s=lm(function(){Xi?ua.emit("unhandledRejection",t,e):Il(kl,e,t)}),i.rejection=Xi||Vn(i)?Al:da,s.error))throw s.value})},Vn=function(i){return i.rejection!==da&&!i.parent},gm=function(i){pi(gl,Ze,function(){var e=i.facade;Xi?ua.emit("rejectionHandled",e):Il(vm,e,i.value)})},wt=function(i,e,t){return function(r){i(e,r,t)}},Rt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=mm,Rl(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=wl(e);r?oa(function(){var s={done:!1};try{pi(r,e,wt(Bs,s,i),wt(Rt,s,i))}catch(n){Rt(s,n,i)}}):(i.value=e,i.state=Pl,Rl(i,!1))}catch(s){Rt({done:!1},s,i)}}};El&&(At=function(e){am(this,es),rm(e),pi(Di,this);var t=Zr(this);try{e(wt(Bs,t),wt(Rt,t))}catch(r){Rt(t,r)}},es=At.prototype,Di=function(e){cm(this,{type:pr,done:!1,notified:!1,parent:!1,reactions:new um,rejection:!1,state:Bn,value:void 0})},Di.prototype=em(es,"then",function(e,t){var r=Zr(this),s=xs(nm(this,At));return r.parent=!0,s.ok=Ds(e)?e:!0,s.fail=Ds(t)&&t,s.domain=Xi?ua.domain:void 0,r.state==Bn?r.reactions.add(s):oa(function(){_l(s,r)}),s.promise}),Mn=function(){var i=new Di,e=Zr(i);this.promise=i,this.resolve=wt(Bs,e),this.reject=wt(Rt,e)},Tl.f=xs=function(i){return i===At||i===bm?new Mn(i):fm(i)});Zv({global:!0,constructor:!0,wrap:!0,forced:El},{Promise:At});tm(At,pr,!1,!0);im(pr);var ym=ue,Nl=ym("iterator"),Cl=!1;try{var Tm=0,Fn={next:function(){return{done:!!Tm++}},return:function(){Cl=!0}};Fn[Nl]=function(){return this},Array.from(Fn,function(){throw 2})}catch(i){}var Em=function(i,e){if(!e&&!Cl)return!1;var t=!1;try{var r={};r[Nl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},$m=xt,km=Em,Pm=fi.CONSTRUCTOR,Dl=Pm||!km(function(i){$m.all(i).then(void 0,function(){})}),Am=we,wm=ve,_m=pt,Rm=Bt,Im=na,Nm=ra,Cm=Dl;Am({target:"Promise",stat:!0,forced:Cm},{all:function(e){var t=this,r=Rm.f(t),s=r.resolve,n=r.reject,o=Im(function(){var l=_m(t.resolve),d=[],u=0,c=1;Nm(e,function(h){var f=u++,p=!1;c++,wm(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 Dm=we,Om=fi.CONSTRUCTOR,Un=xt;Un&&Un.prototype;Dm({target:"Promise",proto:!0,forced:Om,real:!0},{catch:function(i){return this.then(void 0,i)}});var Lm=we,xm=ve,Bm=pt,Mm=Bt,Vm=na,Fm=ra,Um=Dl;Lm({target:"Promise",stat:!0,forced:Um},{race:function(e){var t=this,r=Mm.f(t),s=r.reject,n=Vm(function(){var o=Bm(t.resolve);Fm(e,function(l){xm(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var jm=we,Hm=ve,Gm=Bt,Ym=fi.CONSTRUCTOR;jm({target:"Promise",stat:!0,forced:Ym},{reject:function(e){var t=Gm.f(this);return Hm(t.reject,void 0,e),t.promise}});var qm=Ye,zm=He,Wm=Bt,Ol=function(i,e){if(qm(i),zm(e)&&e.constructor===i)return e;var t=Wm.f(i),r=t.resolve;return r(e),t.promise},Qm=we,Jm=ft,Km=Do,Xm=xt,Zm=fi.CONSTRUCTOR,eb=Ol,tb=Jm("Promise"),ib=!Zm;Qm({target:"Promise",stat:!0,forced:Km},{resolve:function(e){return eb(ib&&this===tb?Xm:this,e)}});var rb=we,Ms=xt,sb=Ee,ab=ft,nb=se,ob=cl,jn=Ol,lb=Ms&&Ms.prototype,ub=!!Ms&&sb(function(){lb.finally.call({then:function(){}},function(){})});rb({target:"Promise",proto:!0,real:!0,forced:ub},{finally:function(i){var e=ob(this,ab("Promise")),t=nb(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 db=ft,ca=db,cb=ca,hb=cb("Promise","finally"),fb=hb,pb=fb,vb=pb,mb=vb,vr=mb,It;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(It||(It={}));var Nt=(i,e=0,t=It.OFFSET_P)=>{switch(t){case It.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case It.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 Ae={[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)=>Ae[i].height>Ae[e].height,bb=(i,e)=>Ae[i].height>=Ae[e].height,ti=(i,e)=>Ae[i].height<Ae[e].height,Sb=(i,e)=>Ae[i].height<=Ae[e].height,gb=i=>i.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:ti(e,t)?1:-1)[0],yb=Object.keys(Ae).sort((i,e)=>ti(i,e)?-1:1),vt=({width:i,height:e})=>{const t=Math.min(i,e),r=Math.max(i,e);return yb.find(s=>{const n=Ae[s];return n.width>=r&&n.height>=t})},Tb=i=>Ae[i].height,Zi=i=>i===exports.VideoQuality.INVARIANT;class J{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 Eb=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.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 L;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(L||(L={}));const $b=5,kb=5,Pb=500,Hn=7e3;class Ab{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(L.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!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===C.Requested&&r!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default: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(Eb(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(Pb)).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===C.Applying||Math.abs(l-n)>$b)&&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<kb&&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(L.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.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:C.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)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.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)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.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=gb(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:{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=Nt(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===C.Applying||r.state===C.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(Hn).subscribe(()=>n(`timeout(${Hn})`)))});vr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===C.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 Gn{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 Ll extends Gn{constructor(){super(),this.listeners||Gn.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 xl=class{constructor(){Object.defineProperty(this,"signal",{value:new Ll,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&&(xl.prototype[Symbol.toStringTag]="AbortController",Ll.prototype[Symbol.toStringTag]="AbortSignal");function Bl(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 wb(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!Bl({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 mr=Bl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ml=mr?wb({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Ct=mr?Ml.fetch:window.fetch;mr?Ml.Request:window.Request;const ut=mr?xl:window.AbortController,Jt=i=>i.range?i.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class ii{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]=Jt(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(Jt),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 ut,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 Ct(l,{signal:u}).then(f=>{var p,m,v;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[b,S]=f.body.tee();(m=(p=this.params).onDownloadStream)===null||m===void 0||m.call(p,S);const g=b.getReader(),P=parseInt((v=f.headers.get("Content-Length"))!==null&&v!==void 0?v:"",10)||n-s+1;c.data=new ArrayBuffer(P);const E=new Uint8Array(c.data),T=({done:w,value:F})=>Q(this,void 0,void 0,function*(){w?this.onBigRequestProgress(c):F&&(E.set(F,c.loaded),c.loaded+=F.byteLength,this.onBigRequestProgress(c),yield g==null?void 0:g.read().then(T,ii.suppressStreamErrors).catch(h))});g==null||g.read().then(T,ii.suppressStreamErrors).catch(h)},ii.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 v=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const b of v){const{request:S}=b,[g,P]=Jt(S),E=g>=t&&P<=t+s,T=t>=g&&t+s<P,w=n.slice(g-t,Math.min(P-t+1,s));if((E||T)&&(S.requestStartDate=(d=S.requestStartDate)!==null&&d!==void 0?d:new Date,S.firstByteDate=(u=S.firstByteDate)!==null&&u!==void 0?u:new Date,S.bytesLoaded=w.byteLength,S.bytesTotal=r-t),E){S.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(O=>O!==b)),(h=b.success)===null||h===void 0||h.call(b,w,"",e);const F=o?Array.from(o.headers.entries()).map(([O,I])=>`${O}: ${I}`).join(`\r
|
|
7
|
+
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(S,e,(p=o==null?void 0:o.status)!==null&&p!==void 0?p:200,F,[])}else T&&((m=b.progress)===null||m===void 0||m.call(b,{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]=Jt(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]=Jt(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 er{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(er.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;er.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const _b=(i,e)=>t=>({create:r=>{const s=i(t).create(r);return new er(s,e,r)}}),Rb=(i,e)=>{const t=new ii(e);return i.extend("SchemeLoaderFactory",function(){const{parent:r}=this,s=r.getLoader;return{getLoader:n=>{const o=s(n);return _b(o,t)}}},!0),()=>t.destroy()};var Ib=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)},Nb=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,v;const b=hi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(P=>P.split(": ")));if("x-playback-duration"in b||"x-playback-duration-millis"in b){const P=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(p=E!=null?E:P*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const S=(m=b["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,g=(v={1:!0,0:!1}[b["x-reused"]])!==null&&v!==void 0?v:void 0;r.next(S),s.next(g)},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(...v){return d(this),p(...v)},f.progress=function(...v){return u(this),m(...v)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},Dt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Cb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Dt}),!0),Db=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 De=(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)=>De(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),qe=(i,e,t,r)=>De(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}),et=(i,e,t,r)=>De(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Ob=i=>["__",i.language,i.label].join("|"),Lb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Le{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(De(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(De(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(De(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(Le.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id!==""?e.id:Ob(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)&&Lb(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 ze=i=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),i.appendChild(e),e};class ha{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Vl=()=>{const{userAgent:i}=window.navigator;return!/chrome/i.test(i)&&/webkit|safari|khtml/i.test(i)};const Vs=3;class xb{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<Vs&&(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||Vs))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 Fl=(i,e,t=Vs)=>{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 Bb=50,Mb=i=>i.webkitAudioDecodedByteCount!=="undefined"?!!i.webkitAudioDecodedByteCount:i.mozHasAudio!=="undefined"?i.mozHasAudio:i.audioTracks?!!i.audioTracks.length:!0,We=i=>{const e=m=>a.fromEvent(i,m).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(m=>a.fromEvent(i,m))).pipe(a.map(m=>m.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>Fl(i.buffered,i.currentTime))),n=Vl()?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(Bb),a.map(()=>Mb(i))),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>Boolean(i.error||i.played.length)),a.map(()=>{var m;const v=i.error;return{id:v?`MediaError#${v.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:v?v.message:"Error event from HTML video element",thrown:(m=i.error)!==null&&m!==void 0?m:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;return c.subscribe(m=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(m)&&p>=i.duration-f&&m<=f&&h.next(p),p=m}),{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$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,isAudioAvailable$:o,playbackRateState$:d}},fa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Vb=we,Fb=dr,Ub=Xs,jb=Ks;Vb({target:"Array",proto:!0},{at:function(e){var t=Fb(this),r=Ub(t),s=jb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Hb=ca,Gb=Hb("Array","at"),Yb=Gb,qb=Yb,zb=qb,Wb=zb,Me=Wb;let pa=!1,Ve={};const Qb=i=>{pa=i},Jb=()=>{Ve={}},Kb=i=>{i(Ve)},Oi=(i,e)=>{var t;pa&&(Ve.meta=(t=Ve.meta)!==null&&t!==void 0?t:{},Ve.meta[i]=e)};class Ce{constructor(e){this.name=e}next(e){var t,r;if(!pa)return;Ve.series=(t=Ve.series)!==null&&t!==void 0?t:{};const s=(r=Ve.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Ve.series[this.name]=s}}const Xb=new Ce("best_bitrate"),Zb=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class eS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const vi=(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,v=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*m*r.containerSizeFactor,height:e.height*m*r.containerSizeFactor},b=v&&vt(v),S=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,g=i.filter(N=>!Zi(N.quality)).sort((N,_)=>qi(N.quality,_.quality)?-1:1),P=(h=Me(g,-1))===null||h===void 0?void 0:h.quality,E=(f=Me(g,0))===null||f===void 0?void 0:f.quality,T=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&ti(s.max,s.min)||a.isNonNullable(s.min)&&E&&qi(s.min,E)||a.isNonNullable(s.max)&&P&&ti(s.max,P),w=S*Zb(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),O=g.filter(N=>{const _=b?ti(N.quality,b):!0,G=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(N.bitrate)?t-n>=N.bitrate*w:!0,K=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!Zi(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&qi(N.quality,d.quality),te=T||(a.isNullable(s.max)||Sb(N.quality,s.max))&&(a.isNullable(s.min)||bb(N.quality,s.min));return _&&G&&!K&&te})[0];O&&O.bitrate&&Xb.next(O.bitrate);const I=(p=O!=null?O:g[Math.ceil((g.length-1)/2)])!==null&&p!==void 0?p:i[0],U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=r.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const N=u.last;return u==null||u.recordSwitch(N),N}return u==null||u.recordSwitch(I),I};var ce=i=>new URL(i).hostname;const tS=300,tr=(i,e=tS)=>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(Pu(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()}),Qe=i=>{try{i.pause(),i.playbackRate=0,i.removeAttribute("src"),i.load(),i.remove()}catch(e){console.error(e)}},iS=5e3,Kt={};var x;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class Yn{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(x.DOWNLOADING_LIB),this.textTracksManager=new Le,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 ha,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===x.DOWNLOADING_LIB||t===x.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&t!==x.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 x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case x.STOPPED:this.prepare();break;case x.PLAYING:case x.PAUSED:case x.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case x.PLAYING:break;case x.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 x.READY:this.play();break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case x.PLAYING:this.pause(),this.liveOffset.pause();break;case x.PAUSED:break;case x.READY:this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case x.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=ze(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(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"),iS);vr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Kt.MediaPlayer=s.MediaPlayer,Kt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Kt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Kt.Debug,"dashjs not loaded"),this.player=Kt.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?fa(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Rb(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&&Db(this.player),Ib(this.player),this.params.tuning.requestQuick&&Cb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.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(tr(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(v=>{const b=typeof v.error=="object"?v.error.code:v.error,S=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:S}})),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 b;return(b=this.videoTracks.find(({bitrateInfo:S})=>S.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===x.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(De(t.videoTrack,()=>{var v,b;const S=this.player.getQualityFor("video");return(b=(v=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===S))===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 S=(b=this.videoTracks.find(({track:g})=>g.id===v))===null||b===void 0?void 0:b.bitrateInfo;S&&this.player.setQualityFor("video",S.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:r}))},r)),this.subscription.add(De(t.autoVideoTrackSwitching,()=>{var v,b,S;return(S=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||S===void 0?void 0:S.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:b}})=>{var S,g;const P=this.player.getDashMetrics(),E=P.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),T=(S=P.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[E])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(ce(b))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:S}}})=>{this.isLive$.next(b),this.availableFrom$.next(S.getTime()),b||e.duration$.next(v),this.videoTracks=[];const g=this.player.getQualityFor("video");let P;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=vt(E),F=E.bitrate/1e3,O={width:E.width,height:E.height},I=this.frameRatesByFrameHeight[E.height];if(w){const U={id:T,quality:w,bitrate:F,size:O,fps:I};this.videoTracks.push({track:U,bitrateInfo:E}),E.qualityIndex===g&&(P=U)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),S=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(S,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=vi(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),S=this.videoTracks.find(({track:g})=>g===b);S!=null&&S.bitrateInfo&&this.player.setQualityFor("video",S==null?void 0:S.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:b})=>this.params.output.liveTime$.next(v+b*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(()=>Fl(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(x.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(x.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)===x.READY&&this.videoState.setState(x.READY)}),s(this.isLive$,e.isLive$),s(tr(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}=Nb(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(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:b})=>{const S=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:S}}})}),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)),this.subscription.add(mt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:m}=We(this.video);this.subscription.add(qe(this.video,t.volume,f,r)),this.subscription.add(f.subscribe(e.volume$,r)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(et(this.video,t.playbackRate,m,r))}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(x.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(x.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=Nt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,It.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(x.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(x.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 mi=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}},tt=i=>Q(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return i.muted=!1,console.warn(r),!1}}return!0});function oe(){return a.now()}function Ul(i){return oe()-i}function qn(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 rS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function zi(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,v=2e3,b=()=>{if(d)return;a.assertNonNullable(c);const _=Ul(c);let G;if(_<v){G=v-_,setTimeout(b,G);return}v*=2,v>m&&(v=m),o&&o.abort(),o=new s,w()};const S=_=>(n=_,N),g=_=>(h=_,N),P=()=>(p="json",N),E=()=>{if(!d){if(--u>=0){b(),r&&r();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,N),w=()=>{c=oe(),o=new s,o.open("get",i);let _=0,G,K=0;const te=()=>(a.assertNonNullable(c),Math.max(c,Math.max(G||0,K||0)));if(n&&o.addEventListener("progress",$=>{const D=oe();n.updateChunk&&$.loaded>_&&(n.updateChunk(te(),$.loaded-_),_=$.loaded,G=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(te(),D)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(K=oe(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=p,o.send(),N},N={withBitrateReporting:S,withParallel:T,withJSONResponse:P,withRetryCount:_=>(u=_,N),withRetryInterval:(_,G)=>(a.isNonNullable(_)&&(v=_),a.isNonNullable(G)&&(m=G),N),withTimeout:_=>(l=_,N),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return N}const sS=100,aS=2e3,nS=500;let oS=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-nS;if(t-e>aS){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>sS&&(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 lS{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=oe(),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=oe()-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=zi(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=oe()}_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=oe();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 Li=1e4,xi=3,uS=300,dS=2e3,cS=6e4,hS=10,fS=1,pS=500;class vS{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 oS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=qn(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=qn(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=()=>{rS(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 lS(xi,Li,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 E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,w)=>{d&&d.abort(),d=zi(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(Li).withBitrateReporting(this.bitrateSwitcher).withRetryCount(xi).withFinally(()=>{d=null}).send()},p=(E,T,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=E=>{const T=r.playbackRate;r.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),r.playbackRate=E)},v=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),b()},b=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const w=oe()-1e4;let F=0;for(let I=0;I<this.bufferStates.length;I++){const U=this.bufferStates[I];E=Math.min(E,U.buf),U.ts<w&&F++}this.bufferStates.splice(0,F),t(`update playback rate; minBuffer=${E} drop=${F} jitter=${this.sourceJitter}`);let O=E-fS;this.sourceJitter>=0?O-=this.sourceJitter/2:this.sourceJitter-=1,O>3?m(1.15):O>1?m(1.1):O>.3?m(1.05):m(1)}},S=E=>{let T;const w=()=>T&&T.start?T.start.length:0,F=$=>T.start[$]/1e3,O=$=>T.dur[$]/1e3,I=$=>T.fragIndex+$,U=($,D)=>({chunkIdx:I($),startTS:F($),dur:O($),discontinuity:D}),N=()=>{let $=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 ie=T.dur.length-1;for(;ie>=0&&(ee-=T.dur[ie],!(ee<=0));--ie);$=Math.min(ie,T.dur.length-1-z),$=Math.max($,0)}return U($,!0)},_=$=>{const D=w();if(!(D<=0)){if(a.isNonNullable($)){for(let z=0;z<D;z++)if(F(z)>$)return U(z)}return N()}},G=$=>{const D=w(),z=$?$.chunkIdx+1:0,ee=z-T.fragIndex;if(!(D<=0)){if(!$||ee<0||ee-D>hS)return t(`Resync: offset=${ee} bChunks=${D} chunk=`+JSON.stringify($)),N();if(!(ee>=D))return U(z-T.fragIndex,!1)}},K=($,D,z)=>{u&&u.abort(),u=zi(this.urlResolver.resolve($,!0,this.lowLatency),D,z,()=>this._retryCallback()).withTimeout(Li).withRetryCount(xi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{K(E,z=>{if(!h())return;T=z;const ee=Boolean(T.lowLatency);ee!==this.lowLatency&&v(ee);let ie=0;for(let he=0;he<T.dur.length;++he)ie+=T.dur[he];ie>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ie/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,$(_(D))},()=>this._handleNetworkError())},nextChunk:G}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let F=S(e.jidxUrl),O,I,U,N,_=0,G,K,te;const $=()=>{G&&(clearTimeout(G),G=void 0);const j=Math.max(pS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ae=_+j,de=oe(),me=Math.min(1e4,ae-de);_=de;const it=()=>{u||h()&&F.seek(()=>{h()&&(_=oe(),D(),$())})};me>0?G=window.setTimeout(()=>{this.paused?$():it()},me):it()},D=()=>{let j;for(;j=F.nextChunk(N);)N=j,_e(j);const ae=F.nextChunk(U);if(ae){if(U&&ae.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}he(ae)}else $()},z=(j,ae)=>{if(!h()||!this.sourceBuffer)return;let de,me,it;const Re=Je=>{window.setTimeout(()=>{h()&&z(j,ae)},Je)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),Re(100);else{const Je=oe(),rt=T.currentTime;!this.paused&&T.buffered.length>1&&K===rt&&Je-te>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),K!==rt&&(K=rt,te=Je);const Vt=this._getBufferSizeSec();if(Vt>30)w(`Buffered ${Vt} seconds; delaying appendBuffer`),Re(2e3);else try{this.sourceBuffer.appendBuffer(j),this.videoPlayStarted?(this.bufferStates.push({ts:Je,buf:Vt}),b(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ae&&ae()}catch(bt){if(bt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),it=this.sourceBuffer.buffered.length,it!==0&&(de=this.sourceBuffer.buffered.start(0),me=rt,me-de>4&&this.sourceBuffer.remove(de,me-3)),Re(1e3);else throw bt}}},ee=()=>{I&&O&&(w([`Appending chunk, sz=${I.byteLength}:`,JSON.stringify(U)]),z(I,function(){I=null,D()}))},ie=j=>e.fragUrlTemplate.replace("%%id%%",j.chunkIdx),he=j=>{h()&&p(ie(j),(ae,de)=>{if(h()){if(de/=1e3,I=ae,U=j,o=j.startTS,de){const me=Math.min(10,j.dur/de);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}ee()}},()=>this._handleNetworkError())},_e=j=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ie(j),!1)))},Mt=j=>{h()&&(e.cachedHeader=j,z(j,()=>{O=!0,ee()}))};n=!0,F.seek(j=>{if(h()){if(_=oe(),!j){$();return}N=j,!a.isNullable(E)||j.startTS>E?he(j):(U=j,D())}},E),e.cachedHeader?Mt(e.cachedHeader):f(e.headerUrl,Mt,()=>this._handleNetworkError())},stop:g,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=oe();if(this.chunkRateEstimator.addInterval(f,m,p)){const b=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:b}),!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&&Ul(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=oe();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=zi(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Li).withRetryCount(xi).withRetryInterval(uS,dS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;tt(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))},cS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var B;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(B||(B={}));const mS=[B.PAUSED,B.PLAYING,B.READY],bS=[B.PAUSED,B.PLAYING,B.READY];class SS{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(B.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Le,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ha,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=mi(h.name))!==null&&o!==void 0?o:vt(h.video),m=h.bitrate/1e3,v=Object.assign({},h.video);if(!p)continue;const b={id:f,quality:p,bitrate:m,size:v};c.push({track:b,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)===B.MANIFEST_READY&&this.videoState.setState(B.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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(B.STOPPED));return}if(!o){if(bS.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===C.Requested&&mS.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_READY),this.dash.attachSource(Nt(this.params.source.url));return;case B.MANIFEST_READY:this.videoState.startTransitionTo(B.READY),this.prepare();break;case B.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(B.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(B.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(B.PAUSED)})}return;case B.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(B.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case B.PAUSED:l===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.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(B.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=ze(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(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 r=We(this.video);this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===B.READY&&this.videoState.setState(B.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(B.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(qe(this.video,this.params.desiredState.volume,r.volumeState$,t)).add(r.volumeState$.subscribe(this.params.output.volume$,t)).add(et(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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:s}})=>{const n=s&&Tb(s);this.dash.setMaxAutoQuality(n)})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case B.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case B.MANIFEST_READY:case B.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 B.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case B.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 vS({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=vi(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=-e,r=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(r),this.dash.reinit(Nt(this.params.source.url,r))}}var jl=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}},lt=(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 gS=i=>{const e=document.createElement("a");return e.href=i,e.origin},yS=i=>{const e=document.createElement("a");return e.href=i,e.host};class Hl{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=hi(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(yS(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 ir{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=v=>{s(ir._str2ua(v.substr(d))),d=v.length};let m=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(m=Dt(m)),this._lastXhr=new Hl(m,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const b=Date.now()-u;this._params.onBandwidthChange({size:v.length,duration:b,speed:8*v.length/(b/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),n==null||n()},v=>{if(v.length-d>l&&p(v),h===0){h=Date.now();return}f=v.length-c;const b=Date.now()-h;f>=100*1024&&b>=1e3&&(this._params.onBandwidthChange({size:f,duration:b,speed:8*f/(b/1e3)}),f=0,c=v.length,h=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},o,(v,b,S)=>this._params.onError(v,b,S))})}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=ir._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 TS{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=Dt(r)),new Hl(r,t,s=>{this.attachManifest(s,t,gS(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,v,b,S,g,P,E,T,w,F,O,I,U,N,_;const G=u.getElementsByTagName("SegmentBase")[0],K=G&&o(G,"indexRange").split("-"),te=G&&G.getElementsByTagName("Initialization")[0],$=te&&o(te,"range").split("-");if(!$||!K){const _e=u.parentElement;if((_e==null?void 0:_e.getAttribute("contentType"))==="text"){const Mt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,j=(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),ae=(v=_e.getAttribute("lang"))!==null&&v!==void 0?v:void 0;j&&d.push({id:Mt,url:j,language:ae})}return}const D=.1,z=Number((b=u.attributes.getNamedItem("bandwidth"))===null||b===void 0?void 0:b.value),ee=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ie;const he=(g=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&g!==void 0?g:void 0;ie=he?fa(he):void 0,l.push({width:Number((P=u.attributes.getNamedItem("width"))===null||P===void 0?void 0:P.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:z,baseURL:ee,failoverHosts:t,indexFrom:Number(K[0]),indexTo:Number(K[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&w!==void 0?w:void 0,mimeType:(O=(F=u.attributes.getNamedItem("mimeType"))===null||F===void 0?void 0:F.value)!==null&&O!==void 0?O:void 0,fps:ie,bufferSize:D*z/8,bufferLength:D,name:(U=(I=u.attributes.getNamedItem("okQuality"))===null||I===void 0?void 0:I.value)!==null&&U!==void 0?U:void 0,id:(_=(N=u.attributes.getNamedItem("id"))===null||N===void 0?void 0:N.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");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(this._representations)}_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 ir({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 M;(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"})(M||(M={}));const ES=[M.PAUSED,M.PLAYING];class $S{constructor(e){this.videoState=new J(M.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Le,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=t=>{var r,s,n;const o=[];for(const l of t){const d=(s=(r=l.name)!==null&&r!==void 0?r:l.id)!==null&&s!==void 0?s:l.height.toString(10),u=(n=l.name&&mi(l.name))!==null&&n!==void 0?n:vt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const p={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:p,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(M.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!==M.STOPPED&&(this.videoState.startTransitionTo(M.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(M.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===C.Requested&&ES.includes(t)&&this.seek(o.position,o.forcePrecise),t){case M.STOPPED:this.videoState.startTransitionTo(M.MANIFEST_LOADED),this.prepare();return;case M.MANIFEST_LOADED:this.videoState.startTransitionTo(M.INITIAL_REPRESENTATION_SELECTED);return;case M.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(M.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case M.METADATA_LOADED:this.videoState.startTransitionTo(M.READY),this.dash.updateRefsForCurrentTime();return;case M.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(M.PLAYING),this.playIfAllowed());return;case M.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(M.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case M.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(M.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=ze(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(ce(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new xb(this.video),this.dash=new TS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),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=We(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$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===M.PLAYING||this.videoState.getState()===M.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(qe(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),o(tr(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===M.READY&&this.videoState.setState(M.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(M.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(M.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(),v=this.elementSize$.getValue(),b=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!b&&a.isNonNullable(p))S=p;else{const g=lt(this.video.buffered,this.video.currentTime*1e3),P=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/P,1);S=(d=vi(h.map(({track:T})=>T),{container:v,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===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return a.isNonNullable(S)?(u=h.find(({track:g})=>g.id===S))===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===M.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(M.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=lt(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(ce(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=jl(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(){tt(this.video).then(e=>{e||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var ge;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ge||(ge={}));var rr;(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"})(rr||(rr={}));var ye;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ye||(ye={}));var H;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(H||(H={}));var Ot;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ot||(Ot={}));var Fs=(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)},PS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",zn=PS?kS:window.requestIdleCallback;var ts,is;let Gl=!1;try{Gl=Vl()&&parseInt((is=(ts=navigator.userAgent.match(/Version\/(\d+)/))===null||ts===void 0?void 0:ts[1])!==null&&is!==void 0?is:"",10)<16}catch(i){console.error(i)}class AS{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;Gl&&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.buffer.abort()}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"&&r==="remove"||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 Wn=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};const Yl=new TextDecoder("ascii"),ql=i=>{let e=0,t=i.getUint32(e);e+=4;const r=new DataView(i.buffer,i.byteOffset+e,4),s=Yl.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}},wS=i=>Yl.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",_S=(i,e,t)=>{const r=ql(i),s=[];let n=0;const o=()=>{const v=r.contents.getUint32(n);return n+=4,v};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 v=0;v<f;v++){const b=o(),S=b>>>31,g=b<<1>>>1,P=o();if(o(),S!==0)throw new Error("Unsupported multilevel sidx");const E=P/u*1e3;s.push({status:H.NONE,time:{from:p,to:p+E},byte:{from:m,to:m+g-1}}),p+=E,m+=g}return s},RS=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=ql(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},IS={validateData:wS,parseInit:()=>null,getIndexRange:()=>{},parseSegments:_S,parseFeedableSegmentChunk:RS};var y;(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"})(y||(y={}));var A;(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"})(A||(A={}));const Qn={[y.EBML]:{type:A.Master},[y.EBMLVersion]:{type:A.UnsignedInteger},[y.EBMLReadVersion]:{type:A.UnsignedInteger},[y.EBMLMaxIDLength]:{type:A.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[y.DocType]:{type:A.String},[y.DocTypeVersion]:{type:A.UnsignedInteger},[y.DocTypeReadVersion]:{type:A.UnsignedInteger},[y.Void]:{type:A.Binary},[y.Segment]:{type:A.Master},[y.SeekHead]:{type:A.Master},[y.Seek]:{type:A.Master},[y.SeekID]:{type:A.Binary},[y.SeekPosition]:{type:A.UnsignedInteger},[y.Info]:{type:A.Master},[y.TimestampScale]:{type:A.UnsignedInteger},[y.Duration]:{type:A.Float},[y.Tracks]:{type:A.Master},[y.Chapters]:{type:A.Master},[y.Cluster]:{type:A.Master},[y.Timestamp]:{type:A.UnsignedInteger},[y.SilentTracks]:{type:A.Master},[y.SilentTrackNumber]:{type:A.UnsignedInteger},[y.Position]:{type:A.UnsignedInteger},[y.PrevSize]:{type:A.UnsignedInteger},[y.SimpleBlock]:{type:A.Binary},[y.BlockGroup]:{type:A.Master},[y.EncryptedBlock]:{type:A.Binary},[y.Attachments]:{type:A.Master},[y.Tags]:{type:A.Master},[y.Cues]:{type:A.Master},[y.CuePoint]:{type:A.Master},[y.CueTime]:{type:A.UnsignedInteger},[y.CueTrackPositions]:{type:A.Master},[y.CueTrack]:{type:A.UnsignedInteger},[y.CueClusterPosition]:{type:A.UnsignedInteger},[y.CueRelativePosition]:{type:A.UnsignedInteger},[y.CueDuration]:{type:A.UnsignedInteger},[y.CueBlockNumber]:{type:A.UnsignedInteger},[y.CueCodecState]:{type:A.UnsignedInteger},[y.CueReference]:{type:A.Master},[y.CueRefTime]:{type:A.UnsignedInteger}},zl=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=sr(i,t),s=r in Qn,n=s?Qn[r].type:A.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=sr(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}},sr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Fe=(i,e)=>{switch(e){case A.SignedInteger:return i.getInt8(0);case A.UnsignedInteger:return sr(i);case A.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case A.String:return new TextDecoder("ascii").decode(i);case A.UTF8:return new TextDecoder("utf-8").decode(i);case A.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case A.Master:return i;case A.Binary:return i;default:a.assertNever(e)}},bi=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=zl(r);if(!e(s))return;s.type===A.Master&&bi(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},NS=i=>{if(i.getUint32(0)!==y.EBML)return!1;let e,t,r;const s=zl(i);return bi(s.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Fe(l,o):n===y.DocType?t=Fe(l,o):n===y.DocTypeReadVersion&&(r=Fe(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},Wl=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],CS=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],DS=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u;return bi(i,({tag:c,type:h,value:f,valueSize:p})=>{if(c===y.SeekID){const m=Fe(f,h);u=sr(m)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+p):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?r=Fe(f,h):c===y.Duration?s=Fe(f,h):c===y.SeekPosition&&u===y.Cues?d=Fe(f,h):n&&o&&Wl.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}},OS=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},LS=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return bi(i,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&s(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Fe(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Fe(u,d));break;default:t&&Wl.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:H.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}}})},xS=i=>{let e=0,t=!1;try{bi(i,r=>r.tag===y.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):CS.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},BS={validateData:NS,parseInit:DS,getIndexRange:OS,parseSegments:LS,parseFeedableSegmentChunk:xS};class Jn{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 ut,this.destroyAbortController=new ut,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(u){return Pe(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 AS(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 v=Math.min(this.bufferLimit,Wn(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),m)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(m=>this.error$.next(m))),yield yield R(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 R(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 R(this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(u){return Pe(this,arguments,function*(){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return yield R(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 R(this.loadInit(c,"high",!1)):h instanceof Promise&&(yield yield R(h)),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield yield R(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 Ot.MP4:this.containerParser=IS;break;case Ot.WEBM:this.containerParser=BS;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 ut,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=lt(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)&&Wn(this.sourceBuffer.buffered)>=this.bufferLimit){const u=lt(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===H.FED&&!l.length&<(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Me(r,-1);d&&d.status===H.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;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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),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 v=f<=r&&p>=r,b=f>r||v||m===0&&r===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=r+S||p<=r+S;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&b&&g&&this.sourceBuffer&&!Fs(this.sourceBuffer.buffered,r))&&b&&g});if(s===-1)return[];if(t!==ye.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===H.NONE||f.status===H.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 ye.BYTE_RANGE:{s=t.segmentReference.url,n={from:Me(e,0).byte.from,to:Me(e,-1).byte.to};break}case ye.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=H.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 Pe(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(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=lt((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=H.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===H.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=H.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===ye.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 b=p?f.byte.from-r:0,S=p?f.byte.to-r:e.byteLength,g=b<s,P=S<=s;if(f.status===H.DOWNLOADING&&g&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+b,m);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(m,s-b),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+b+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=T.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.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=zn(()=>vr(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 Pe(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,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===H.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===H.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===H.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===H.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=zn(()=>{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!==H.FED&&n!==H.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=H.PARTIALLY_EJECTED:s.status=H.NONE)}}}var _t;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(_t||(_t={}));class MS{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 ut,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return Pe(this,arguments,function*(){let n=s;this.requestQuic&&(n=Dt(n));const o=yield yield R(Ct(n,{signal:this.abortAllController.signal}).catch(Xt));return o?(this.onHeadersReceived(o.headers),yield R(o.text())):yield R(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?_t.HEADER:_t.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return Pe(this,arguments,function*(){let v=s;const b=new Headers;if(o)switch(n){case _t.HEADER:{b.append("Range",`bytes=${o.from}-${o.to}`);break}case _t.PARAM:{const $=new URL(v,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),v=$.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=Dt(v));let S=this.abortAllController.signal;if(u){const $=new ut;if(this.subscription.add(a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(D){Xt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(D){Xt(D)}S=$.signal}const g=a.now(),P=yield yield R(Ct(v,{priority:d,headers:b,signal:S}).catch(Xt)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!P)return yield R(null);if(!P.ok||!P.body)return yield R(Promise.reject(new Error(`Fetch error ${P.status}: ${P.statusText}`)));this.onHeadersReceived(P.headers);const T=parseInt((f=P.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield yield R(P.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed($.byteLength,a.now()-E),l==null||l(new DataView($),$.byteLength),yield R($)}if(!l&&!c)return yield R(P.arrayBuffer());const[w,F]=P.body.tee(),O=w.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(F));let I=0;const U=new ArrayBuffer(T),N=new Uint8Array(U),_=new DataView(U);let G=!1;const K=$=>{G=!0,Xt($)},te=a.abortable(S,function({done:$,value:D}){return Pe(this,arguments,function*(){if(I===0&&this.lastRequestFirstBytes$.next(a.now()-g),S.aborted)return yield R(void 0);$?l==null||l(_,I):D&&(N.set(D,I),I+=D.byteLength,l==null||l(_,I),yield yield R(O==null?void 0:O.read().then(te,K)))})}.bind(this));return yield yield R(O==null?void 0:O.read().then(te,K)),yield R(G?null:U)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return Pe(this,arguments,function*(){if(s.type!==ye.BYTE_RANGE)return yield R(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 v=yield yield R(this.fetch(s.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!v)return yield R(null);const b=new DataView(v,d-c,u-c+1);if(!n.validateData(b))throw new Error("Invalid media file");const S=n.parseInit(b),g=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!g)throw new ReferenceError("No way to load representation index");let P;if(f)P=new DataView(v,g.from-c,g.to-g.from+1);else{const T=yield yield R(this.fetch(s.url,{range:g,priority:o,measureThroughput:!1}));if(!T)return yield R(null);P=new DataView(T)}const E=n.parseSegments(P,S,g);return yield R({dataView:new DataView(v),segments:E})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return Pe(this,arguments,function*(){if(s.type!==ye.TEMPLATE)return yield R(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield R(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield R(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:H.NONE,size:void 0}));return yield R({segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=jl(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 ye.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case ye.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 Xt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var VS=He,FS=ni,US=ue,jS=US("match"),HS=function(i){var e;return VS(i)&&((e=i[jS])!==void 0?!!e:FS(i)=="RegExp")},GS=ci,YS=String,qS=function(i){if(GS(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return YS(i)},zS=Ye,WS=function(){var i=zS(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},QS=ve,JS=Oe,KS=nr,XS=WS,Kn=RegExp.prototype,ZS=function(i){var e=i.flags;return e===void 0&&!("flags"in Kn)&&!JS(i,"flags")&&KS(Kn,i)?QS(XS,i):e},va=$e,eg=dr,tg=Math.floor,rs=va("".charAt),ig=va("".replace),ss=va("".slice),rg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sg=/\$([$&'`]|\d{1,2})/g,ag=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,d=sg;return s!==void 0&&(s=eg(s),d=rg),ig(n,d,function(u,c){var h;switch(rs(c,0)){case"$":return"$";case"&":return i;case"`":return ss(e,0,t);case"'":return ss(e,o);case"<":h=s[ss(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=tg(f/10);return p===0?u:p<=l?r[p-1]===void 0?rs(c,1):r[p-1]+rs(c,1):u}h=r[f-1]}return h===void 0?"":h})},ng=we,og=ve,ma=$e,Xn=js,lg=se,ug=oi,dg=HS,$t=qS,cg=ur,hg=ZS,fg=ag,pg=ue,vg=pg("replace"),mg=TypeError,Ql=ma("".indexOf),bg=ma("".replace),Zn=ma("".slice),Sg=Math.max,eo=function(i,e,t){return t>i.length?-1:e===""?t:Ql(i,e,t)};ng({target:"String",proto:!0},{replaceAll:function(e,t){var r=Xn(this),s,n,o,l,d,u,c,h,f,p=0,m=0,v="";if(!ug(e)){if(s=dg(e),s&&(n=$t(Xn(hg(e))),!~Ql(n,"g")))throw mg("`.replaceAll` does not allow non-global regexes");if(o=cg(e,vg),o)return og(o,e,r,t);if(s)return bg($t(r),e,t)}for(l=$t(r),d=$t(e),u=lg(t),u||(t=$t(t)),c=d.length,h=Sg(1,c),p=eo(l,d,0);p!==-1;)f=u?$t(t(d,p,l)):fg(d,l,p,[],void 0,t),v+=Zn(l,m,p)+f,m=p+c,p=eo(l,d,p+h);return m<l.length&&(v+=Zn(l,m)),v}});var gg=ca,yg=gg("String","replaceAll"),Tg=yg,Eg=Tg,$g=Eg,kg=$g,to=kg;const io=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},as=(i,e)=>{let t=i;t=to(t,"$$","$");const r={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[s,n]of Object.entries(r)){const o=new RegExp(`\\$${s}(?:%0(\\d+)d)?\\$`,"g");t=to(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},Pg=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,m,v,b,S,g,P,E,T,w,F,O,I,U,N,_,G,K,te,$,D,z,ee,ie,he,_e;const j=new DOMParser().parseFromString(i,"application/xml"),ae={video:[],audio:[],text:[]},de=j.children[0],me=de.getElementsByTagName("Period")[0],it=me.children;let Re;const Je=de.getAttribute("mediaPresentationDuration"),rt=me.getAttribute("duration");if(Je)Re=io(Je);else if(rt){const Ie=io(rt);a.isNonNullable(Ie)&&(Re=Ie)}let Vt=0;const bt=(r=(t=de.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],tu=bt.includes(rr.WEBM_AS_IN_FFMPEG)||bt.includes(rr.WEBM_AS_IN_SPEC)?Ot.WEBM:Ot.MP4;for(const Ie of it){const Si=Ie.getAttribute("mimeType"),iu=Ie.getAttribute("codecs"),ba=(s=Ie.getAttribute("contentType"))!==null&&s!==void 0?s:Si==null?void 0:Si.split("/")[0],ru=(o=(n=Ie.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],su=Ie.querySelectorAll("Representation"),au=Ie.querySelector("SegmentTemplate");if(ba!=="text")for(const ne of su){const Ft=(l=ne.getAttribute("mimeType"))!==null&&l!==void 0?l:Si,Sa=(u=(d=ne.getAttribute("codecs"))!==null&&d!==void 0?d:iu)!==null&&u!==void 0?u:"",gi=(h=(c=ne.getAttribute("contentType"))!==null&&c!==void 0?c:Ft==null?void 0:Ft.split("/")[0])!==null&&h!==void 0?h:ba,nu=(p=(f=Ie.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&p!==void 0?p:[],ou=parseInt((m=ne.getAttribute("width"))!==null&&m!==void 0?m:"",10),ga=parseInt((v=ne.getAttribute("height"))!==null&&v!==void 0?v:"",10),ya=parseInt((b=ne.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Ta=(S=ne.getAttribute("frameRate"))!==null&&S!==void 0?S:"",lu=(g=ne.getAttribute("quality"))!==null&&g!==void 0?g:void 0,uu=Ta?fa(Ta):void 0,du=(P=ne.getAttribute("id"))!==null&&P!==void 0?P:(Vt++).toString(10),cu=gi==="video"?`${ga}p`:gi==="audio"?`${ya}Kbps`:Sa,hu=`${du}@${cu}`,fu=(w=(T=(E=ne.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",Ea=new URL(fu,e).toString(),pu=[...bt,...ru,...nu];let Sr;const vu=ne.querySelector("SegmentBase"),st=(F=ne.querySelector("SegmentTemplate"))!==null&&F!==void 0?F:au;if(vu){const Ut=(I=(O=ne.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&I!==void 0?I:"",[jt,yr]=Ut.split("-").map(at=>parseInt(at,10)),Ht={from:jt,to:yr},Gt=(U=ne.querySelector("SegmentBase"))===null||U===void 0?void 0:U.getAttribute("indexRange"),[Tr,yi]=Gt?Gt.split("-").map(at=>parseInt(at,10)):[],Yt=Gt?{from:Tr,to:yi}:void 0;Sr={type:ye.BYTE_RANGE,url:Ea,initRange:Ht,indexRange:Yt}}else if(st){const Ut={representationId:(N=ne.getAttribute("id"))!==null&&N!==void 0?N:void 0,bandwidth:(_=ne.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},jt=parseInt((G=st.getAttribute("timescale"))!==null&&G!==void 0?G:"",10),yr=(K=st.getAttribute("initialization"))!==null&&K!==void 0?K:"",Ht=st.getAttribute("media"),Gt=($=parseInt((te=st.getAttribute("startNumber"))!==null&&te!==void 0?te:"",10))!==null&&$!==void 0?$:1,Tr=as(yr,Ut);if(!Ht)throw new ReferenceError("No media attribute in SegmentTemplate");const yi=(D=st.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],Yt=[];if(yi.length){let at=Gt,nt=0;for(const qt of yi){const St=parseInt((z=qt.getAttribute("d"))!==null&&z!==void 0?z:"",10)*1e3,zt=parseInt((ee=qt.getAttribute("r"))!==null&&ee!==void 0?ee:"",10)||0,Wt=(he=parseInt((ie=qt.getAttribute("t"))!==null&&ie!==void 0?ie:"",10))!==null&&he!==void 0?he:void 0;for(let $a=0;$a<zt+1;$a++){const mu=as(Ht,Object.assign(Object.assign({},Ut),{segmentNumber:at.toString(10),segmentTime:Wt.toString(10)})),bu=Wt?Wt/jt:nt;nt+=St/jt;const Su=nt;at++,Yt.push({time:{from:bu,to:Su},url:mu})}}}else if(a.isNonNullable(Re)){const nt=parseInt((_e=st.getAttribute("duration"))!==null&&_e!==void 0?_e:"",10)/jt*1e3,qt=Math.ceil(Re/nt);let St=0;for(let zt=1;zt<qt;zt++){const Wt=as(Ht,Object.assign(Object.assign({},Ut),{segmentNumber:zt.toString(10),segmentTime:St.toString(10)}));Yt.push({time:{from:St,to:St+nt},url:Wt}),St+=nt}}Sr={type:ye.TEMPLATE,baseUrl:Ea,initUrl:Tr,segments:Yt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!gi||!Ft)continue;const gr={video:ge.VIDEO,audio:ge.AUDIO,text:ge.TEXT}[gi];gr&&ae[gr].push({id:hu,kind:gr,segmentReference:Sr,profiles:pu,duration:Re,bitrate:ya,mime:Ft,codecs:Sa,width:ou,height:ga,fps:uu,quality:lu})}}return{duration:Re,container:tu,representations:ae}},Ag=["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 wg=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.state$=new J(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 ut,this.initManifest=a.abortable(this.destroyController.signal,function(t,r){return Pe(this,arguments,function*(){this.element=t,this.state$.startTransitionTo(Se.MANIFEST_READY);const s=yield yield R(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 R(void 0);let n;try{n=Pg(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 R(void 0);const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest=Object.assign(Object.assign({},n),{representations:hi(Object.entries(n.representations).map(([l,d])=>[l,d.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 Pe(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 Jn(ge.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new Jn(ge.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 R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(r)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield R(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 MS({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(...Ag.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&&Fs(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={[ge.VIDEO]:this.videoBufferManager,[ge.AUDIO]:this.audioBufferManager,[ge.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),Fs(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(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 _g=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?mi(n):void 0)!==null&&o!==void 0?o:vt({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},Rg=({id:i,bitrate:e})=>({id:i,bitrate:e}),Ig=(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 Ng{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(X.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Le,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new eS,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===C.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=ze(this.params.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(ce(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new wg({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=We(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(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(),a.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(mt(this.video,t.isLooped,s)),this.subscription.add(qe(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(et(this.video,t.playbackRate,r.playbackRateState$,s)),n(tr(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===Se.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();a.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((v,b)=>b.bitrate-v.bitrate),p=Array.from(h.video).sort((v,b)=>b.bitrate-v.bitrate);if(!this.params.tuning.isAudioDisabled)for(const v of f){const b=Rg(v);b&&this.audioTracks.push({track:b,representation:v})}for(const v of p){const b=_g(v);if(b){this.videoTracks.push({track:b,representation:v});const S=!this.params.tuning.isAudioDisabled&&Ig(f,p,v);S&&this.audioRepresentations.set(v.id,S)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const m=this.selectVideoRepresentation();a.assertNonNullable(m),this.player.initRepresentations(m.id,(c=this.audioRepresentations.get(m.id))===null||c===void 0?void 0:c.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(),c=this.player.state$.getTransition();if(u!==Se.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(ge.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ge.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:S}})=>S===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=lt(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),v=vi(this.videoTracks.map(({track:S})=>S),{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}),b=l?v!=null?v:u:u!=null?u:v;return b&&((o=this.videoTracks.find(({track:S})=>S===b))===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(){tt(this.video).then(e=>{e||(this.videoState.setState(X.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Cg=5e3,xe={};var V;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const Bi=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class Dg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(V.INITIALIZING),this.textTracksManager=new Le,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!==V.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===C.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case V.STOPPED:break;case V.READY:case V.PLAYING:case V.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case V.STOPPED:this.prepare();break;case V.READY:case V.PLAYING:case V.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case V.PLAYING:break;case V.STOPPED:this.prepare();break;case V.READY:case V.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case V.PAUSED:break;case V.STOPPED:this.prepare();break;case V.READY:this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=ze(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(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),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"),Cg);vr(import("hls.js").then(s=>{e||(xe.Hls=s.default,xe.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(xe.Hls,"hls.js not loaded"),this.hls=new xe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){a.assertNonNullable(xe.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=We(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$),this.subscription.add(mt(this.video,e.isLooped,r)),this.subscription.add(qe(this.video,e.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(et(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(Bi(this.hls,xe.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(V.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(V.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)===V.READY&&this.videoState.setState(V.READY),this.videoState.getState()===V.PLAYING&&this.playIfAllowed()},r)),n(Bi(this.hls,xe.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:v,height:b}=h,S=(p=mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:vt({width:v,height:b});if(!S)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:m.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:v,height:b},fps:g};return this.trackLevels.set(m,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(Bi(this.hls,xe.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ce(u))),t.hostname$),this.subscription.add(De(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=Bi(this.hls,xe.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(De(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(V.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(V.PLAYING),(yield tt(this.video))||(this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(V.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(V.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const ro="X-Playback-Duration";var so=i=>Q(void 0,void 0,void 0,function*(){const e=yield Ct(i,{method:"HEAD"});return e.headers.has(ro)?parseInt(e.headers.get(ro),10):void 0});const Og=i=>{let e=null;if(i.QUALITY&&(e=mi(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=vt({width:t,height:r})}return e!=null?e:null},Jl=(i,e=i)=>Q(void 0,void 0,void 0,function*(){var t;const n=(yield(yield Ct(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=hi(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Og(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 v;if(c.RESOLUTION){const[S,g]=c.RESOLUTION.split("x").map(P=>parseInt(P,10));S&&g&&(v={width:S,height:g})}const b=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:b,bandwidth:p,size:v,fps:m})}return o});var Y;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(Y||(Y={}));class Lg{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(Y.STOPPED),this.textTracksManager=new Le,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ha,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!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(s===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Y.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===C.Requested){this.videoState.startTransitionTo(Y.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(s){case Y.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),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.liveOffset.pause(),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.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 Y.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=ze(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),Jl(Nt(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(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",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=We(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$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Y.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)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,r)),this.subscription.add(s.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),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(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Y.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===C.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=Nt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),so(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{Ct(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();so(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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 xg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(W.STOPPED),this.textTracksManager=new Le,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===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===C.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=ze(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.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(ce(this.params.source.url)),Jl(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=We(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$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(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(ce(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===W.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===C.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(){tt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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 Bg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(Z.STOPPED),this.trackUrls={},this.textTracksManager=new Le,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===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:d*1e3,forcePrecise:!0});return}switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&l.state===C.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=ze(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=We(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$),this.subscription.add(mt(this.video,t.isLooped,r)),this.subscription.add(qe(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(et(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=Dt(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(ce(s))}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const ao=["stun:videostun.mycdn.me:80"],Mg=1e3,Vg=3,ns=()=>null;class Fg{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=ns,this.externalStopCallback=ns,this.externalErrorCallback=ns,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:ao}]};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),Mg)}normalizeOptions(e={}){const t={stunServerList:ao,maxRetryNumber:Vg,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var q;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(q||(q={}));class Ug{constructor(e){this.videoState=new J(q.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(r===exports.PlaybackState.STOPPED){t!==q.STOPPED&&(this.videoState.startTransitionTo(q.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(q.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===q.STOPPED){this.videoState.startTransitionTo(q.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case q.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed());return;case q.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(q.PAUSED),this.video.pause()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case q.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(q.PLAYING),this.playIfAllowed()):(s==null?void 0:s.to)===exports.PlaybackState.PAUSED&&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=ze(e.container),this.liveStreamClient=new Fg(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=We(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)===q.READY&&this.videoState.setState(q.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(q.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(q.PLAYING)},r)).add(s.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(qe(this.video,t.volume,s.volumeState$,r)).add(s.volumeState$.subscribe(e.volume$,r)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case q.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case q.READY:break;case q.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case q.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.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(q.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:a.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){tt(this.video).then(e=>{e||(this.videoState.setState(q.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class no{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 jg=()=>{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")},os,ls,us,ds,cs,hs,Mi,fs,Vi,ps,Fi,vs,Ui,ms,ji,bs;const Kl=jg(),Ke=document.createElement("video"),Be={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ls=(os=window.SourceBuffer)===null||os===void 0?void 0:os.prototype)===null||ls===void 0?void 0:ls.appendBuffer)),hls:Boolean(((us=Ke.canPlayType)===null||us===void 0?void 0:us.call(Ke,"application/x-mpegurl"))||((ds=Ke.canPlayType)===null||ds===void 0?void 0:ds.call(Ke,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},be={mp4:Boolean((cs=Ke.canPlayType)===null||cs===void 0?void 0:cs.call(Ke,"video/mp4")),webm:Boolean((hs=Ke.canPlayType)===null||hs===void 0?void 0:hs.call(Ke,"video/webm")),cmaf:!0},Xe={h264:Boolean((fs=(Mi=window.MediaSource)===null||Mi===void 0?void 0:Mi.isTypeSupported)===null||fs===void 0?void 0:fs.call(Mi,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((ps=(Vi=window.MediaSource)===null||Vi===void 0?void 0:Vi.isTypeSupported)===null||ps===void 0?void 0:ps.call(Vi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((vs=(Fi=window.MediaSource)===null||Fi===void 0?void 0:Fi.isTypeSupported)===null||vs===void 0?void 0:vs.call(Fi,'video/webm; codecs="vp9"')),aac:Boolean((ms=(Ui=window.MediaSource)===null||Ui===void 0?void 0:Ui.isTypeSupported)===null||ms===void 0?void 0:ms.call(Ui,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((bs=(ji=window.MediaSource)===null||ji===void 0?void 0:ji.isTypeSupported)===null||bs===void 0?void 0:bs.call(ji,'audio/webm; codecs="opus"'))},kt=(Xe.h264||Xe.h265)&&Xe.aac,br=Be.hls&&be.mp4,Hg=Boolean(window.WebSocket),Gg=()=>Object.keys(Xe).filter(i=>Xe[i]),Yg=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_SEP:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_WEBM:return Be.mse&&be.webm&&Xe.vp9&&Xe.opus;case exports.VideoFormat.DASH_LIVE:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.DASH_LIVE_CMAF:return Be.mse&&be.mp4&&kt&&be.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Be.mse&&be.mp4&&kt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return br||e&&Be.mse&&be.mp4&&kt;case exports.VideoFormat.MPEG:return be.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Be.webrtc&&Hg&&Xe.h264&&(be.mp4||be.webm);default:return a.assertNever(t)}}),qg=()=>Kl?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:br?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],zg=()=>Kl?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:br?[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],oo=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Wg=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$,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="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const lo={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},Qg={cacheDuration:12e4},Jg={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Kg={maxPausedTime:3e4},uo={maxPausedTime:3e4};class Xg{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),element$:new a.ValueSubject(void 0)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Yg([...zg(),...qg()],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 no(s);const n=[...oo(!0),...oo(!1)];this.chromecastFormatsIterator=new no(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!==C.None;this.params.desiredState.seekState.setState({state:C.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 fe.SCREEN:return this.createScreenProvider(t);case fe.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 $S(Object.assign(Object.assign({},o),{source:l,config:Qg}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new Yn(Object.assign(Object.assign({},o),{source:l,format:e,config:uo})):new Ng(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Yn(Object.assign(Object.assign({},o),{source:l,format:e,config:uo}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),br||!this.params.tuning.useHlsJs?new xg(Object.assign(Object.assign({},o),{source:l})):new Dg(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 Lg(Object.assign(Object.assign({},o),{source:l,config:Kg}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bg(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new SS(Object.assign(Object.assign({},o),{source:l,config:Jg}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Ug({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 Ab({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()?fe.CHROMECAST:fe.SCREEN}chooseFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case fe.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case fe.SCREEN:return this.screenFormatsIterator.next();case fe.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case fe.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case fe.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 hi(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$,Wg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:lo.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===fe.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<lo.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(r++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var Te;(function(i){i[i.LOCAL_STORAGE=0]="LOCAL_STORAGE",i[i.SESSION_STORAGE=1]="SESSION_STORAGE",i[i.RUNTIME=2]="RUNTIME"})(Te||(Te={}));const Xl=new Map;let dt=Te.RUNTIME;const Ss=`vk-videoplayer-dummy-key-${Math.random()}`,Zg=()=>{try{localStorage.setItem(Ss,"test"),localStorage.removeItem(Ss),dt=Te.LOCAL_STORAGE}catch(i){if(i instanceof DOMException||i instanceof TypeError)try{sessionStorage.getItem(Ss),dt=Te.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)dt=Te.RUNTIME;else throw e}else throw i}};Zg();const ey=i=>{var e,t;switch(dt){case Te.LOCAL_STORAGE:return(e=localStorage.getItem(i))!==null&&e!==void 0?e:void 0;case Te.SESSION_STORAGE:return(t=sessionStorage.getItem(i))!==null&&t!==void 0?t:void 0;case Te.RUNTIME:return Xl.get(i);default:a.assertNever(dt)}},co=(i,e)=>{switch(dt){case Te.LOCAL_STORAGE:try{localStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Te.SESSION_STORAGE:try{sessionStorage.setItem(i,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case Te.RUNTIME:return void Xl.set(i,e);default:a.assertNever(dt)}},Us=(i,e,t)=>t*e+(1-t)*i,Zl=(i,e)=>i.reduce((t,r)=>t+r,0)/e,ty=(i,e,t,r)=>{let s=0,n=t;const o=Zl(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 eu{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 Ce(`raw_${r}`),this.smoothedSeries$=new Ce(`smoothed_${r}`),this.reportedSeries$=new Ce(`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 iy extends eu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Us(this.slow,e,this.params.emaAlphaSlow),this.fast=Us(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class ry extends eu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Zl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Us(this.emaSmoothed,e,this.params.emaAlpha);const r=ty(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class ho{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new iy({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new ry({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}}const sy=5e3,fo="one_video_throughput",po="one_video_rtt",je=window.navigator.connection,vo=()=>{const i=je==null?void 0:je.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},mo=()=>{const i=je==null?void 0:je.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},bo=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class ri{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=ri.load(fo)||(e.useBrowserEstimation?vo():void 0)||sy,n=(r=(t=ri.load(po))!==null&&t!==void 0?t:e.useBrowserEstimation?mo():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(bo(s,n,e.rttPenaltyRequestSize)),this.throughput=ho.getSmoothedValue(s,-1,e),this.rtt=ho.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=vo();d&&this.throughput.next(d);const u=mo();a.isNonNullable(u)&&this.rtt.next(u)};je&&"onchange"in je&&this.subscription.add(a.fromEvent(je,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{co(fo,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{co(po,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})=>bo(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(ri.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=ey(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const So={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,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}},ay=i=>{const e={};for(const t of Object.keys(So)){const r=So[t],s=i[t];Array.isArray(r)&&Array.isArray(s)?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 ny=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===C.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===C.None))),oy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const go=({playbackState:i,seekState:e,playbackAbort$:t,looped$:r,position$:s})=>new a.Observable(n=>{let o;const l=i.transitionEnded$.pipe(a.filter(p=>(p.from===exports.PlaybackState.PAUSED||p.from===exports.PlaybackState.STOPPED)&&p.to===exports.PlaybackState.PLAYING)),d=i.stateChangeEnded$.pipe(a.filter(p=>p.from===exports.PlaybackState.PLAYING&&p.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(a.filter(({to:p})=>{var m,v;return p.state===C.Requested&&((v=(m=i.getTransition())===null||m===void 0?void 0:m.from)!==null&&v!==void 0?v:i.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(a.filter(({from:p,to:m})=>{var v,b;return p.state===C.Applying&&m.state===C.None&&((b=(v=i.getTransition())===null||v===void 0?void 0:v.from)!==null&&b!==void 0?b:i.getState())===exports.PlaybackState.PLAYING})),h=a.merge(l,c).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable)),f=a.merge(a.merge(d,u,t),r).pipe(a.map(()=>s.getValue()),a.filter(a.isNonNullable));return new a.Subscription().add(h.subscribe(p=>{o=p})).add(f.subscribe(p=>{if(a.isNullable(o)||o===p)return;const m={from:o,to:p};o=void 0,n.next(m)}))});class ly{constructor(e={}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new J(exports.PlaybackState.STOPPED),seekState:new J({state:C.None}),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),playbackRate:new J(1),externalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({})},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),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),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,started$:new a.Subject,willPause$:new a.Subject,willResume$: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),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:Kb},this.initLogs(),this.tuning=ay(e),this.chromecastInitializer=new Ru({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ri(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=oy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Xg({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(),(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:C.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===C.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$.pipe(a.filter(()=>!this.isPlaybackStarted),a.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===C.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},d),{state:C.Applying})):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(d=>d.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Zi(u)?1:Zi(c)?-1:qi(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.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(d=>d?{start:d.from,end:d.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(e.providerOutput.volume$.pipe(a.map(d=>d.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(d=>d.volume),a.filterChanged()).subscribe(this.info.volume$)).add(ny({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(d=>({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(()=>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:d})=>d===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 d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||r.getValue();return d&&!u}),a.filterChanged());this.subscription.add(n.subscribe(d=>{d?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))}));const o=new a.Subscription;this.subscription.add(o);const l=a.merge(a.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(a.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(a.filterChanged()).subscribe(d=>{switch(a.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new a.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(a.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(go({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(a.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{var u,c;const h=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=d==null?void 0:d.size)===null||u===void 0?void 0:u.width,height:(c=d==null?void 0:d.size)===null||c===void 0?void 0:c.height},{width:h==null?void 0:h.videoWidth,height:h==null?void 0:h.videoHeight})}))}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=vi(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),Jb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>Qb(r)),this.providerContainer.current$.subscribe(({type:r})=>Oi("provider",r)),t.duration$.subscribe(r=>Oi("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Oi("tracks",r)),this.events.fatalError$.subscribe(new Ce("fatalError")),this.events.managedError$.subscribe(new Ce("managedError")),t.position$.subscribe(new Ce("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Ce("quality")),this.info.currentBuffer$.subscribe(new Ce("buffer")),t.isBuffering$.subscribe(new Ce("isBuffering"))].forEach(r=>this.subscription.add(r)),Oi("codecs",Gg())}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.transitionEnded$).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 uy=`${wu}@${Au}`;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=ly;exports.SDK_VERSION=uy;
|