@vkontakte/videoplayer-core 2.0.91 → 2.0.92-dev.61e3488.0
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 +7 -7
- package/es2015.esm.js +7 -7
- package/es2018.cjs.js +7 -7
- package/es2018.esm.js +7 -7
- package/esnext.cjs.js +7 -7
- package/esnext.esm.js +7 -7
- package/evergreen.esm.js +7 -7
- package/index.d.ts +23 -0
- package/package.json +2 -2
package/es2015.cjs.js
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.92-dev.61e3488.0
|
|
3
|
+
* Fri, 27 Oct 2023 13:31:01 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-92/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Mu=Object.create;var ja=Object.defineProperty;var Vu=Object.getOwnPropertyDescriptor;var Fu=Object.getOwnPropertyNames;var Uu=Object.getPrototypeOf,ju=Object.prototype.hasOwnProperty;var Hu=(i,e,t,r)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Fu(e))!ju.call(i,s)&&s!==t&&ja(i,s,{get:()=>e[s],enumerable:!(r=Vu(e,s))||r.enumerable});return i};var Ha=(i,e,t)=>(t=i!=null?Mu(Uu(i)):{},Hu(e||!i||!i.__esModule?ja(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Gu=require("lodash/debounce.js");const Bo="2.0.91";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ue;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ue||(ue={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var B;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(B||(B={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(exports.Surface||(exports.Surface={}));function 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 I(i){return this instanceof I?(this.v=i,this):new I(i)}function be(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var r=t.apply(i,e||[]),s,n=[];return s={},o("next"),o("throw"),o("return"),s[Symbol.asyncIterator]=function(){return this},s;function o(f){r[f]&&(s[f]=function(p){return new Promise(function(m,b){n.push([f,p,m,b])>1||l(f,p)})})}function l(f,p){try{d(r[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof I?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 Yu=i=>new Promise((e,t)=>{const r=document.createElement("script");r.setAttribute("src",i),r.onload=()=>e,r.onerror=()=>t,document.body.appendChild(r)});class qu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const r="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${r}`}),e.isDisabled||!r)return;const s=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;s?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Yu("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var r,s,n;(n=(s=(r=cast.framework.CastContext.getInstance())===null||r===void 0?void 0:r.getCurrentSession())===null||s===void 0?void 0:s.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),r=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(r,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(s=>{var n,o;switch(s.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=r.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(s.sessionState)}})).add(a.merge(a.fromEvent(r,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(s=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(s)}`})}),a.map(s=>s.castState)),a.observableFrom([r.getCastState()])).pipe(a.filterChanged(),a.map(zu),a.tap(s=>{this.log({message:`realCastState$: ${s}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(s=>{var n;const o=s===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const 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 zu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var Nr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function lr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var ke=function(i){try{return!!i()}catch(e){return!0}},Wu=ke,ur=!Wu(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Mo=ur,Vo=Function.prototype,Ds=Vo.call,Qu=Mo&&Vo.bind.bind(Ds,Ds),Pe=Mo?Qu:function(i){return function(){return Ds.apply(i,arguments)}},Fo=Pe,Ku=Fo({}.toString),Ju=Fo("".slice),ui=function(i){return Ju(Ku(i),8,-1)},Xu=Pe,Zu=ke,ed=ui,xr=Object,td=Xu("".split),id=Zu(function(){return!xr("z").propertyIsEnumerable(0)})?function(i){return ed(i)=="String"?td(i,""):xr(i)}:xr,di=function(i){return i==null},rd=di,sd=TypeError,ra=function(i){if(rd(i))throw sd("Can't call method on "+i);return i},ad=id,nd=ra,ci=function(i){return ad(nd(i))},Ft={},wi=function(i){return i&&i.Math==Math&&i},le=wi(typeof globalThis=="object"&&globalThis)||wi(typeof window=="object"&&window)||wi(typeof self=="object"&&self)||wi(typeof Nr=="object"&&Nr)||function(){return this}()||Nr||Function("return this")(),Ns=typeof document=="object"&&document.all,od=typeof Ns=="undefined"&&Ns!==void 0,Uo={all:Ns,IS_HTMLDDA:od},jo=Uo,ld=jo.all,ae=jo.IS_HTMLDDA?function(i){return typeof i=="function"||i===ld}:function(i){return typeof i=="function"},ud=le,dd=ae,Ga=ud.WeakMap,cd=dd(Ga)&&/native code/.test(String(Ga)),Ya=ae,Ho=Uo,hd=Ho.all,ze=Ho.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Ya(i)||i===hd}:function(i){return typeof i=="object"?i!==null:Ya(i)},fd=ke,st=!fd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),vt={},pd=le,qa=ze,xs=pd.document,md=qa(xs)&&qa(xs.createElement),sa=function(i){return md?xs.createElement(i):{}},vd=st,bd=ke,Sd=sa,Go=!vd&&!bd(function(){return Object.defineProperty(Sd("div"),"a",{get:function(){return 7}}).a!=7}),gd=st,yd=ke,Yo=gd&&yd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Td=ze,Ed=String,$d=TypeError,We=function(i){if(Td(i))return i;throw $d(Ed(i)+" is not an object")},kd=ur,Ai=Function.prototype.call,ge=kd?Ai.bind(Ai):function(){return Ai.apply(Ai,arguments)},aa={},Lr=aa,Or=le,Pd=ae,za=function(i){return Pd(i)?i:void 0},bt=function(i,e){return arguments.length<2?za(Lr[i])||za(Or[i]):Lr[i]&&Lr[i][e]||Or[i]&&Or[i][e]},wd=Pe,dr=wd({}.isPrototypeOf),cr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",qo=le,Br=cr,Wa=qo.process,Qa=qo.Deno,Ka=Wa&&Wa.versions||Qa&&Qa.version,Ja=Ka&&Ka.v8,_e,Zi;Ja&&(_e=Ja.split("."),Zi=_e[0]>0&&_e[0]<4?1:+(_e[0]+_e[1]));!Zi&&Br&&(_e=Br.match(/Edge\/(\d+)/),(!_e||_e[1]>=74)&&(_e=Br.match(/Chrome\/(\d+)/),_e&&(Zi=+_e[1])));var zo=Zi,Xa=zo,Ad=ke,_d=le,Rd=_d.String,Wo=!!Object.getOwnPropertySymbols&&!Ad(function(){var i=Symbol();return!Rd(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&Xa&&Xa<41}),Cd=Wo,Qo=Cd&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Id=bt,Dd=ae,Nd=dr,xd=Qo,Ld=Object,Ko=xd?function(i){return typeof i=="symbol"}:function(i){var e=Id("Symbol");return Dd(e)&&Nd(e.prototype,Ld(i))},Od=String,hr=function(i){try{return Od(i)}catch(e){return"Object"}},Bd=ae,Md=hr,Vd=TypeError,St=function(i){if(Bd(i))return i;throw Vd(Md(i)+" is not a function")},Fd=St,Ud=di,fr=function(i,e){var t=i[e];return Ud(t)?void 0:Fd(t)},Mr=ge,Vr=ae,Fr=ze,jd=TypeError,Hd=function(i,e){var t,r;if(e==="string"&&Vr(t=i.toString)&&!Fr(r=Mr(t,i))||Vr(t=i.valueOf)&&!Fr(r=Mr(t,i))||e!=="string"&&Vr(t=i.toString)&&!Fr(r=Mr(t,i)))return r;throw jd("Can't convert object to primitive value")},Jo={exports:{}},Gd=!0,Za=le,Yd=Object.defineProperty,qd=function(i,e){try{Yd(Za,i,{value:e,configurable:!0,writable:!0})}catch(t){Za[i]=e}return e},zd=le,Wd=qd,en="__core-js_shared__",Qd=zd[en]||Wd(en,{}),na=Qd,tn=na;(Jo.exports=function(i,e){return tn[i]||(tn[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var Xo=Jo.exports,Kd=ra,Jd=Object,pr=function(i){return Jd(Kd(i))},Xd=Pe,Zd=pr,ec=Xd({}.hasOwnProperty),Ve=Object.hasOwn||function(e,t){return ec(Zd(e),t)},tc=Pe,ic=0,rc=Math.random(),sc=tc(1 .toString),Zo=function(i){return"Symbol("+(i===void 0?"":i)+")_"+sc(++ic+rc,36)},ac=le,nc=Xo,rn=Ve,oc=Zo,lc=Wo,uc=Qo,It=ac.Symbol,Ur=nc("wks"),dc=uc?It.for||It:It&&It.withoutSetter||oc,ce=function(i){return rn(Ur,i)||(Ur[i]=lc&&rn(It,i)?It[i]:dc("Symbol."+i)),Ur[i]},cc=ge,sn=ze,an=Ko,hc=fr,fc=Hd,pc=ce,mc=TypeError,vc=pc("toPrimitive"),bc=function(i,e){if(!sn(i)||an(i))return i;var t=hc(i,vc),r;if(t){if(e===void 0&&(e="default"),r=cc(t,i,e),!sn(r)||an(r))return r;throw mc("Can't convert object to primitive value")}return e===void 0&&(e="number"),fc(i,e)},Sc=bc,gc=Ko,oa=function(i){var e=Sc(i,"string");return gc(e)?e:e+""},yc=st,Tc=Go,Ec=Yo,_i=We,nn=oa,$c=TypeError,jr=Object.defineProperty,kc=Object.getOwnPropertyDescriptor,Hr="enumerable",Gr="configurable",Yr="writable";vt.f=yc?Ec?function(e,t,r){if(_i(e),t=nn(t),_i(r),typeof e=="function"&&t==="prototype"&&"value"in r&&Yr in r&&!r[Yr]){var s=kc(e,t);s&&s[Yr]&&(e[t]=r.value,r={configurable:Gr in r?r[Gr]:s[Gr],enumerable:Hr in r?r[Hr]:s[Hr],writable:!1})}return jr(e,t,r)}:jr:function(e,t,r){if(_i(e),t=nn(t),_i(r),Tc)try{return jr(e,t,r)}catch(s){}if("get"in r||"set"in r)throw $c("Accessors not supported");return"value"in r&&(e[t]=r.value),e};var mr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Pc=st,wc=vt,Ac=mr,hi=Pc?function(i,e,t){return wc.f(i,e,Ac(1,t))}:function(i,e,t){return i[e]=t,i},_c=Xo,Rc=Zo,on=_c("keys"),la=function(i){return on[i]||(on[i]=Rc(i))},ua={},Cc=cd,el=le,Ic=ze,Dc=hi,qr=Ve,zr=na,Nc=la,xc=ua,ln="Object already initialized",Ls=el.TypeError,Lc=el.WeakMap,er,ai,tr,Oc=function(i){return tr(i)?ai(i):er(i,{})},Bc=function(i){return function(e){var t;if(!Ic(e)||(t=ai(e)).type!==i)throw Ls("Incompatible receiver, "+i+" required");return t}};if(Cc||zr.state){var De=zr.state||(zr.state=new Lc);De.get=De.get,De.has=De.has,De.set=De.set,er=function(i,e){if(De.has(i))throw Ls(ln);return e.facade=i,De.set(i,e),e},ai=function(i){return De.get(i)||{}},tr=function(i){return De.has(i)}}else{var Pt=Nc("state");xc[Pt]=!0,er=function(i,e){if(qr(i,Pt))throw Ls(ln);return e.facade=i,Dc(i,Pt,e),e},ai=function(i){return qr(i,Pt)?i[Pt]:{}},tr=function(i){return qr(i,Pt)}}var tl={set:er,get:ai,has:tr,enforce:Oc,getterFor:Bc},Mc=ur,il=Function.prototype,un=il.apply,dn=il.call,rl=typeof Reflect=="object"&&Reflect.apply||(Mc?dn.bind(un):function(){return dn.apply(un,arguments)}),Vc=ui,Fc=Pe,sl=function(i){if(Vc(i)==="Function")return Fc(i)},da={},al={},nl={}.propertyIsEnumerable,ol=Object.getOwnPropertyDescriptor,Uc=ol&&!nl.call({1:2},1);al.f=Uc?function(e){var t=ol(this,e);return!!t&&t.enumerable}:nl;var jc=st,Hc=ge,Gc=al,Yc=mr,qc=ci,zc=oa,Wc=Ve,Qc=Go,cn=Object.getOwnPropertyDescriptor;da.f=jc?cn:function(e,t){if(e=qc(e),t=zc(t),Qc)try{return cn(e,t)}catch(r){}if(Wc(e,t))return Yc(!Hc(Gc.f,e,t),e[t])};var Kc=ke,Jc=ae,Xc=/#|\.prototype\./,fi=function(i,e){var t=eh[Zc(i)];return t==ih?!0:t==th?!1:Jc(e)?Kc(e):!!e},Zc=fi.normalize=function(i){return String(i).replace(Xc,".").toLowerCase()},eh=fi.data={},th=fi.NATIVE="N",ih=fi.POLYFILL="P",ll=fi,hn=sl,rh=St,sh=ur,ah=hn(hn.bind),vr=function(i,e){return rh(i),e===void 0?i:sh?ah(i,e):function(){return i.apply(e,arguments)}},Ri=le,nh=rl,oh=sl,lh=ae,uh=da.f,dh=ll,wt=aa,ch=vr,At=hi,fn=Ve,hh=function(i){var e=function(t,r,s){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,r)}return new i(t,r,s)}return nh(i,this,arguments)};return e.prototype=i.prototype,e},Ce=function(i,e){var t=i.target,r=i.global,s=i.stat,n=i.proto,o=r?Ri:s?Ri[t]:(Ri[t]||{}).prototype,l=r?wt:wt[t]||At(wt,t,{})[t],d=l.prototype,u,c,h,f,p,m,b,y,T;for(f in e)u=dh(r?f:t+(s?".":"#")+f,i.forced),c=!u&&o&&fn(o,f),m=l[f],c&&(i.dontCallGetSet?(T=uh(o,f),b=T&&T.value):b=o[f]),p=c&&b?b:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?y=ch(p,Ri):i.wrap&&c?y=hh(p):n&&lh(p)?y=oh(p):y=p,(i.sham||p&&p.sham||m&&m.sham)&&At(y,"sham",!0),At(l,f,y),n&&(h=t+"Prototype",fn(wt,h)||At(wt,h,{}),At(wt[h],f,p),i.real&&d&&(u||!d[f])&&At(d,f,p)))},Os=st,fh=Ve,ul=Function.prototype,ph=Os&&Object.getOwnPropertyDescriptor,ca=fh(ul,"name"),mh=ca&&function(){}.name==="something",vh=ca&&(!Os||Os&&ph(ul,"name").configurable),bh={EXISTS:ca,PROPER:mh,CONFIGURABLE:vh},dl={},Sh=Math.ceil,gh=Math.floor,yh=Math.trunc||function(e){var t=+e;return(t>0?gh:Sh)(t)},Th=yh,ha=function(i){var e=+i;return e!==e||e===0?0:Th(e)},Eh=ha,$h=Math.max,kh=Math.min,Ph=function(i,e){var t=Eh(i);return t<0?$h(t+e,0):kh(t,e)},wh=ha,Ah=Math.min,_h=function(i){return i>0?Ah(wh(i),9007199254740991):0},Rh=_h,fa=function(i){return Rh(i.length)},Ch=ci,Ih=Ph,Dh=fa,pn=function(i){return function(e,t,r){var s=Ch(e),n=Dh(s),o=Ih(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}},Nh={includes:pn(!0),indexOf:pn(!1)},xh=Pe,Wr=Ve,Lh=ci,Oh=Nh.indexOf,Bh=ua,mn=xh([].push),Mh=function(i,e){var t=Lh(i),r=0,s=[],n;for(n in t)!Wr(Bh,n)&&Wr(t,n)&&mn(s,n);for(;e.length>r;)Wr(t,n=e[r++])&&(~Oh(s,n)||mn(s,n));return s},cl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Vh=Mh,Fh=cl,Uh=Object.keys||function(e){return Vh(e,Fh)},jh=st,Hh=Yo,Gh=vt,Yh=We,qh=ci,zh=Uh;dl.f=jh&&!Hh?Object.defineProperties:function(e,t){Yh(e);for(var r=qh(t),s=zh(t),n=s.length,o=0,l;n>o;)Gh.f(e,l=s[o++],r[l]);return e};var Wh=bt,hl=Wh("document","documentElement"),Qh=We,Kh=dl,vn=cl,Jh=ua,Xh=hl,Zh=sa,ef=la,bn=">",Sn="<",Bs="prototype",Ms="script",fl=ef("IE_PROTO"),Qr=function(){},pl=function(i){return Sn+Ms+bn+i+Sn+"/"+Ms+bn},gn=function(i){i.write(pl("")),i.close();var e=i.parentWindow.Object;return i=null,e},tf=function(){var i=Zh("iframe"),e="java"+Ms+":",t;return i.style.display="none",Xh.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(pl("document.F=Object")),t.close(),t.F},Ci,Qi=function(){try{Ci=new ActiveXObject("htmlfile")}catch(e){}Qi=typeof document!="undefined"?document.domain&&Ci?gn(Ci):tf():gn(Ci);for(var i=vn.length;i--;)delete Qi[Bs][vn[i]];return Qi()};Jh[fl]=!0;var ml=Object.create||function(e,t){var r;return e!==null?(Qr[Bs]=Qh(e),r=new Qr,Qr[Bs]=null,r[fl]=e):r=Qi(),t===void 0?r:Kh.f(r,t)},rf=ke,sf=!rf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),af=Ve,nf=ae,of=pr,lf=la,uf=sf,yn=lf("IE_PROTO"),Vs=Object,df=Vs.prototype,vl=uf?Vs.getPrototypeOf:function(i){var e=of(i);if(af(e,yn))return e[yn];var t=e.constructor;return nf(t)&&e instanceof t?t.prototype:e instanceof Vs?df:null},cf=hi,pa=function(i,e,t,r){return r&&r.enumerable?i[e]=t:cf(i,e,t),i},hf=ke,ff=ae,pf=ze,mf=ml,Tn=vl,vf=pa,bf=ce,Fs=bf("iterator"),bl=!1,Ye,Kr,Jr;[].keys&&(Jr=[].keys(),"next"in Jr?(Kr=Tn(Tn(Jr)),Kr!==Object.prototype&&(Ye=Kr)):bl=!0);var Sf=!pf(Ye)||hf(function(){var i={};return Ye[Fs].call(i)!==i});Sf?Ye={}:Ye=mf(Ye);ff(Ye[Fs])||vf(Ye,Fs,function(){return this});var Sl={IteratorPrototype:Ye,BUGGY_SAFARI_ITERATORS:bl},gf=ce,yf=gf("toStringTag"),gl={};gl[yf]="z";var ma=String(gl)==="[object z]",Tf=ma,Ef=ae,Ki=ui,$f=ce,kf=$f("toStringTag"),Pf=Object,wf=Ki(function(){return arguments}())=="Arguments",Af=function(i,e){try{return i[e]}catch(t){}},pi=Tf?Ki:function(i){var e,t,r;return i===void 0?"Undefined":i===null?"Null":typeof(t=Af(e=Pf(i),kf))=="string"?t:wf?Ki(e):(r=Ki(e))=="Object"&&Ef(e.callee)?"Arguments":r},_f=ma,Rf=pi,Cf=_f?{}.toString:function(){return"[object "+Rf(this)+"]"},If=ma,Df=vt.f,Nf=hi,xf=Ve,Lf=Cf,Of=ce,En=Of("toStringTag"),va=function(i,e,t,r){if(i){var s=t?i:i.prototype;xf(s,En)||Df(s,En,{configurable:!0,value:e}),r&&!If&&Nf(s,"toString",Lf)}},Bf=Sl.IteratorPrototype,Mf=ml,Vf=mr,Ff=va,Uf=Ft,jf=function(){return this},Hf=function(i,e,t,r){var s=e+" Iterator";return i.prototype=Mf(Bf,{next:Vf(+!r,t)}),Ff(i,s,!1,!0),Uf[s]=jf,i},Gf=Ce,Yf=ge,yl=bh,qf=Hf,zf=vl,Wf=va,$n=pa,Qf=ce,kn=Ft,Tl=Sl,Kf=yl.PROPER;yl.CONFIGURABLE;Tl.IteratorPrototype;var Ii=Tl.BUGGY_SAFARI_ITERATORS,Xr=Qf("iterator"),Pn="keys",Di="values",wn="entries",Jf=function(){return this},Xf=function(i,e,t,r,s,n,o){qf(t,e,r);var l=function(T){if(T===s&&f)return f;if(!Ii&&T in c)return c[T];switch(T){case Pn:return function(){return new t(this,T)};case Di:return function(){return new t(this,T)};case wn:return function(){return new t(this,T)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[Xr]||c["@@iterator"]||s&&c[s],f=!Ii&&h||l(s),p=e=="Array"&&c.entries||h,m,b,y;if(p&&(m=zf(p.call(new i)),m!==Object.prototype&&m.next&&(Wf(m,d,!0,!0),kn[d]=Jf)),Kf&&s==Di&&h&&h.name!==Di&&(u=!0,f=function(){return Yf(h,this)}),s)if(b={values:l(Di),keys:n?f:l(Pn),entries:l(wn)},o)for(y in b)(Ii||u||!(y in c))&&$n(c,y,b[y]);else Gf({target:e,proto:!0,forced:Ii||u},b);return o&&c[Xr]!==f&&$n(c,Xr,f,{name:s}),kn[e]=f,b},Zf=function(i,e){return{value:i,done:e}},ep=ci,An=Ft,El=tl;vt.f;var tp=Xf,Ni=Zf,$l="Array Iterator",ip=El.set,rp=El.getterFor($l);tp(Array,"Array",function(i,e){ip(this,{type:$l,target:ep(i),index:0,kind:e})},function(){var i=rp(this),e=i.target,t=i.kind,r=i.index++;return!e||r>=e.length?(i.target=void 0,Ni(void 0,!0)):t=="keys"?Ni(r,!1):t=="values"?Ni(e[r],!1):Ni([r,e[r]],!1)},"values");An.Arguments=An.Array;var sp=ce,ap=Ft,np=sp("iterator"),op=Array.prototype,lp=function(i){return i!==void 0&&(ap.Array===i||op[np]===i)},up=pi,_n=fr,dp=di,cp=Ft,hp=ce,fp=hp("iterator"),kl=function(i){if(!dp(i))return _n(i,fp)||_n(i,"@@iterator")||cp[up(i)]},pp=ge,mp=St,vp=We,bp=hr,Sp=kl,gp=TypeError,yp=function(i,e){var t=arguments.length<2?Sp(i):e;if(mp(t))return vp(pp(t,i));throw gp(bp(i)+" is not iterable")},Tp=ge,Rn=We,Ep=fr,$p=function(i,e,t){var r,s;Rn(i);try{if(r=Ep(i,"return"),!r){if(e==="throw")throw t;return t}r=Tp(r,i)}catch(n){s=!0,r=n}if(e==="throw")throw t;if(s)throw r;return Rn(r),t},kp=vr,Pp=ge,wp=We,Ap=hr,_p=lp,Rp=fa,Cn=dr,Cp=yp,Ip=kl,In=$p,Dp=TypeError,Ji=function(i,e){this.stopped=i,this.result=e},Dn=Ji.prototype,ba=function(i,e,t){var r=t&&t.that,s=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=kp(e,r),u,c,h,f,p,m,b,y=function(g){return u&&In(u,"normal",g),new Ji(!0,g)},T=function(g){return s?(wp(g),l?d(g[0],g[1],y):d(g[0],g[1])):l?d(g,y):d(g)};if(n)u=i.iterator;else if(o)u=i;else{if(c=Ip(i),!c)throw Dp(Ap(i)+" is not iterable");if(_p(c)){for(h=0,f=Rp(i);f>h;h++)if(p=T(i[h]),p&&Cn(Dn,p))return p;return new Ji(!1)}u=Cp(i,c)}for(m=n?i.next:u.next;!(b=Pp(m,u)).done;){try{p=T(b.value)}catch(g){In(u,"throw",g)}if(typeof p=="object"&&p&&Cn(Dn,p))return p}return new Ji(!1)},Np=oa,xp=vt,Lp=mr,Op=function(i,e,t){var r=Np(e);r in i?xp.f(i,r,Lp(0,t)):i[r]=t},Bp=Ce,Mp=ba,Vp=Op;Bp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Mp(e,function(r,s){Vp(t,r,s)},{AS_ENTRIES:!0}),t}});var Fp=aa,Up=Fp.Object.fromEntries,jp={CSSRuleList:0,CSSStyleDeclaration:0,CSSValueList:0,ClientRectList:0,DOMRectList:0,DOMStringList:0,DOMTokenList:1,DataTransferItemList:0,FileList:0,HTMLAllCollection:0,HTMLCollection:0,HTMLFormElement:0,HTMLSelectElement:0,MediaList:0,MimeTypeArray:0,NamedNodeMap:0,NodeList:1,PaintRequestList:0,Plugin:0,PluginArray:0,SVGLengthList:0,SVGNumberList:0,SVGPathSegList:0,SVGPointList:0,SVGStringList:0,SVGTransformList:0,SourceBufferList:0,StyleSheetList:0,TextTrackCueList:0,TextTrackList:0,TouchList:0},Hp=jp,Gp=le,Yp=pi,qp=hi,Nn=Ft,zp=ce,xn=zp("toStringTag");for(var Zr in Hp){var Ln=Gp[Zr],es=Ln&&Ln.prototype;es&&Yp(es)!==xn&&qp(es,xn,Zr),Nn[Zr]=Nn.Array}var Wp=Up,Qp=Wp,Kp=Qp,Jp=Kp,mi=lr(Jp),Xp=ui,br=typeof process!="undefined"&&Xp(process)=="process",Zp=vt,em=function(i,e,t){return Zp.f(i,e,t)},tm=bt,im=em,rm=ce,sm=st,On=rm("species"),am=function(i){var e=tm(i);sm&&e&&!e[On]&&im(e,On,{configurable:!0,get:function(){return this}})},nm=dr,om=TypeError,lm=function(i,e){if(nm(e,i))return i;throw om("Incorrect invocation")},um=Pe,dm=ae,Us=na,cm=um(Function.toString);dm(Us.inspectSource)||(Us.inspectSource=function(i){return cm(i)});var Pl=Us.inspectSource,hm=Pe,fm=ke,wl=ae,pm=pi,mm=bt,vm=Pl,Al=function(){},bm=[],_l=mm("Reflect","construct"),Sa=/^\s*(?:class|function)\b/,Sm=hm(Sa.exec),gm=!Sa.exec(Al),Jt=function(e){if(!wl(e))return!1;try{return _l(Al,bm,e),!0}catch(t){return!1}},Rl=function(e){if(!wl(e))return!1;switch(pm(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return gm||!!Sm(Sa,vm(e))}catch(t){return!0}};Rl.sham=!0;var ym=!_l||fm(function(){var i;return Jt(Jt.call)||!Jt(Object)||!Jt(function(){i=!0})||i})?Rl:Jt,Tm=ym,Em=hr,$m=TypeError,km=function(i){if(Tm(i))return i;throw $m(Em(i)+" is not a constructor")},Bn=We,Pm=km,wm=di,Am=ce,_m=Am("species"),Cl=function(i,e){var t=Bn(i).constructor,r;return t===void 0||wm(r=Bn(t)[_m])?e:Pm(r)},Rm=Pe,Cm=Rm([].slice),Im=TypeError,Dm=function(i,e){if(i<e)throw Im("Not enough arguments");return i},Nm=cr,Il=/(?:ipad|iphone|ipod).*applewebkit/i.test(Nm),Se=le,xm=rl,Lm=vr,Mn=ae,Om=Ve,Dl=ke,Vn=hl,Bm=Cm,Fn=sa,Mm=Dm,Vm=Il,Fm=br,js=Se.setImmediate,Hs=Se.clearImmediate,Um=Se.process,ts=Se.Dispatch,jm=Se.Function,Un=Se.MessageChannel,Hm=Se.String,is=0,ii={},jn="onreadystatechange",ni,ht,rs,ss;Dl(function(){ni=Se.location});var ga=function(i){if(Om(ii,i)){var e=ii[i];delete ii[i],e()}},as=function(i){return function(){ga(i)}},Hn=function(i){ga(i.data)},Gn=function(i){Se.postMessage(Hm(i),ni.protocol+"//"+ni.host)};(!js||!Hs)&&(js=function(e){Mm(arguments.length,1);var t=Mn(e)?e:jm(e),r=Bm(arguments,1);return ii[++is]=function(){xm(t,void 0,r)},ht(is),is},Hs=function(e){delete ii[e]},Fm?ht=function(i){Um.nextTick(as(i))}:ts&&ts.now?ht=function(i){ts.now(as(i))}:Un&&!Vm?(rs=new Un,ss=rs.port2,rs.port1.onmessage=Hn,ht=Lm(ss.postMessage,ss)):Se.addEventListener&&Mn(Se.postMessage)&&!Se.importScripts&&ni&&ni.protocol!=="file:"&&!Dl(Gn)?(ht=Gn,Se.addEventListener("message",Hn,!1)):jn in Fn("script")?ht=function(i){Vn.appendChild(Fn("script"))[jn]=function(){Vn.removeChild(this),ga(i)}}:ht=function(i){setTimeout(as(i),0)});var Nl={set:js,clear:Hs},xl=function(){this.head=null,this.tail=null};xl.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 Ll=xl,Gm=cr,Ym=/ipad|iphone|ipod/i.test(Gm)&&typeof Pebble!="undefined",qm=cr,zm=/web0s(?!.*chrome)/i.test(qm),mt=le,Yn=vr,Wm=da.f,ns=Nl.set,Qm=Ll,Km=Il,Jm=Ym,Xm=zm,os=br,qn=mt.MutationObserver||mt.WebKitMutationObserver,zn=mt.document,Wn=mt.process,xi=mt.Promise,Qn=Wm(mt,"queueMicrotask"),Gs=Qn&&Qn.value,_t,ls,us,Li,Kn;if(!Gs){var Oi=new Qm,Bi=function(){var i,e;for(os&&(i=Wn.domain)&&i.exit();e=Oi.get();)try{e()}catch(t){throw Oi.head&&_t(),t}i&&i.enter()};!Km&&!os&&!Xm&&qn&&zn?(ls=!0,us=zn.createTextNode(""),new qn(Bi).observe(us,{characterData:!0}),_t=function(){us.data=ls=!ls}):!Jm&&xi&&xi.resolve?(Li=xi.resolve(void 0),Li.constructor=xi,Kn=Yn(Li.then,Li),_t=function(){Kn(Bi)}):os?_t=function(){Wn.nextTick(Bi)}:(ns=Yn(ns,mt),_t=function(){ns(Bi)}),Gs=function(i){Oi.head||_t(),Oi.add(i)}}var Zm=Gs,ev=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},ya=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},tv=le,Ut=tv.Promise,Ol=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",iv=Ol,rv=br,sv=!iv&&!rv&&typeof window=="object"&&typeof document=="object",av=le,ri=Ut,nv=ae,ov=ll,lv=Pl,uv=ce,dv=sv,cv=Ol,ds=zo,Jn=ri&&ri.prototype,hv=uv("species"),Ys=!1,Bl=nv(av.PromiseRejectionEvent),fv=ov("Promise",function(){var i=lv(ri),e=i!==String(ri);if(!e&&ds===66||!(Jn.catch&&Jn.finally))return!0;if(!ds||ds<51||!/native code/.test(i)){var t=new ri(function(n){n(1)}),r=function(n){n(function(){},function(){})},s=t.constructor={};if(s[hv]=r,Ys=t.then(function(){})instanceof r,!Ys)return!0}return!e&&(dv||cv)&&!Bl}),vi={CONSTRUCTOR:fv,REJECTION_EVENT:Bl,SUBCLASSING:Ys},jt={},Xn=St,pv=TypeError,mv=function(i){var e,t;this.promise=new i(function(r,s){if(e!==void 0||t!==void 0)throw pv("Bad Promise constructor");e=r,t=s}),this.resolve=Xn(e),this.reject=Xn(t)};jt.f=function(i){return new mv(i)};var vv=Ce,ir=br,rt=le,bi=ge,bv=pa,Sv=va,gv=am,yv=St,qs=ae,Tv=ze,Ev=lm,$v=Cl,Ml=Nl.set,Ta=Zm,kv=ev,Pv=ya,wv=Ll,Vl=tl,zs=Ut,Ea=vi,Fl=jt,Sr="Promise",Ul=Ea.CONSTRUCTOR,Av=Ea.REJECTION_EVENT;Ea.SUBCLASSING;var cs=Vl.getterFor(Sr),_v=Vl.set,Rv=zs&&zs.prototype,Dt=zs,hs=Rv,jl=rt.TypeError,Ws=rt.document,$a=rt.process,Qs=Fl.f,Cv=Qs,Iv=!!(Ws&&Ws.createEvent&&rt.dispatchEvent),Hl="unhandledrejection",Dv="rejectionhandled",Zn=0,Gl=1,Nv=2,ka=1,Yl=2,Mi,eo,xv,ql=function(i){var e;return Tv(i)&&qs(e=i.then)?e:!1},zl=function(i,e){var t=e.value,r=e.state==Gl,s=r?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{s?(r||(e.rejection===Yl&&Ov(e),e.rejection=ka),s===!0?d=t:(l&&l.enter(),d=s(t),l&&(l.exit(),c=!0)),d===i.promise?o(jl("Promise-chain cycle")):(u=ql(d))?bi(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Wl=function(i,e){i.notified||(i.notified=!0,Ta(function(){for(var t=i.reactions,r;r=t.get();)zl(r,i);i.notified=!1,e&&!i.rejection&&Lv(i)}))},Ql=function(i,e,t){var r,s;Iv?(r=Ws.createEvent("Event"),r.promise=e,r.reason=t,r.initEvent(i,!1,!0),rt.dispatchEvent(r)):r={promise:e,reason:t},!Av&&(s=rt["on"+i])?s(r):i===Hl&&kv("Unhandled promise rejection",t)},Lv=function(i){bi(Ml,rt,function(){var e=i.facade,t=i.value,r=to(i),s;if(r&&(s=Pv(function(){ir?$a.emit("unhandledRejection",t,e):Ql(Hl,e,t)}),i.rejection=ir||to(i)?Yl:ka,s.error))throw s.value})},to=function(i){return i.rejection!==ka&&!i.parent},Ov=function(i){bi(Ml,rt,function(){var e=i.facade;ir?$a.emit("rejectionHandled",e):Ql(Dv,e,i.value)})},Nt=function(i,e,t){return function(r){i(e,r,t)}},Lt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Nv,Wl(i,!0))},Ks=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw jl("Promise can't be resolved itself");var r=ql(e);r?Ta(function(){var s={done:!1};try{bi(r,e,Nt(Ks,s,i),Nt(Lt,s,i))}catch(n){Lt(s,n,i)}}):(i.value=e,i.state=Gl,Wl(i,!1))}catch(s){Lt({done:!1},s,i)}}};Ul&&(Dt=function(e){Ev(this,hs),yv(e),bi(Mi,this);var t=cs(this);try{e(Nt(Ks,t),Nt(Lt,t))}catch(r){Lt(t,r)}},hs=Dt.prototype,Mi=function(e){_v(this,{type:Sr,done:!1,notified:!1,parent:!1,reactions:new wv,rejection:!1,state:Zn,value:void 0})},Mi.prototype=bv(hs,"then",function(e,t){var r=cs(this),s=Qs($v(this,Dt));return r.parent=!0,s.ok=qs(e)?e:!0,s.fail=qs(t)&&t,s.domain=ir?$a.domain:void 0,r.state==Zn?r.reactions.add(s):Ta(function(){zl(s,r)}),s.promise}),eo=function(){var i=new Mi,e=cs(i);this.promise=i,this.resolve=Nt(Ks,e),this.reject=Nt(Lt,e)},Fl.f=Qs=function(i){return i===Dt||i===xv?new eo(i):Cv(i)});vv({global:!0,constructor:!0,wrap:!0,forced:Ul},{Promise:Dt});Sv(Dt,Sr,!1,!0);gv(Sr);var Bv=ce,Kl=Bv("iterator"),Jl=!1;try{var Mv=0,io={next:function(){return{done:!!Mv++}},return:function(){Jl=!0}};io[Kl]=function(){return this},Array.from(io,function(){throw 2})}catch(i){}var Vv=function(i,e){if(!e&&!Jl)return!1;var t=!1;try{var r={};r[Kl]=function(){return{next:function(){return{done:t=!0}}}},i(r)}catch(s){}return t},Fv=Ut,Uv=Vv,jv=vi.CONSTRUCTOR,Xl=jv||!Uv(function(i){Fv.all(i).then(void 0,function(){})}),Hv=Ce,Gv=ge,Yv=St,qv=jt,zv=ya,Wv=ba,Qv=Xl;Hv({target:"Promise",stat:!0,forced:Qv},{all:function(e){var t=this,r=qv.f(t),s=r.resolve,n=r.reject,o=zv(function(){var l=Yv(t.resolve),d=[],u=0,c=1;Wv(e,function(h){var f=u++,p=!1;c++,Gv(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 Kv=Ce,Jv=vi.CONSTRUCTOR,ro=Ut;ro&&ro.prototype;Kv({target:"Promise",proto:!0,forced:Jv,real:!0},{catch:function(i){return this.then(void 0,i)}});var Xv=Ce,Zv=ge,eb=St,tb=jt,ib=ya,rb=ba,sb=Xl;Xv({target:"Promise",stat:!0,forced:sb},{race:function(e){var t=this,r=tb.f(t),s=r.reject,n=ib(function(){var o=eb(t.resolve);rb(e,function(l){Zv(o,t,l).then(r.resolve,s)})});return n.error&&s(n.value),r.promise}});var ab=Ce,nb=ge,ob=jt,lb=vi.CONSTRUCTOR;ab({target:"Promise",stat:!0,forced:lb},{reject:function(e){var t=ob.f(this);return nb(t.reject,void 0,e),t.promise}});var ub=We,db=ze,cb=jt,Zl=function(i,e){if(ub(i),db(e)&&e.constructor===i)return e;var t=cb.f(i),r=t.resolve;return r(e),t.promise},hb=Ce,fb=bt,pb=Gd,mb=Ut,vb=vi.CONSTRUCTOR,bb=Zl,Sb=fb("Promise"),gb=!vb;hb({target:"Promise",stat:!0,forced:pb},{resolve:function(e){return bb(gb&&this===Sb?mb:this,e)}});var yb=Ce,Js=Ut,Tb=ke,Eb=bt,$b=ae,kb=Cl,so=Zl,Pb=Js&&Js.prototype,wb=!!Js&&Tb(function(){Pb.finally.call({then:function(){}},function(){})});yb({target:"Promise",proto:!0,real:!0,forced:wb},{finally:function(i){var e=kb(this,Eb("Promise")),t=$b(i);return this.then(t?function(r){return so(e,i()).then(function(){return r})}:i,t?function(r){return so(e,i()).then(function(){throw r})}:i)}});var Ab=bt,Pa=Ab,_b=Pa,Rb=_b("Promise","finally"),Cb=Rb,Ib=Cb,Db=Ib,Nb=Db,gr=lr(Nb),ne;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ne||(ne={}));var Me=(i,e=0,t=ne.OFFSET_P)=>{switch(t){case ne.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ne.PLAYBACK_SHIFT:{if(e===0)return i;const r=new URL(i);return r.searchParams.append("playback_shift",e.toFixed(0)),r.toString()}case ne.DASH_CMAF_OFFSET_P:{const r=new URL(i);return r.searchParams.set("offset_p",e.toFixed(0)),r.toString()}default:a.assertNever(t)}return i};const ao=(i,e)=>{var t;switch(e){case ne.OFFSET_P:return NaN;case ne.PLAYBACK_SHIFT:{const r=new URL(i);return Number(r.searchParams.get("playback_shift"))}case ne.DASH_CMAF_OFFSET_P:{const r=new URL(i);return Number((t=r.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var k=(i,e,t=!1)=>{const r=i.getTransition();(t||!r||r.to===e)&&i.setState(e)};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 xb=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var N;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(N||(N={}));const Lb=5,Ob=5,Bb=500,no=7e3;class Mb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(N.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!==N.STOPPED&&(this.videoState.startTransitionTo(N.STOPPED),this.stop());return}if(!s){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&r!==N.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(r){case N.PLAYING:case N.PAUSED:case N.READY:break;case N.STOPPED:this.videoState.startTransitionTo(N.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PLAYING:{switch(r){case N.PLAYING:break;case N.PAUSED:this.videoState.startTransitionTo(N.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case N.READY:this.videoState.startTransitionTo(N.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case N.STOPPED:this.videoState.startTransitionTo(N.READY),this.prepare();break;default:a.assertNever(r)}break}case exports.PlaybackState.PAUSED:{switch(r){case N.PLAYING:this.videoState.startTransitionTo(N.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case N.PAUSED:break;case N.READY:this.videoState.startTransitionTo(N.PAUSED),this.videoState.setState(N.PAUSED);break;case N.STOPPED:this.videoState.startTransitionTo(N.READY),this.prepare();break;default:a.assertNever(r)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(xb(e.format)),this.params.output.isAudioAvailable$.next(!0),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const t=this.params.connection.session.getMediaSession();t&&this.restoreSession(t),this.subscribe()}destroy(){this.log({message:"[destroy]"}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new a.Subscription;this.subscription.add(e),this.subscription.add(a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>`stateChangeStarted$ ${JSON.stringify(s)}`)),this.videoState.stateChangeEnded$.pipe(a.map(s=>`stateChangeEnded$ ${JSON.stringify(s)}`))).subscribe(s=>this.log({message:`[videoState] ${s}`})));const t=(s,n)=>this.subscription.add(s.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const s=new a.Subject;e.add(s.pipe(a.debounce(Bb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===B.Applying||Math.abs(l-n)>Lb)&&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<Ob&&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(N.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(N.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const r=this.params.output.isLive$.getValue();this.params.output.duration$.next(r?0:t.duration),this.params.output.position$.next(r?0:t.currentTime),this.params.desiredState.seekState.setState({state:B.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),r=this.createLoadRequest(t);this.loadMedia(r)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===N.PAUSED||e===N.PLAYING)&&(this.videoState.setState(N.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)===N.PLAYING||e===N.PAUSED)&&(this.videoState.setState(N.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===N.READY&&this.videoState.setState(N.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()!==N.STOPPED&&this.videoState.setState(N.STOPPED)}handleRemoteVolumeChange(e){var t,r;const s=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:s.volume,muted:(r=e.muted)!==null&&r!==void 0?r:s.muted};(n.volume!==s.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:r}=this.params.connection;t.currentTime=e,r.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const r=this.params.source;let s,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=r[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),s=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=r[e];a.assertNonNullable(c),s=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=r[e];a.assertNonNullable(c),s=Me(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:s,n);l.contentUrl=s,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const r=this.params.desiredState.seekState.getState();return r.state===B.Applying||r.state===B.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:r.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),r=new Promise((s,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(no).subscribe(()=>n(`timeout(${no})`)))});gr(Promise.race([t,r]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},s=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${s}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:s})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Vb=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)},Fb=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,b;const y=mi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in y||"x-playback-duration-millis"in y){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),S=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=S!=null?S:v*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const T=(m=y["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,g=(b={1:!0,0:!1}[y["x-reused"]])!==null&&b!==void 0?b:void 0;r.next(T),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(...b){return d(this),p(...b)},f.progress=function(...b){return u(this),m(...b)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:s,connectionType$:r}},Bt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Ub=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Bt}),!0),jb=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 Re=(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},gt=(i,e,t)=>Re(e,()=>i.loop,r=>{a.isNonNullable(r)&&(i.loop=r)},{onError:t}),Qe=(i,e,t,r)=>Re(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}),at=(i,e,t,r)=>Re(e,()=>i.playbackRate,s=>{a.isNonNullable(s)&&(i.playbackRate=s)},{changed$:t,onError:r}),Hb=i=>["__",i.language,i.label].join("|"),Gb=(i,e)=>{if(i.id===e)return!0;const[t,r,s]=e.split("|");return i.language===r&&i.label===s};class Fe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,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(Re(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{a.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="internal"))),onError:s})),this.subscription.add(Re(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(Re(t.currentTextTrack,()=>{if(this.video)return;const n=this.htmlTextTracksAsArray().find(({mode:o})=>o==="showing");return n&&this.htmlTextTrackToITextTrack(n).id},n=>this.select(n),{changed$:this.current$,onError:s})),this.subscription.add(Re(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const r=this.current$.getValue();r&&this.select(r)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(r=>this.htmlTextTrackToITextTrack(r))),a.filterChanged((r,s)=>r.length===s.length&&r.every(({id:n},o)=>n===s[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:r})=>r==="showing")),a.map(r=>r&&this.htmlTextTrackToITextTrack(r).id),a.filterChanged()).subscribe(this.current$));const t=r=>{var s,n;return this.applyCueSettings((n=(s=r.target)===null||s===void 0?void 0:s.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(r=>{var s,n;(s=r.track)===null||s===void 0||s.addEventListener("cuechange",t);const o=l=>{var 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(Fe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:r}=e,s=e.id?e.id:Hb(e),n=this.externalTracks.has(s),o=s.includes("auto");return n?{id:s,type:"external",isAuto:o,language:t,label:r,url:this.externalTracks.get(s).url}:{id:s,type:"internal",isAuto:o,language:t,label:r,url:this.internalTracks.get(s).url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(r=>r.id===t)).forEach(([,t])=>this.detach(t)))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))a.isNonNullable(e)&&Gb(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),r=>r.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const wa=i=>{i.removeAttribute("src"),i.load()},Yb=i=>{try{i.pause(),i.playbackRate=0,wa(i),i.remove()}catch(e){console.error(e)}};class qb{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const Xs=window.WeakMap?new WeakMap:new qb,Ke=i=>{let e=i.querySelector("video");const t=!!e;return e?wa(e):(e=document.createElement("video"),i.appendChild(e)),Xs.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Je=i=>{const e=Xs.get(i);Xs.delete(i),e?wa(i):Yb(i)};class yr{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const eu=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},oo=i=>{const e=eu(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},zb=i=>{const e=eu(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},Zs=3;class Wb{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<Zs&&(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||Zs))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 tu=(i,e,t=Zs)=>{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 Xe=i=>{const e=v=>a.fromEvent(i,v).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],r=a.merge(...t.map(v=>a.fromEvent(i,v))).pipe(a.map(v=>v.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),s=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>tu(i.buffered,i.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>!!(i.error||i.played.length)),a.map(()=>{var v;const S=i.error;return{id:S?`MediaError#${S.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:S?S.message:"Error event from HTML video element",thrown:(v=i.error)!==null&&v!==void 0?v:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(v=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(v)&&p>=i.duration-f&&v<=f&&h.next(p),p=v});const m=a.fromEvent(i,"enterpictureinpicture"),b=a.fromEvent(i,"leavepictureinpicture"),y=new a.ValueSubject(zb(i));m.subscribe(()=>y.next(!0)),b.subscribe(()=>y.next(!1));const T=new a.ValueSubject(oo(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>oo(i))).subscribe(T),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:r,currentBuffer$:s,volumeState$:l,playbackRateState$:d,inPiP$:y,inFullscreen$:T}},Aa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Qb=Ce,Kb=pr,Jb=fa,Xb=ha;Qb({target:"Array",proto:!0},{at:function(e){var t=Kb(this),r=Jb(t),s=Xb(e),n=s>=0?s:r+s;return n<0||n>=r?void 0:t[n]}});var Zb=Pa,eS=Zb("Array","at"),tS=eS,iS=tS,rS=iS,sS=rS,xe=lr(sS);let _a=!1,Ge={};const aS=i=>{_a=i},nS=()=>{Ge={}},oS=i=>{i(Ge)},Vi=(i,e)=>{var t;_a&&(Ge.meta=(t=Ge.meta)!==null&&t!==void 0?t:{},Ge.meta[i]=e)};class Le{constructor(e){this.name=e}next(e){var t,r;if(!_a)return;Ge.series=(t=Ge.series)!==null&&t!==void 0?t:{};const s=(r=Ge.series[this.name])!==null&&r!==void 0?r:[];s.push([Date.now(),e]),Ge.series[this.name]=s}}const lS=new Le("best_bitrate"),uS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class dS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Ht=(i,{container:e,throughput:t,tuning:r,limits:s,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c})=>{var h,f,p,m;const b=r.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=r.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*r.containerSizeFactor,height:e.height*b*r.containerSizeFactor},T=y&&a.videoSizeToQuality(y),g=r.considerPlaybackRate&&a.isNonNullable(l)?l:1,v=i.filter(w=>!a.isInvariantQuality(w.quality)).sort((w,V)=>a.isHigher(w.quality,V.quality)?-1:1),S=(f=xe(v,-1))===null||f===void 0?void 0:f.quality,E=(p=xe(v,0))===null||p===void 0?void 0:p.quality,P=a.isNullable(s)||a.isNonNullable(s.min)&&a.isNonNullable(s.max)&&a.isLower(s.max,s.min)||a.isNonNullable(s.min)&&E&&a.isHigher(s.min,E)||a.isNonNullable(s.max)&&S&&a.isLower(s.max,S),x=g*uS(o!=null?o:.5,r.bitrateFactorAtEmptyBuffer,r.bitrateFactorAtFullBuffer),R=v.filter(w=>{const V=T?a.isLower(w.quality,T):!0,q=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(w.bitrate)?t-n>=w.bitrate*x:!0,X=r.lazyQualitySwitch&&a.isNonNullable(r.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<r.minBufferToSwitchUp&&a.isHigher(w.quality,d.quality),_=!!c&&a.isHigherOrEqual(w.quality,c),C=P||(a.isNullable(s.max)||a.isLowerOrEqual(w.quality,s.max))&&(a.isNullable(s.min)||a.isHigherOrEqual(w.quality,s.min));return V&&q&&!X&&C&&!_})[0];R&&R.bitrate&&lS.next(R.bitrate);const D=(m=R!=null?R:v[Math.ceil((v.length-1)/2)])!==null&&m!==void 0?m:i[0],L=D&&u&&u.history[D.id]&&a.now()-u.history[D.id]<=r.trackCooldown&&(!u.last||D.id!==u.last.id);if(D!=null&&D.id&&u&&!L&&u.recordSelection(D),L&&(u!=null&&u.last)){const w=u.last;return u==null||u.recordSwitch(w),w}return u==null||u.recordSwitch(D),D};var fe=i=>new URL(i).hostname;const cS=300,rr=(i,e=cS)=>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(Gu(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()});class Tr{constructor(){this.onDroopedVideoFramesLimit$=new a.Subject,this.subscription=new a.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new a.Subject,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!a.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality(),s=t-this.prevTotalVideoFrames,n=r-this.prevDroppedVideoFrames,o=1-(s-n)/s;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,r)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const s=!!this.isForceCheckCounter;return s&&(this.isForceCheckCounter-=1),!s})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),r=a.merge(e,t);this.subscription.add(r.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:r}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,r),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,r;const s=(r=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>a.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||r===void 0?void 0:r[0];return e!=null?e:s}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&!!this.video.getVideoPlaybackQuality}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Xt={};var M;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(M||(M={}));const re=(i,e)=>new a.Observable(t=>{const r=s=>t.next(s);return i.on(e,r),()=>i.off(e,r)});class lo{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(M.DOWNLOADING_LIB),this.textTracksManager=new Fe,this.droppedFramesManager=new Tr,this.videoTracks$=new a.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new yr,this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===M.DOWNLOADING_LIB||t===M.STREAM_INITIALIZED))switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&t!==M.STOPPED&&r!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),r){case exports.PlaybackState.STOPPED:{switch(t){case M.STOPPED:break;case M.PLAYING:case M.PAUSED:case M.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case M.STOPPED:this.prepare();break;case M.PLAYING:case M.PAUSED:case M.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case M.PLAYING:break;case M.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case M.READY:this.play();break;case M.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case M.PLAYING:this.pause(),this.liveOffset.pause();break;case M.PAUSED:break;case M.READY:this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(r)}},this.video=Ke(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=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"),this.params.tuning.dynamicImportTimeout);gr(import("dashjs/dist/dash.mediaplayer.min.js").then(s=>{e||(Xt.MediaPlayer=s.MediaPlayer,Xt.Debug=s.Debug,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Xt.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Xt.Debug,"dashjs not loaded"),this.player=Xt.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?Aa(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&jb(this.player),Vb(this.player),this.params.tuning.requestQuick&&Ub(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,r=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},s=(v,S)=>this.subscription.add(v.subscribe(S,r));s(rr(this.video),this.elementSize$),s(re(this.player,"error").pipe(a.map(v=>{const S=typeof v.error=="object"?v.error.code:v.error,E=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${S}`,message:E}})),e.error$),s(re(this.player,"playbackError").pipe(a.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=re(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({newQuality:v})=>{var S;return(S=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===v))===null||S===void 0?void 0:S.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:v})=>v===M.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Re(t.videoTrack,()=>{var v,S;const E=this.player.getQualityFor("video");return(S=(v=this.videoTracks$.getValue().find(({bitrateInfo:P})=>P.qualityIndex===E))===null||v===void 0?void 0:v.track)===null||S===void 0?void 0:S.id},v=>{var S;if(a.isNullable(v))return;const E=(S=this.videoTracks$.getValue().find(({track:P})=>P.id===v))===null||S===void 0?void 0:S.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:r}))},r)),this.subscription.add(Re(t.autoVideoTrackSwitching,()=>{var v,S,E;return(E=(S=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||S===void 0?void 0:S.autoSwitchBitrate)===null||E===void 0?void 0:E.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:r})),s(re(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),s(re(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:S}})=>{var E,P;const x=this.player.getDashMetrics(),Y=x.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),R=(E=x.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,D=(P={1:!0,0:!1}[Y])!==null&&P!==void 0?P:void 0;this.params.output.httpConnectionType$.next(R),this.params.output.httpConnectionReused$.next(D),e.hostname$.next(fe(S))}),s(re(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:S,availableFrom:E}}})=>{this.isLive$.next(S),this.availableFrom$.next(E.getTime()),S||e.duration$.next(v);const P=[],x=this.player.getQualityFor("video");let Y;for(const R of this.player.getBitrateInfoListFor("video")){const D=R.qualityIndex.toString(10),L=a.videoSizeToQuality(R),w=R.bitrate/1e3,V={width:R.width,height:R.height},q=this.frameRatesByFrameHeight[R.height];if(L){const X={id:D,quality:L,bitrate:w,size:V,fps:q};P.push({track:X,bitrateInfo:R}),R.qualityIndex===x&&(Y=X)}}this.videoTracks$.next(P),e.availableVideoTracks$.next(P.map(({track:R})=>R)),Y&&e.currentVideoTrack$.next(Y),this.videoState.setState(M.STREAM_INITIALIZED),this.videoState.startTransitionTo(M.READY)}),s(re(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const S=v.requestEndDate.getTime()-v.firstByteDate.getTime(),E=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,S)}),s(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),S=Ht(this.videoTracks$.getValue().map(({track:x})=>x),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}),E=t.autoVideoTrackLimits.getTransition();E&&e.autoVideoTrackLimits$.next(E.to);const P=this.videoTracks$.getValue().find(({track:x})=>x===S);P!=null&&P.bitrateInfo&&this.player.setQualityFor("video",P==null?void 0:P.bitrateInfo.qualityIndex,!1)}),s(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:v})=>v),a.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=re(this.player,"playbackTimeUpdated").pipe(a.map(({time:v})=>v!=null?v:0));s(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:S})=>this.params.output.liveTime$.next(v+S*1e3)),s(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),s(re(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),s(re(this.player,"playbackEnded"),e.endedEvent$),s(re(this.player,"playbackProgress").pipe(a.map(()=>tu(this.video.buffered,this.video.currentTime))),e.currentBuffer$),s(re(this.player,"playbackPlaying"),()=>{this.videoState.setState(M.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),s(re(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),s(re(this.player,"playbackPaused"),()=>{this.videoState.setState(M.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),s(re(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===M.READY&&this.videoState.setState(M.READY)}),s(this.isLive$,e.isLive$),s(rr(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}=Fb(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:S})=>{const E=!v&&S;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),s(o.pipe(a.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(re(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(re(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,r))},r)),s(re(this.player,"manifestLoaded"),v=>{var S,E,P,x,Y,R,D;if(!((E=(S=v.data)===null||S===void 0?void 0:S.Period)===null||E===void 0)&&E.AdaptationSet){const L=[];for(const w of(x=(P=v.data)===null||P===void 0?void 0:P.Period)===null||x===void 0?void 0:x.AdaptationSet)if(w.contentType==="text"){const V=(Y=w.Representation)===null||Y===void 0?void 0:Y.id,q=new URL((R=w.Representation)===null||R===void 0?void 0:R.BaseURL,(D=v.data)===null||D===void 0?void 0:D.baseUri).toString(),X="internal",_=w.lang;L.push({id:V,url:q,type:X,language:_})}t.internalTextTracks.startTransitionTo(L)}}),this.subscription.add(gt(this.video,t.isLooped,r));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:b,inFullscreen$:y,pause$:T,playing$:g}=Xe(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:g,pause$:T,tracks$:this.videoTracks$.pipe(a.map(v=>v.map(({track:S})=>S)))}),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(at(this.video,t.playbackRate,m,r)),this.subscription.add(b.subscribe(e.inPiP$)),this.subscription.add(y.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(M.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3);const s=Me(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ne.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(M.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(M.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}Je(this.video),this.params.output.element$.next(void 0)}}var Si=i=>{switch(i){case"mobile":return a.VideoQuality.Q_144P;case"lowest":return a.VideoQuality.Q_240P;case"low":return a.VideoQuality.Q_360P;case"sd":case"medium":return a.VideoQuality.Q_480P;case"hd":case"high":return a.VideoQuality.Q_720P;case"fullhd":case"full":return a.VideoQuality.Q_1080P;case"quadhd":case"quad":return a.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return a.VideoQuality.Q_2160P}};const uo=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var nt=i=>Q(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!uo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(r){return uo(r)&&(i.muted=!1,console.warn(r)),!1}}return!0});function de(){return a.now()}function iu(i){return de()-i}function co(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 hS(i,e,t){const r=(...s)=>{t.apply(null,s),i.removeEventListener(e,r)};i.addEventListener(e,r)}function Xi(i,e,t,r){const s=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,b=2e3,y=()=>{if(d)return;a.assertNonNullable(c);const w=iu(c);let V;if(w<b){V=b-w,setTimeout(y,V);return}b*=2,b>m&&(b=m),o&&o.abort(),o=new s,P()};const T=w=>(n=w,L),g=w=>(h=w,L),v=()=>(p="json",L),S=()=>{if(!d){if(--u>=0){y(),r&&r();return}d=!0,h&&h(),t&&t()}},E=w=>(f=w,L),P=()=>{c=de(),o=new s,o.open("get",i);let w=0,V,q=0;const X=()=>(a.assertNonNullable(c),Math.max(c,Math.max(V||0,q||0)));if(n&&o.addEventListener("progress",_=>{const C=de();n.updateChunk&&_.loaded>w&&(n.updateChunk(X(),_.loaded-w),w=_.loaded,V=C)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>S())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const _=o.status;if(_>=200&&_<300){if(o.response.byteLength&&n){const C=o.response.byteLength-w;C&&n.updateChunk&&n.updateChunk(X(),C)}h&&h(),o&&e(o.response)}else S()}),o.addEventListener("error",()=>{S()}),f){const _=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=de(),o.removeEventListener("readystatechange",_))};o.addEventListener("readystatechange",_)}return o.responseType=p,o.send(),L},L={withBitrateReporting:T,withParallel:E,withJSONResponse:v,withRetryCount:w=>(u=w,L),withRetryInterval:(w,V)=>(a.isNonNullable(w)&&(b=w),a.isNonNullable(V)&&(m=V),L),withTimeout:w=>(l=w,L),withFinally:g,send:P,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return L}const fS=100,pS=2e3,mS=500;let vS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,r){return{start:e,end:t,bytes:r}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-mS;if(t-e>pS){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>fS&&(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 bS{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=de(),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=de()-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=Xi(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=de()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=de();if(Object.keys(this.activeRequests).length>=e)return!1;const r=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),r>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),r),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,r,s){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=r,o._retryCB=s,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),r(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=r,n._retryCB=s,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Fi=1e4,Ui=3,SS=300,gS=2e3,yS=6e4,TS=10,ES=1,$S=500;class kS{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new vS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=co(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=co(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const r=e.buffered.length;return r!==0&&(t=e.buffered.end(r-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var r;!!e.error&&!this.destroyed&&(t(`Video element error: ${(r=e.error)===null||r===void 0?void 0:r.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const r=this._getBufferSizeSec();!this.paused&&r<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(r+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,r=t.buffered.length;let s;r!==0&&(s=t.buffered.start(r-1),t.currentTime<s&&(e("Fixup stall"),t.currentTime=s))}_selectQuality(e){const{videoElement:t}=this.params;let r,s,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!s||n.bitrate>s.bitrate)&&(s=n):(!r||r.bitrate>n.bitrate)&&(r=n));return s||r}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:r,videoElement:s,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,r("setting video src"),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,s.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{hS(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 bS(Ui,Fi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:r,playerCallback:s}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const S=n&&(!c||c===this.rep);return S||t("Not running!"),S},f=(S,E,P)=>{d&&d.abort(),d=Xi(this.urlResolver.resolve(S,!1),E,P,()=>this._retryCallback()).withTimeout(Fi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ui).withFinally(()=>{d=null}).send()},p=(S,E,P)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(S,!1),E,P,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=S=>{const E=r.playbackRate;r.playbackRate!==S&&(t(`Playback rate switch: ${E}=>${S}`),r.playbackRate=S)},b=S=>{this.lowLatency=S,t(`lowLatency changed to ${S}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let S=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const P=de()-1e4;let x=0;for(let R=0;R<this.bufferStates.length;R++){const D=this.bufferStates[R];S=Math.min(S,D.buf),D.ts<P&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${S} drop=${x} jitter=${this.sourceJitter}`);let Y=S-ES;this.sourceJitter>=0?Y-=this.sourceJitter/2:this.sourceJitter-=1,Y>3?m(1.15):Y>1?m(1.1):Y>.3?m(1.05):m(1)}},T=S=>{let E;const P=()=>E&&E.start?E.start.length:0,x=_=>E.start[_]/1e3,Y=_=>E.dur[_]/1e3,R=_=>E.fragIndex+_,D=(_,C)=>({chunkIdx:R(_),startTS:x(_),dur:Y(_),discontinuity:C}),L=()=>{let _=0;if(E&&E.dur){let C=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,H=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=C;this.sourceJitter>1&&(te+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(te-=E.dur[se],!(te<=0));--se);_=Math.min(se,E.dur.length-1-H),_=Math.max(_,0)}return D(_,!0)},w=_=>{const C=P();if(!(C<=0)){if(a.isNonNullable(_)){for(let H=0;H<C;H++)if(x(H)>_)return D(H)}return L()}},V=_=>{const C=P(),H=_?_.chunkIdx+1:0,te=H-E.fragIndex;if(!(C<=0)){if(!_||te<0||te-C>TS)return t(`Resync: offset=${te} bChunks=${C} chunk=`+JSON.stringify(_)),L();if(!(te>=C))return D(H-E.fragIndex,!1)}},q=(_,C,H)=>{u&&u.abort(),u=Xi(this.urlResolver.resolve(_,!0,this.lowLatency),C,H,()=>this._retryCallback()).withTimeout(Fi).withRetryCount(Ui).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(_,C)=>{q(S,H=>{if(!h())return;E=H;const te=!!E.lowLatency;te!==this.lowLatency&&b(te);let se=0;for(let pe=0;pe<E.dur.length;++pe)se+=E.dur[pe];se>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),s({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,_(w(C))},()=>this._handleNetworkError())},nextChunk:V}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:S=>{const{videoElement:E,logger:P}=this.params;let x=T(e.jidxUrl),Y,R,D,L,w=0,V,q,X;const _=()=>{V&&(clearTimeout(V),V=void 0);const U=Math.max($S,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=w+U,ye=de(),me=Math.min(1e4,he-ye);w=ye;const Te=()=>{u||h()&&x.seek(()=>{h()&&(w=de(),C(),_())})};me>0?V=window.setTimeout(()=>{this.paused?_():Te()},me):Te()},C=()=>{let U;for(;U=x.nextChunk(L);)L=U,Ie(U);const he=x.nextChunk(D);if(he){if(D&&he.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?_():(g(),this._initPlayerWith(e));return}pe(he)}else _()},H=(U,he)=>{if(!h()||!this.sourceBuffer)return;let ye,me,Te;const yt=ot=>{window.setTimeout(()=>{h()&&H(U,he)},ot)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),yt(100);else{const ot=de(),Tt=E.currentTime;!this.paused&&E.buffered.length>1&&q===Tt&&ot-X>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),q!==Tt&&(q=Tt,X=ot);const Et=this._getBufferSizeSec();if(Et>30)P(`Buffered ${Et} seconds; delaying appendBuffer`),yt(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:ot,buf:Et}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch(yi){if(yi.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(ye=this.sourceBuffer.buffered.start(0),me=Tt,me-ye>4&&this.sourceBuffer.remove(ye,me-3)),yt(1e3);else throw yi}}},te=()=>{R&&Y&&(P([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(D)]),H(R,function(){R=null,C()}))},se=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),pe=U=>{h()&&p(se(U),(he,ye)=>{if(h()){if(ye/=1e3,R=he,D=U,o=U.startTS,ye){const me=Math.min(10,U.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*me:me}te()}},()=>this._handleNetworkError())},Ie=U=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(U),!1)))},Ze=U=>{h()&&(e.cachedHeader=U,H(U,()=>{Y=!0,te()}))};n=!0,x.seek(U=>{if(h()){if(w=de(),!U){_();return}L=U,!a.isNullable(S)||U.startTS>S?pe(U):(D=U,C())}},S),e.cachedHeader?Ze(e.cachedHeader):f(e.headerUrl,Ze,()=>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=de();if(this.chunkRateEstimator.addInterval(f,m,p)){const y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:y}),!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&&iu(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=de();h<l&&(o=f),l=h}}}_fetchManifest(e,t,r){this.manifestRequest=Xi(this.urlResolver.resolve(e,!0),t,r,()=>this._retryCallback()).withJSONResponse().withTimeout(Fi).withRetryCount(Ui).withRetryInterval(SS,gS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;nt(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))},yS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var O;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(O||(O={}));const PS=[O.PAUSED,O.PLAYING,O.READY],wS=[O.PAUSED,O.PLAYING,O.READY];class AS{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(O.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Fe,this.droppedFramesManager=new Tr,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new yr,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=Si(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,b=Object.assign({},h.video);if(!p)continue;const y={id:f,quality:p,bitrate:m,size:b};c.push({track:y,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)===O.MANIFEST_READY&&this.videoState.setState(O.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=()=>{const s=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){s!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(O.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(wS.includes(s)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===B.Requested&&PS.includes(s)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(s){case O.STOPPED:this.videoState.startTransitionTo(O.MANIFEST_READY),this.dash.attachSource(Me(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(O.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(O.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(s)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=s=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:s})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(s=>({transition:s,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(s=>({transition:s,type:"end"})))).subscribe(({transition:s,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(s)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const r=Xe(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.representations$.pipe(a.map(s=>s.map(({track:n})=>n)))}),this.subscription.add(r.canplay$.subscribe(()=>{var s;((s=this.videoState.getTransition())===null||s===void 0?void 0:s.to)===O.READY&&this.videoState.setState(O.READY)},t)).add(r.pause$.subscribe(()=>{this.videoState.setState(O.PAUSED)},t)).add(r.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(O.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(gt(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(at(this.video,this.params.desiredState.playbackRate,r.playbackRateState$,t)).add(r.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(r.playing$.subscribe(this.params.output.firstFrameEvent$)).add(r.canplay$.subscribe(this.params.output.canplay$)).add(r.inPiP$.subscribe(this.params.output.inPiP$)).add(r.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:s}})=>{const n=s&&a.videoQualityToHeight(s);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:s})})).add(this.videoState.stateChangeEnded$.subscribe(s=>{var n;switch(s.to){case O.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case O.MANIFEST_READY:case O.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 O.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case O.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(s.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Je(this.video)}createLiveDashPlayer(){const e=new kS({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=Ht(l.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}))===null||n===void 0?void 0:n.id,h=this.params.desiredState.videoTrack.getTransition(),f=this.params.desiredState.videoTrack.getState(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((h&&c||c!==f)&&this.setVideoTrack(c),p&&this.setAutoQuality(u),h||p||c!==f){const m=(o=l.find(({track:b})=>b.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const r=(t=this.representations$.getValue().find(({track:s})=>s.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(r,`No such representation ${e}`),this.dash.switchByName(r.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===O.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Me(this.params.source.url,o)),s&&this.dash.pause(),this.liveOffset.resetTo(o,s)}}var ru=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}},tt=(i,e)=>{let t=0;for(let r=0;r<i.length;r++){const s=i.start(r)*1e3,n=i.end(r)*1e3;s<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const _S=i=>{const e=document.createElement("a");return e.href=i,e.origin},RS=i=>{const e=document.createElement("a");return e.href=i,e.host};class su{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(this._xhr){if(((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=mi(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(RS(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 sr{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=b=>{s(sr._str2ua(b.substr(d))),d=b.length};let m=e.baseURL+"&bytes="+t+"-"+r;this._params.requestQuic&&(m=Bt(m)),this._lastXhr=new su(m,e.failoverHosts,b=>{this._lastXhr=void 0,p(b);const y=Date.now()-u;this._params.onBandwidthChange({size:b.length,duration:y,speed:8*b.length/(y/1e3)}),this._onDashCallback("loading",{size:b.length,done:!0}),n==null||n()},b=>{if(b.length-d>l&&p(b),h===0){h=Date.now();return}f=b.length-c;const y=Date.now()-h;f>=100*1024&&y>=1e3&&(this._params.onBandwidthChange({size:f,duration:y,speed:8*f/(y/1e3)}),f=0,c=b.length,h=Date.now()),this._onDashCallback("loading",{size:b.length,done:!1})},o,(b,y,T)=>this._params.onError(b,y,T))})}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=sr._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 CS{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=Bt(r)),new su(r,t,s=>{this.attachManifest(s,t,_S(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,b,y,T,g,v,S,E,P,x,Y,R,D,L,w;const V=u.getElementsByTagName("SegmentBase")[0],q=V&&o(V,"indexRange").split("-"),X=V&&V.getElementsByTagName("Initialization")[0],_=X&&o(X,"range").split("-");if(!_||!q){const Ie=u.parentElement;if((Ie==null?void 0:Ie.getAttribute("contentType"))==="text"){const Ze=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,U=(r?r+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),he=(b=Ie.getAttribute("lang"))!==null&&b!==void 0?b:void 0;U&&d.push({id:Ze,url:U,language:he})}return}const C=.1,H=Number((y=u.attributes.getNamedItem("bandwidth"))===null||y===void 0?void 0:y.value),te=(r?r+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let se;const pe=(g=(T=u.attributes.getNamedItem("frameRate"))===null||T===void 0?void 0:T.value)!==null&&g!==void 0?g:void 0;se=pe?Aa(pe):void 0,l.push({width:Number((v=u.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((S=u.attributes.getNamedItem("height"))===null||S===void 0?void 0:S.value),bandwidth:H,baseURL:te,failoverHosts:t,indexFrom:Number(q[0]),indexTo:Number(q[1]),initFrom:Number(_[0]),initTo:Number(_[1]),codecs:(P=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&P!==void 0?P:void 0,mimeType:(Y=(x=u.attributes.getNamedItem("mimeType"))===null||x===void 0?void 0:x.value)!==null&&Y!==void 0?Y:void 0,fps:se,bufferSize:C*H/8,bufferLength:C,name:(D=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&D!==void 0?D:void 0,id:(w=(L=u.attributes.getNamedItem("id"))===null||L===void 0?void 0:L.value)!==null&&w!==void 0?w:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const 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 sr({mediaSource:r,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),r.duration||(r.duration=this._duration),this._loopTimeout||l(),r.removeEventListener("sourceopen",d),r.removeEventListener("webkitsourceopen",d)};r.addEventListener("sourceopen",d,!1),r.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(r),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,r=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(r){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const r=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!r||!s){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(s.toTime<r.to+n){const o=this._findRef(s.toTime);o&&o.toTime<r.to+n?(this._buffer.smartRemove(s.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(s.fromTime-n,s.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,s.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return;if(Array.isArray(r)&&r.length===0){this._params.onError("emptyrefs","Empty refs");return}let s;for(let n=0;n<r.length;n++){const o=r[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!s||o.fromTime<s.fromTime)&&(s=o)}if(!s){const n=r[r.length-1];if(e>n.toTime)return n}return s}_isLastRef(e){var t;const r=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!r)return!1;const s=r[r.length-1];return e.fromTime===s.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const r=this._video.buffered.start(t),s=this._video.buffered.end(t);if(e>r&&e<s)return Math.round(s*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var F;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(F||(F={}));const IS=[F.PAUSED,F.PLAYING];class DS{constructor(e){this.videoState=new J(F.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Fe,this.droppedFramesManager=new Tr,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=({representations:t,textRepresentations:r})=>{var s,n,o;const l=[];for(const d of t){const u=(n=(s=d.name)!==null&&s!==void 0?s:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Si(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(r==null?void 0:r.length)>0){const d=[];for(const u of r){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(F.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var r;const s=(r=this.representations$.getValue().find(({representation:n})=>n===t))===null||r===void 0?void 0:r.track;s&&(this.params.output.currentVideoTrack$.next(s),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(s.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),r=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(o)};`}),s===exports.PlaybackState.STOPPED){t!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(F.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!r)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===B.Requested&&IS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_LOADED),this.prepare();return;case F.MANIFEST_LOADED:this.videoState.startTransitionTo(F.INITIAL_REPRESENTATION_SELECTED);return;case F.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(F.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case F.METADATA_LOADED:this.videoState.startTransitionTo(F.READY),this.dash.updateRefsForCurrentTime();return;case F.READY:s===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):s===exports.PlaybackState.PAUSED?(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed());return;case F.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(F.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case F.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:r})=>{this.log({message:`[videoState change] ${r}: ${JSON.stringify(t)}`})}),this.video=Ke(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Wb(this.video),this.dash=new CS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:r})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:r}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,r,s)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:r,thrown:s,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},s=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Xe(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.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===F.PLAYING||this.videoState.getState()===F.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(gt(this.video,t.isLooped,r)),this.subscription.add(Qe(this.video,t.volume,n.volumeState$,r)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(at(this.video,t.playbackRate,n.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(a.map(l=>l.map(({track:d})=>d)))}),o(rr(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===F.READY&&this.videoState.setState(F.READY)},r)).add(n.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},r)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(F.METADATA_LOADED)},r)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},r)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),y=s();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let T;if(!y&&a.isNonNullable(p))T=p;else{const g=tt(this.video.buffered,this.video.currentTime*1e3),v=y?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,S=Math.min(g/v,1);T=(d=Ht(h.map(({track:P})=>P),{container:b,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:S,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:P})=>P===c))===null||l===void 0?void 0:l.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}))===null||d===void 0?void 0:d.id;const E=t.autoVideoTrackLimits.getTransition();E&&e.autoVideoTrackLimits$.next(E.to)}return a.isNonNullable(T)?(u=h.find(({track:g})=>g.id===T))===null||u===void 0?void 0:u.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,r)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===F.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(F.INITIAL_REPRESENTATION_SELECTED),r)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&s()?l.height<=d.height:l===d)).subscribe(l=>{const d=tt(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(fe(l.baseURL)))},r)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=ru(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.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Je(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}var oe;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(oe||(oe={}));var ar;(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"})(ar||(ar={}));var $e;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})($e||($e={}));var j;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(j||(j={}));var Mt;(function(i){i.MP4="mp4",i.WEBM="webm"})(Mt||(Mt={}));var nr;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(nr||(nr={}));var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class ho{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 au extends ho{constructor(){super(),this.listeners||ho.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 nu=class{constructor(){Object.defineProperty(this,"signal",{value:new au,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&&(nu.prototype[Symbol.toStringTag]="AbortController",au.prototype[Symbol.toStringTag]="AbortSignal");function ou(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 NS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:r,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:s=!1}=i;if(!ou({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 Er=ou({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),lu=Er?NS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,oi=Er?lu.fetch:window.fetch;Er?lu.Request:window.Request;const Ot=Er?nu:window.AbortController;var ea=(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 xS=(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)},LS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",fo=LS?xS:window.requestIdleCallback;var fs,ps;let uu=!1;try{uu=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((ps=(fs=navigator.userAgent.match(/Version\/(\d+)/))===null||fs===void 0?void 0:fs[1])!==null&&ps!==void 0?ps:"",10)<16}catch(i){console.error(i)}class OS{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const r=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!r),this.currentTask=null}this.queue.length&&this.pull()}catch(r){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:r})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return Q(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(r=>{const s={operation:"append",data:e,signal:t,callback:r};this.queue.push(s),this.pull()})})}remove(e,t,r){return Q(this,void 0,void 0,function*(){return r&&r.aborted?!1:new Promise(s=>{const n={operation:"remove",from:e,to:t,signal:r,callback:s};this.queue.unshift(n),this.pull()})})}abort(e){return Q(this,void 0,void 0,function*(){return new Promise(t=>{let r;uu&&e?r={operation:"safariAbort",init:e,callback:t}:r={operation:"abort",callback:t};for(const{callback:s}of this.queue)s(!1);r&&(this.queue=[r]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:r}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&r==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${r}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var po=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ue{get id(){return this.type}get size(){return this.size32}constructor(e){this.cursor=0,this.source=e,this.children=[];const t=this.readUint32();this.size32=t<=e.buffer.byteLength?t:NaN,this.type=this.readString(4),this.size64=0,this.usertype=0,this.content=new DataView(e.buffer,e.byteOffset+this.cursor,this.size32?this.size32-8:void 0),this.children=this.parseChildrenBoxes()}parseChildrenBoxes(){return[]}readString(e,t="ascii"){const s=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,s}readUint8(){const e=this.source.getUint8(this.cursor);return this.cursor+=1,e}readUint16(){const e=this.source.getUint16(this.cursor);return this.cursor+=2,e}readUint32(){const e=this.source.getUint32(this.cursor);return this.cursor+=4,e}readUint64(){const e=this.source.getBigInt64(this.cursor);return this.cursor+=8,e}}class du extends Ue{}class BS extends Ue{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const r=this.readString(4);this.compatibleBrands.push(r),t-=4}}}class MS extends Ue{parseChildrenBoxes(){return Gt(this.content)}}class VS extends Ue{constructor(e){super(e),this.data=this.content}}class gi extends Ue{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class FS extends gi{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let r=this.readUint32();const s=r>>>31,n=r<<1>>>1,o=this.readUint32();r=this.readUint32();const l=r>>>28,d=r<<3>>>3;this.segments.push({referenceType:s,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class US extends Ue{parseChildrenBoxes(){return Gt(this.content)}}class jS extends Ue{parseChildrenBoxes(){return Gt(this.content)}}var pt;(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"})(pt||(pt={}));class HS extends gi{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=pt.MONOSCOPIC;break;case 1:this.stereoMode=pt.TOP_BOTTOM;break;case 2:this.stereoMode=pt.LEFT_RIGHT;break;case 3:this.stereoMode=pt.STEREO_CUSTOM;break;case 4:this.stereoMode=pt.RIGHT_LEFT;break}this.cursor+=1}}class GS extends gi{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class YS extends gi{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class qS extends Ue{parseChildrenBoxes(){return Gt(this.content)}}class zS extends gi{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 WS extends Ue{parseChildrenBoxes(){return Gt(this.content)}}class QS extends Ue{parseChildrenBoxes(){return Gt(this.content)}}const KS={ftyp:BS,moov:MS,mdat:VS,sidx:FS,trak:US,mdia:qS,tkhd:zS,minf:WS,sv3d:jS,st3d:HS,prhd:GS,proj:QS,equi:YS,unknown:du};class JS{createBox(e,t){const r=KS[e];return r?new r(t):new du(t)}createFromView(e){const r=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return $r.createBox(r,new DataView(e.buffer,e.byteOffset))}}const $r=new JS;function ti(i,e){const t=new TextDecoder("ascii");let r=i.byteOffset,s=[];for(;r<i.byteLength;){const n=t.decode(new DataView(i.buffer,r,1));if(n===e[s.length]?s.push(n):s=[],s.length===4&&s.join("")===e){const l=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+l>i.byteLength?null:$r.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function XS(i,e){const t=[];let r=0;for(;r<i.byteLength;){const s=ti(new DataView(i.buffer,i.byteOffset+r,i.byteLength-r),e);if(s)t.push(s),r+=s.size+s.source.byteOffset;else break}return t}function Gt(i){const e=[];let t=0;for(;t<i.byteLength;){const r=$r.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(r),!r.size)break;t+=r.size}return e}const ZS=new TextDecoder("ascii"),eg=i=>ZS.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",tg=i=>{const e=$r.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,r=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:j.NONE,time:{from:t,to:t+o},byte:{from:r,to:r+n.referencedSize-1}};return t+=o,r+=n.referencedSize,l})},ig=i=>{const e=XS(i,"mdat");if(e.length){const t=e.reduce((r,s)=>r+s.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},rg=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:nr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ti(i,"sv3d")){e.is3dVideo=!0;const r=ti(i,"st3d");r&&(e.stereoMode=r.stereoMode);const s=ti(i,"prhd");s&&(e.projectionData.pose.yaw=s.poseYawDegrees,e.projectionData.pose.pitch=s.posePitchDegrees,e.projectionData.pose.roll=s.poseRollDegrees);const n=ti(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},sg={validateData:eg,parseInit:rg,getIndexRange:()=>{},parseSegments:tg,parseFeedableSegmentChunk:ig};var $;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})($||($={}));var 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 mo={[$.EBML]:{type:A.Master},[$.EBMLVersion]:{type:A.UnsignedInteger},[$.EBMLReadVersion]:{type:A.UnsignedInteger},[$.EBMLMaxIDLength]:{type:A.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[$.DocType]:{type:A.String},[$.DocTypeVersion]:{type:A.UnsignedInteger},[$.DocTypeReadVersion]:{type:A.UnsignedInteger},[$.Void]:{type:A.Binary},[$.Segment]:{type:A.Master},[$.SeekHead]:{type:A.Master},[$.Seek]:{type:A.Master},[$.SeekID]:{type:A.Binary},[$.SeekPosition]:{type:A.UnsignedInteger},[$.Info]:{type:A.Master},[$.TimestampScale]:{type:A.UnsignedInteger},[$.Duration]:{type:A.Float},[$.Tracks]:{type:A.Master},[$.TrackEntry]:{type:A.Master},[$.Video]:{type:A.Master},[$.Projection]:{type:A.Master},[$.ProjectionType]:{type:A.UnsignedInteger},[$.ProjectionPrivate]:{type:A.Master},[$.Chapters]:{type:A.Master},[$.Cluster]:{type:A.Master},[$.Timestamp]:{type:A.UnsignedInteger},[$.SilentTracks]:{type:A.Master},[$.SilentTrackNumber]:{type:A.UnsignedInteger},[$.Position]:{type:A.UnsignedInteger},[$.PrevSize]:{type:A.UnsignedInteger},[$.SimpleBlock]:{type:A.Binary},[$.BlockGroup]:{type:A.Master},[$.EncryptedBlock]:{type:A.Binary},[$.Attachments]:{type:A.Master},[$.Tags]:{type:A.Master},[$.Cues]:{type:A.Master},[$.CuePoint]:{type:A.Master},[$.CueTime]:{type:A.UnsignedInteger},[$.CueTrackPositions]:{type:A.Master},[$.CueTrack]:{type:A.UnsignedInteger},[$.CueClusterPosition]:{type:A.UnsignedInteger},[$.CueRelativePosition]:{type:A.UnsignedInteger},[$.CueDuration]:{type:A.UnsignedInteger},[$.CueBlockNumber]:{type:A.UnsignedInteger},[$.CueCodecState]:{type:A.UnsignedInteger},[$.CueReference]:{type:A.Master},[$.CueRefTime]:{type:A.UnsignedInteger}},cu=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const r=or(i,t),s=r in mo,n=s?mo[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=or(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}},or=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Oe=(i,e)=>{switch(e){case A.SignedInteger:return i.getInt8(0);case A.UnsignedInteger:return or(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)}},Vt=(i,e)=>{let t=0;for(;t<i.byteLength;){const r=new DataView(i.buffer,i.byteOffset+t),s=cu(r);if(!e(s))return;s.type===A.Master&&Vt(s.value,e),t=s.value.byteOffset-i.byteOffset+s.valueSize}},ag=i=>{if(i.getUint32(0)!==$.EBML)return!1;let e,t,r;const s=cu(i);return Vt(s.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=Oe(l,o):n===$.DocType?t=Oe(l,o):n===$.DocTypeReadVersion&&(r=Oe(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(r===void 0||r<=2)},hu=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],ng=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],og=i=>{let e,t,r,s,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Vt(i,({tag:f,type:p,value:m,valueSize:b})=>{if(f===$.SeekID){const y=Oe(m,p);u=or(y)}else f!==$.SeekPosition&&(u=void 0);return f===$.Segment?(e=m.byteOffset,t=m.byteOffset+b):f===$.Info?n=!0:f===$.SeekHead?o=!0:f===$.TimestampScale?r=Oe(m,p):f===$.Duration?s=Oe(m,p):f===$.SeekPosition&&u===$.Cues?d=Oe(m,p):f===$.Tracks?Vt(m,({tag:y,type:T,value:g})=>y===$.ProjectionType?(c=Oe(g,T)===1,!1):!0):n&&o&&hu.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(s,"Failed to parse webm Segment duration"),r=r!=null?r:1e6,{segmentStart:Math.round(e/1e9*r*1e3),segmentEnd:Math.round(t/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(s/1e9*r*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:nr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},lg=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ug=(i,e)=>{let t=!1,r=!1;const s=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Vt(i,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&s(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=Oe(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=Oe(u,d));break;default:t&&hu.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:j.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}}})},dg=i=>{let e=0,t=!1;try{Vt(i,r=>r.tag===$.Cluster?r.tagSize<=i.byteLength?(e=r.tagSize,!1):(e+=r.tagHeaderSize,!0):ng.includes(r.tag)?(e+r.tagSize<=i.byteLength&&(e+=r.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(r.tag))),!0):!1)}catch(r){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},cg={validateData:ag,parseInit:og,getIndexRange:lg,parseSegments:ug,parseFeedableSegmentChunk:dg},fu=1e4,hg=3e4,fg=5e3,pg=fu,mg=({id:i,width:e,height:t,bitrate:r,fps:s,quality:n})=>{var o;const l=(o=n?Si(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:r,size:{width:e,height:t},fps:s}},vg=({id:i,bitrate:e})=>({id:i,bitrate:e}),bg=(i,e,t)=>{var r;const s=e.indexOf(t);return(r=xe(i,Math.round(i.length*s/e.length)))!==null&&r!==void 0?r:xe(i,-1)},Sg=({id:i,lang:e,url:t,isAuto:r})=>({id:i,url:t,isAuto:r,type:"internal",language:e}),ji=i=>{const e=[];let t=0,r=i.length-1;for(;t<fu&&r>=0;)e.unshift(i[r]),t+=i[r].time.to-i[r].time.from,r--;return e};class vo{constructor(e,t,r,s,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.isSeekingLive=!1,this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ot,this.destroyAbortController=new Ot,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){const h=this.representations.get(c);a.assertNonNullable(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new OS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(b=>{if(!this.sourceBuffer)return;const y=Math.min(this.bufferLimit,po(this.sourceBuffer.buffered)*.8);this.bufferLimit=y,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield yield I(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(a.assertNonNullable(f,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield I(void 0);this.searchGaps(p,h),yield yield I(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield I(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);a.assertNonNullable(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(a.isNullable(p)||a.isNullable(f)?yield yield I(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield I(p)),f=this.segments.get(c),a.assertNonNullable(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield I(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield I(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.searchGaps(f,h),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(c){return be(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield I(void 0);for(const y of this.representations.keys()){const T=c.find(S=>S.id===y);T&&this.representations.set(y,T);const g=this.representations.get(y);if(!g)return yield I(void 0);const v=ji(g.segmentReference.segments);this.segments.set(g.id,v)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,f=this.representations.get(h);a.assertNonNullable(f);const p=ji(f.segmentReference.segments),m=this.initData.get(f.id);if(a.assertNonNullable(m,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(m instanceof ArrayBuffer))return yield I(void 0);const b=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),b&&(yield yield I(this.sourceBufferTaskQueue.remove(b.from*1e3,b.to*1e3,this.destroyAbortController.signal))),this.searchGaps(p,f),yield yield I(this.sourceBufferTaskQueue.append(m,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isLive=!!(u!=null&&u.dynamic),this.container=r,r){case Mt.MP4:this.containerParser=sg;break;case Mt.WEBM:this.containerParser=cg;break;default:a.assertNever(r)}this.initData=new Map(s.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(s.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ot,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),r=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!r)return;const s=r.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=tt(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)&&po(this.sourceBuffer.buffered)>=this.bufferLimit){const u=tt(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=xe(l,0);c&&c.time.from-s.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&s&&s.status===j.FED&&!l.length&&tt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=xe(r,-1);d&&d.status===j.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===d))}searchGaps(e,t){this.gaps=[];let r=0;for(const s of e)s.time.from-r>0&&this.gaps.push({representation:t.id,from:r,to:s.time.from}),r=s.time.to;a.isNonNullable(t.duration)&&t.duration-r>0&&this.gaps.push({representation:t.id,from:r,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(s=>s.id===this.downloadingRepresentationId);if(!t)return;const r=this.segments.get(t.id);if(r!=null&&r.length)return{from:r[0].time.from,to:r[r.length-1].time.to}}updateLive(e){var t,r,s,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o)return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:j.NONE,size:void 0})),d=(r=this.segments.get(o.id))!==null&&r!==void 0?r:[],u=(n=(s=xe(d,-1))===null||s===void 0?void 0:s.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.round(u)>=Math.round(h.time.from)&&Math.round(u)<=Math.round(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=ji(l);this.segments.set(o.id,[...h])}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}findSegmentStartTime(e){var t,r,s;const n=(r=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&r!==void 0?r:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(s=l==null?void 0:l.time.from)!==null&&s!==void 0?s:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,r){return this.isLive?this.selectForwardBufferSegmentsLive(e,r):this.selectForwardBufferSegmentsRecord(e,t,r)}selectForwardBufferSegmentsLive(e,t){const r=e.findIndex(s=>t>=s.time.from&&t<s.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=r),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,r){const s=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const b=f<=r&&p>=r,y=f>r||b||m===0&&r===0,T=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=r+T||p<=r+T;return(h===j.NONE||h===j.PARTIALLY_EJECTED&&y&&g&&this.sourceBuffer&&!ea(this.sourceBuffer.buffered,r))&&y&&g});if(s===-1)return[];if(t!==$e.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===j.NONE||f.status===j.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 $e.BYTE_RANGE:{s=t.segmentReference.url,n={from:xe(e,0).byte.from,to:xe(e,-1).byte.to};break}case $e.TEMPLATE:{const u=xe(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=j.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return be(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield I(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=>{if(u.name!=="AbortError"){for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)}})})}onSegmentDownloadError(e){var t;let r=!1;const s=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(s)&&(r=tt((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),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=j.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===j.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=j.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===$e.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=r&&f.byte.to<r+e.byteLength))continue;if(n.aborted){o();continue}const y=p?f.byte.from-r:0,T=p?f.byte.to-r:e.byteLength,g=y<s,v=T<=s;if(f.status===j.DOWNLOADING&&g&&v){f.status=j.DOWNLOADED,this.activeSegments.delete(h);const S=new DataView(e.buffer,e.byteOffset+y,m);this.sourceBufferTaskQueue.append(S,n).then(E=>E&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(m,s-y),h.loadedBytes>h.feedingBytes)){const S=new DataView(e.buffer,e.byteOffset+y+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===m?S:this.containerParser.parseFeedableSegmentChunk(S);E!=null&&E.byteLength&&(f.status=j.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(P=>{if(n.aborted)o();else if(P)h.fedBytes+=E.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.NONE;for(const r of this.activeSegments.values())if(r.segment===e){this.activeSegments.delete(r);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[s,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=s)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const r=this.representations.get(e);r&&(this.initLoadIdleCallback=fo(()=>gr(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 be(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield I(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,s)).then(l=>Q(this,void 0,void 0,function*(){if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,this.isLive?ji(c):c),d&&this.parsedInitData.set(e.id,d)})).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===j.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===j.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===j.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===j.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const 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=fo(()=>{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!==j.FED&&n!==j.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=j.PARTIALLY_EJECTED:s.status=j.NONE)}}}var xt;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(xt||(xt={}));class gg{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 Ot,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(s){return be(this,arguments,function*(){let n=s;this.requestQuic&&(n=Bt(n));const o=yield yield I(oi(n,{signal:this.abortAllController.signal}).catch(Zt));return o?(this.onHeadersReceived(o.headers),yield I(o.text())):yield I(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(s,{rangeMethod:n=this.compatibilityMode?xt.HEADER:xt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return be(this,arguments,function*(){let b=s;const y=new Headers;if(o)switch(n){case xt.HEADER:{y.append("Range",`bytes=${o.from}-${o.to}`);break}case xt.PARAM:{const C=new URL(b,location.href);C.searchParams.append("bytes",`${o.from}-${o.to}`),b=C.toString();break}default:a.assertNever(n)}this.requestQuic&&(b=Bt(b));let T=this.abortAllController.signal,g;if(u){const C=new Ot;if(g=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{C.abort()}catch(H){Zt(H)}}),this.abortAllController.signal.aborted||u.aborted)try{C.abort()}catch(H){Zt(H)}T=C.signal}const v=a.now(),S=yield yield I(oi(b,{priority:d,headers:y,signal:T}).catch(Zt)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-v),!S)return g==null||g.unsubscribe(),yield I(null);if(!S.ok||!S.body)return g==null||g.unsubscribe(),yield I(Promise.reject(new Error(`Fetch error ${S.status}: ${S.statusText}`)));this.onHeadersReceived(S.headers);const P=parseInt((f=S.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!P){const C=yield yield I(S.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(C.byteLength,a.now()-E),l==null||l(new DataView(C),C.byteLength),g==null||g.unsubscribe(),yield I(C)}if(!l&&!c)return g==null||g.unsubscribe(),yield I(S.arrayBuffer());const[x,Y]=S.body.tee(),R=x.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(Y));let D=0;const L=new ArrayBuffer(P),w=new Uint8Array(L),V=new DataView(L);let q=!1;const X=C=>{g==null||g.unsubscribe(),q=!0,Zt(C)},_=a.abortable(T,function({done:C,value:H}){return be(this,arguments,function*(){if(D===0&&this.lastRequestFirstBytes$.next(a.now()-v),T.aborted)return g==null||g.unsubscribe(),yield I(void 0);!C&&H&&(w.set(H,D),D+=H.byteLength,l==null||l(V,D),yield yield I(R==null?void 0:R.read().then(_,X)))})}.bind(this));return yield yield I(R==null?void 0:R.read().then(_,X)),g==null||g.unsubscribe(),yield I(q?null:L)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(s,n,o){var l;return be(this,arguments,function*(){if(s.type!==$e.BYTE_RANGE)return yield I(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 b=yield yield I(this.fetch(s.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!b)return yield I(null);const y=new DataView(b,d-c,u-c+1);if(!n.validateData(y))throw new Error("Invalid media file");const T=n.parseInit(y),g=(l=s.indexRange)!==null&&l!==void 0?l:n.getIndexRange(T);if(!g)throw new ReferenceError("No way to load representation index");let v;if(f)v=new DataView(b,g.from-c,g.to-g.from+1);else{const E=yield yield I(this.fetch(s.url,{range:g,priority:o,measureThroughput:!1}));if(!E)return yield I(null);v=new DataView(E)}const S=n.parseSegments(v,T,g);return yield I({init:T,dataView:new DataView(b),segments:S})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(s,n){return be(this,arguments,function*(){if(s.type!==$e.TEMPLATE)return yield I(null);const o=new URL(s.initUrl,s.baseUrl).toString(),l=yield yield I(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield I(null);const d=s.segments.map(u=>Object.assign(Object.assign({},u),{status:j.NONE,size:void 0}));return yield I({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=r}onHeadersReceived(e){const{type:t,reused:r}=ru(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 $e.BYTE_RANGE:return(s=yield this.fetchByteRangeRepresentation(e,t,r))!==null&&s!==void 0?s:null;case $e.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,r))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Zt=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var yg=ze,Tg=ui,Eg=ce,$g=Eg("match"),kg=function(i){var e;return yg(i)&&((e=i[$g])!==void 0?!!e:Tg(i)=="RegExp")},Pg=pi,wg=String,Ag=function(i){if(Pg(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return wg(i)},_g=We,Rg=function(){var i=_g(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},Cg=ge,Ig=Ve,Dg=dr,Ng=Rg,bo=RegExp.prototype,xg=function(i){var e=i.flags;return e===void 0&&!("flags"in bo)&&!Ig(i,"flags")&&Dg(bo,i)?Cg(Ng,i):e},Ra=Pe,Lg=pr,Og=Math.floor,ms=Ra("".charAt),Bg=Ra("".replace),vs=Ra("".slice),Mg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Vg=/\$([$&'`]|\d{1,2})/g,Fg=function(i,e,t,r,s,n){var o=t+i.length,l=r.length,d=Vg;return s!==void 0&&(s=Lg(s),d=Mg),Bg(n,d,function(u,c){var h;switch(ms(c,0)){case"$":return"$";case"&":return i;case"`":return vs(e,0,t);case"'":return vs(e,o);case"<":h=s[vs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Og(f/10);return p===0?u:p<=l?r[p-1]===void 0?ms(c,1):r[p-1]+ms(c,1):u}h=r[f-1]}return h===void 0?"":h})},Ug=Ce,jg=ge,Ca=Pe,So=ra,Hg=ae,Gg=di,Yg=kg,Rt=Ag,qg=fr,zg=xg,Wg=Fg,Qg=ce,Kg=Qg("replace"),Jg=TypeError,pu=Ca("".indexOf),Xg=Ca("".replace),go=Ca("".slice),Zg=Math.max,yo=function(i,e,t){return t>i.length?-1:e===""?t:pu(i,e,t)};Ug({target:"String",proto:!0},{replaceAll:function(e,t){var r=So(this),s,n,o,l,d,u,c,h,f,p=0,m=0,b="";if(!Gg(e)){if(s=Yg(e),s&&(n=Rt(So(zg(e))),!~pu(n,"g")))throw Jg("`.replaceAll` does not allow non-global regexes");if(o=qg(e,Kg),o)return jg(o,e,r,t);if(s)return Xg(Rt(r),e,t)}for(l=Rt(r),d=Rt(e),u=Hg(t),u||(t=Rt(t)),c=d.length,h=Zg(1,c),p=yo(l,d,0);p!==-1;)f=u?Rt(t(d,p,l)):Wg(d,l,p,[],void 0,t),b+=go(l,m,p)+f,m=p+c,p=yo(l,d,p+h);return m<l.length&&(b+=go(l,m)),b}});var ey=Pa,ty=ey("String","replaceAll"),iy=ty,ry=iy,sy=ry,ay=sy,To=lr(ay);const Eo=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},bs=(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},ny=(i,e)=>{var t,r,s,n,o,l,d,u,c,h,f,p,m,b,y,T,g,v,S,E,P,x,Y,R,D,L,w,V,q,X,_,C,H,te,se,pe,Ie,Ze,U;const ye=new DOMParser().parseFromString(i,"application/xml"),me={video:[],audio:[],text:[]},Te=ye.children[0],yt=Te.getElementsByTagName("Period")[0],ot=yt.children,Tt=Te.getAttribute("type")==="dynamic",Et=Te.getAttribute("availabilityStartTime"),yi=Et?new Date(Et).getTime():void 0;let lt;const Ia=Te.getAttribute("mediaPresentationDuration"),Da=yt.getAttribute("duration"),kr=Te.getElementsByTagName("vk:Attrs")[0],Na=kr==null?void 0:kr.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Ia)lt=Eo(Ia);else if(Da){const we=Eo(Da);a.isNonNullable(we)&&(lt=we)}else Na&&(lt=parseInt(Na,10));let Eu=0;const Pr=(r=(t=Te.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&r!==void 0?r:[],$u=Pr.includes(ar.WEBM_AS_IN_FFMPEG)||Pr.includes(ar.WEBM_AS_IN_SPEC)?Mt.WEBM:Mt.MP4;for(const we of ot){const Ti=we.getAttribute("mimeType"),ku=we.getAttribute("codecs"),xa=(s=we.getAttribute("contentType"))!==null&&s!==void 0?s:Ti==null?void 0:Ti.split("/")[0],Pu=(o=(n=we.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],La=we.querySelectorAll("Representation"),wu=we.querySelector("SegmentTemplate");if(xa===oe.TEXT){for(const ie of La){const ut=ie.getAttribute("id")||"",Ei=we.getAttribute("lang"),$t=(u=(d=(l=ie.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",wr=new URL($t,e).toString();me[oe.TEXT].push({id:ut,lang:Ei,kind:oe.TEXT,url:wr})}continue}for(const ie of La){const ut=(c=ie.getAttribute("mimeType"))!==null&&c!==void 0?c:Ti,Ei=(f=(h=ie.getAttribute("codecs"))!==null&&h!==void 0?h:ku)!==null&&f!==void 0?f:"",$t=(m=(p=ie.getAttribute("contentType"))!==null&&p!==void 0?p:ut==null?void 0:ut.split("/")[0])!==null&&m!==void 0?m:xa,wr=(y=(b=we.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&y!==void 0?y:[],Au=parseInt((T=ie.getAttribute("width"))!==null&&T!==void 0?T:"",10),Oa=parseInt((g=ie.getAttribute("height"))!==null&&g!==void 0?g:"",10),Ba=parseInt((v=ie.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,Ma=(S=ie.getAttribute("frameRate"))!==null&&S!==void 0?S:"",_u=(E=ie.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Ru=Ma?Aa(Ma):void 0,Cu=(P=ie.getAttribute("id"))!==null&&P!==void 0?P:(Eu++).toString(10),Iu=$t==="video"?`${Oa}p`:$t==="audio"?`${Ba}Kbps`:Ei,Du=`${Cu}@${Iu}`,Nu=(R=(Y=(x=ie.querySelector("BaseURL"))===null||x===void 0?void 0:x.textContent)===null||Y===void 0?void 0:Y.trim())!==null&&R!==void 0?R:"",Va=new URL(Nu,e).toString(),xu=[...Pr,...Pu,...wr];let Ar;const Lu=ie.querySelector("SegmentBase"),dt=(D=ie.querySelector("SegmentTemplate"))!==null&&D!==void 0?D:wu;if(Lu){const Yt=(w=(L=ie.querySelector("SegmentBase Initialization"))===null||L===void 0?void 0:L.getAttribute("range"))!==null&&w!==void 0?w:"",[qt,Rr]=Yt.split("-").map(kt=>parseInt(kt,10)),zt={from:qt,to:Rr},Wt=(V=ie.querySelector("SegmentBase"))===null||V===void 0?void 0:V.getAttribute("indexRange"),[Cr,$i]=Wt?Wt.split("-").map(kt=>parseInt(kt,10)):[],Qt=Wt?{from:Cr,to:$i}:void 0;Ar={type:$e.BYTE_RANGE,url:Va,initRange:zt,indexRange:Qt}}else if(dt){const Yt={representationId:(q=ie.getAttribute("id"))!==null&&q!==void 0?q:void 0,bandwidth:(X=ie.getAttribute("bandwidth"))!==null&&X!==void 0?X:void 0},qt=parseInt((_=dt.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Rr=(C=dt.getAttribute("initialization"))!==null&&C!==void 0?C:"",zt=dt.getAttribute("media"),Wt=(te=parseInt((H=dt.getAttribute("startNumber"))!==null&&H!==void 0?H:"",10))!==null&&te!==void 0?te:1,Cr=bs(Rr,Yt);if(!zt)throw new ReferenceError("No media attribute in SegmentTemplate");const $i=(se=dt.querySelectorAll("SegmentTimeline S"))!==null&&se!==void 0?se:[],Qt=[];let kt=0;if($i.length){let Ir=Wt,je=0;for(const Kt of $i){const et=parseInt((pe=Kt.getAttribute("d"))!==null&&pe!==void 0?pe:"",10),ct=parseInt((Ie=Kt.getAttribute("r"))!==null&&Ie!==void 0?Ie:"",10)||0,ki=parseInt((Ze=Kt.getAttribute("t"))!==null&&Ze!==void 0?Ze:"",10);je=Number.isFinite(ki)?ki:je;const Dr=et/qt*1e3,Fa=je/qt*1e3;for(let Pi=0;Pi<ct+1;Pi++){const Ou=bs(zt,Object.assign(Object.assign({},Yt),{segmentNumber:Ir.toString(10),segmentTime:(je+Pi*et).toString(10)})),Ua=(Fa||0)+Pi*Dr,Bu=Ua+Dr;Ir++,Qt.push({time:{from:Ua,to:Bu},url:Ou})}je+=(ct+1)*et,kt+=(ct+1)*Dr}}else if(a.isNonNullable(lt)){const je=parseInt((U=dt.getAttribute("duration"))!==null&&U!==void 0?U:"",10)/qt*1e3,Kt=Math.ceil(lt/je);let et=0;for(let ct=1;ct<Kt;ct++){const ki=bs(zt,Object.assign(Object.assign({},Yt),{segmentNumber:ct.toString(10),segmentTime:et.toString(10)}));Qt.push({time:{from:et,to:et+je},url:ki}),et+=je}}Ar={type:$e.TEMPLATE,baseUrl:Va,initUrl:Cr,totalSegmentsDurationMs:kt,segments:Qt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!$t||!ut)continue;const _r={video:oe.VIDEO,audio:oe.AUDIO,text:oe.TEXT}[$t];_r&&me[_r].push({id:Du,kind:_r,segmentReference:Ar,profiles:xu,duration:lt,bitrate:Ba,mime:ut,codecs:Ei,width:Au,height:Oa,fps:Ru,quality:_u})}}return{dynamic:Tt,liveAvailabilityStartTime:yi,duration:lt,container:$u,representations:me}},ta=1e3,$o=["timeupdate","progress","play","seeked","stalled","waiting"];var Ee;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Ee||(Ee={}));let oy=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new J(Ee.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ot,this.initManifest=a.abortable(this.destroyController.signal,function(t,r,s){var n;return be(this,arguments,function*(){this.element=t,this.manifestUrlString=Me(r,s,ne.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ee.MANIFEST_READY),this.manifest=yield yield I(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Ee.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=a.abortable(this.destroyController.signal,function(){var t;return be(this,arguments,function*(){const r=yield yield I(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!r)return yield I(this.manifest);let s;try{s=ny(r!=null?r:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!s)return yield I(null);const n=({kind:o,mime:l,codecs:d})=>{var u,c,h,f;return!!(!((c=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||c===void 0)&&c.call(u,l)&&(!((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${d}"`))||o===oe.TEXT)};return this.isLive$.getValue()!==s.dynamic&&(this.isLive$.next(s.dynamic),this.liveDuration$.getValue()!==s.duration&&this.liveDuration$.next(-1*((t=s.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==s.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(s.liveAvailabilityStartTime)),yield I(Object.assign(Object.assign({},s),{representations:mi(Object.entries(s.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,r){return be(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ee.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new vo(oe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(r)&&(this.audioBufferManager=new vo(oe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(a.interval(ta).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=ao(this.manifestUrlString,ne.DASH_CMAF_OFFSET_P);this.manifestUrlString=Me(this.manifestUrlString,u+1e3,ne.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...$o.map(l=>a.fromEvent(this.element,l))).pipe(a.throttle(ta),a.map(l=>this.element?tt(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(d=>{var u,c;let h=0;if(d){const f=((c=(u=this.element)===null||u===void 0?void 0:u.currentTime)!==null&&c!==void 0?c:0)*1e3;h=Math.min(...this.bufferManagers.map(m=>{var b,y;return(y=(b=m.getLiveSegmentsToLoadState(this.manifest))===null||b===void 0?void 0:b.to)!==null&&y!==void 0?y:0}))-f}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(d=>Q(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const u=this.element.playbackRate,c=ao(this.manifestUrlString,ne.DASH_CMAF_OFFSET_P),h=hg*u,f=pg*u,p=fg*u;l=d>l?d:l;const m=c===0&&d<p,b=c!==0&&d<h+p&&d>=h,y=c!==0&&d<h;if(y||b){const T=l-(h+f),g=Math.trunc(c+T/u);let v;d?g>0?v=g:v=0:v=c,this.manifestUrlString=Me(this.manifestUrlString,v,ne.DASH_CMAF_OFFSET_P)}(m||y||b)&&(yield this.updateLive(),l=0)})))}const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield I(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 I(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(r)])):yield yield I(this.videoBufferManager.startWith(t)),this.state$.setState(Ee.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,r;if(!this.element||!this.videoBufferManager)return;const s=this.element.currentTime*1e3;this.videoBufferManager.maintain(s),(t=this.audioBufferManager)===null||t===void 0||t.maintain(s),(this.videoBufferManager.gaps.length||!((r=this.audioBufferManager)===null||r===void 0)&&r.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new gg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,r,s,n;return Q(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.manifestUrlString=Me(this.manifestUrlString,e,ne.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((r=this.manifest)===null||r===void 0?void 0:r.representations.video),yield(s=this.audioBufferManager)===null||s===void 0?void 0:s.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Ee.RUNNING),this.subscription.add(a.merge(...$o.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&&ea(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}switchRepresentation(e,t){return Q(this,void 0,void 0,function*(){const r={[oe.VIDEO]:this.videoBufferManager,[oe.AUDIO]:this.audioBufferManager,[oe.TEXT]:null}[e];return r==null?void 0:r.switchTo(t)})}seek(e,t){var r,s,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((r=this.videoBufferManager.findSegmentStartTime(e))!==null&&r!==void 0?r:e,(n=(s=this.audioBufferManager)===null||s===void 0?void 0:s.findSegmentStartTime(e))!==null&&n!==void 0?n:e),ea(this.element.buffered,d)||(this.videoBufferManager.abort(),(o=this.audioBufferManager)===null||o===void 0||o.abort()),this.videoBufferManager.maintain(d),(l=this.audioBufferManager)===null||l===void 0||l.maintain(d),this.element.currentTime=d/1e3}stop(){var e,t;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),(e=this.videoBufferManager)===null||e===void 0||e.destroy(),this.videoBufferManager=null,(t=this.audioBufferManager)===null||t===void 0||t.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Ee.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}updateLive(){var e;return Q(this,void 0,void 0,function*(){this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,r=[];for(const s of this.bufferManagers)for(const n of s.gaps)s.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?r.push(1/0):r.push(n.to));if(r.length){const s=Math.max(...r);s===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=s/1e3}}};class ly{constructor(e,t){this.fov=e,this.orientation=t}}class uy{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,r=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+r)}pointCameraTo(e=0,t=0,r=0){t=this.limitCameraRotationY(t);const s=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=r-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=r,this.lastCameraTurn={x:s,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,r){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=r!=null?r:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,r){this.setRotationSpeed(e,t,r),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,r=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r);else if(this.fading&&this.fadeStartSpeed){const s=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*s,this.fadeStartSpeed.y*s,this.fadeStartSpeed.z*s),s>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*r,this.rotationSpeed.y*this.options.rotationSpeedCorrection*r,this.rotationSpeed.z*this.options.rotationSpeedCorrection*r):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var dy=`#define GLSLIFY 1
|
|
7
|
-
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,
|
|
6
|
+
"use strict";var Gu=Object.create;var Qa=Object.defineProperty;var Yu=Object.getOwnPropertyDescriptor;var qu=Object.getOwnPropertyNames;var zu=Object.getPrototypeOf,Wu=Object.prototype.hasOwnProperty;var Qu=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of qu(e))!Wu.call(i,r)&&r!==t&&Qa(i,r,{get:()=>e[r],enumerable:!(s=Yu(e,r))||s.enumerable});return i};var Ka=(i,e,t)=>(t=i!=null?Gu(zu(i)):{},Qu(e||!i||!i.__esModule?Qa(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Ku=require("lodash/debounce.js");const Go="2.0.92-dev.61e3488.0";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ue;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(ue||(ue={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var B;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(B||(B={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(exports.Surface||(exports.Surface={}));function q(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 fe(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){s[f]&&(r[f]=function(p){return new Promise(function(m,b){n.push([f,p,m,b])>1||l(f,p)})})}function l(f,p){try{d(s[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof R?Promise.resolve(f.value.v).then(u,c):h(n[0][2],f)}function u(f){l("next",f)}function c(f){l("throw",f)}function h(f,p){f(p),n.shift(),n.length&&l(n[0][0],n[0][1])}}var Ju=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 Xu{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Ju("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(Zu),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 Zu=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var Vs=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function hs(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Pe=function(i){try{return!!i()}catch(e){return!0}},ed=Pe,fs=!ed(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Yo=fs,qo=Function.prototype,Br=qo.call,td=Yo&&qo.bind.bind(Br,Br),we=Yo?td:function(i){return function(){return Br.apply(i,arguments)}},zo=we,id=zo({}.toString),sd=zo("".slice),fi=function(i){return sd(id(i),8,-1)},rd=we,ad=Pe,nd=fi,Fs=Object,od=rd("".split),ld=ad(function(){return!Fs("z").propertyIsEnumerable(0)})?function(i){return nd(i)=="String"?od(i,""):Fs(i)}:Fs,pi=function(i){return i==null},ud=pi,dd=TypeError,da=function(i){if(ud(i))throw dd("Can't call method on "+i);return i},cd=ld,hd=da,mi=function(i){return cd(hd(i))},Qt={},Ri=function(i){return i&&i.Math==Math&&i},le=Ri(typeof globalThis=="object"&&globalThis)||Ri(typeof window=="object"&&window)||Ri(typeof self=="object"&&self)||Ri(typeof Vs=="object"&&Vs)||function(){return this}()||Vs||Function("return this")(),Mr=typeof document=="object"&&document.all,fd=typeof Mr=="undefined"&&Mr!==void 0,Wo={all:Mr,IS_HTMLDDA:fd},Qo=Wo,pd=Qo.all,ae=Qo.IS_HTMLDDA?function(i){return typeof i=="function"||i===pd}:function(i){return typeof i=="function"},md=le,vd=ae,Ja=md.WeakMap,bd=vd(Ja)&&/native code/.test(String(Ja)),Xa=ae,Ko=Wo,Sd=Ko.all,Qe=Ko.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Xa(i)||i===Sd}:function(i){return typeof i=="object"?i!==null:Xa(i)},gd=Pe,ot=!gd(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Et={},yd=le,Za=Qe,Vr=yd.document,Td=Za(Vr)&&Za(Vr.createElement),ca=function(i){return Td?Vr.createElement(i):{}},Ed=ot,$d=Pe,kd=ca,Jo=!Ed&&!$d(function(){return Object.defineProperty(kd("div"),"a",{get:function(){return 7}}).a!=7}),Pd=ot,wd=Pe,Xo=Pd&&wd(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Ad=Qe,_d=String,Cd=TypeError,Ke=function(i){if(Ad(i))return i;throw Cd(_d(i)+" is not an object")},Rd=fs,Di=Function.prototype.call,ge=Rd?Di.bind(Di):function(){return Di.apply(Di,arguments)},ha={},Us=ha,js=le,Dd=ae,en=function(i){return Dd(i)?i:void 0},$t=function(i,e){return arguments.length<2?en(Us[i])||en(js[i]):Us[i]&&Us[i][e]||js[i]&&js[i][e]},Id=we,ps=Id({}.isPrototypeOf),ms=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Zo=le,Hs=ms,tn=Zo.process,sn=Zo.Deno,rn=tn&&tn.versions||sn&&sn.version,an=rn&&rn.v8,De,is;an&&(De=an.split("."),is=De[0]>0&&De[0]<4?1:+(De[0]+De[1]));!is&&Hs&&(De=Hs.match(/Edge\/(\d+)/),(!De||De[1]>=74)&&(De=Hs.match(/Chrome\/(\d+)/),De&&(is=+De[1])));var el=is,nn=el,Nd=Pe,xd=le,Ld=xd.String,tl=!!Object.getOwnPropertySymbols&&!Nd(function(){var i=Symbol();return!Ld(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&nn&&nn<41}),Od=tl,il=Od&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Bd=$t,Md=ae,Vd=ps,Fd=il,Ud=Object,sl=Fd?function(i){return typeof i=="symbol"}:function(i){var e=Bd("Symbol");return Md(e)&&Vd(e.prototype,Ud(i))},jd=String,vs=function(i){try{return jd(i)}catch(e){return"Object"}},Hd=ae,Gd=vs,Yd=TypeError,kt=function(i){if(Hd(i))return i;throw Yd(Gd(i)+" is not a function")},qd=kt,zd=pi,bs=function(i,e){var t=i[e];return zd(t)?void 0:qd(t)},Gs=ge,Ys=ae,qs=Qe,Wd=TypeError,Qd=function(i,e){var t,s;if(e==="string"&&Ys(t=i.toString)&&!qs(s=Gs(t,i))||Ys(t=i.valueOf)&&!qs(s=Gs(t,i))||e!=="string"&&Ys(t=i.toString)&&!qs(s=Gs(t,i)))return s;throw Wd("Can't convert object to primitive value")},rl={exports:{}},Kd=!0,on=le,Jd=Object.defineProperty,Xd=function(i,e){try{Jd(on,i,{value:e,configurable:!0,writable:!0})}catch(t){on[i]=e}return e},Zd=le,ec=Xd,ln="__core-js_shared__",tc=Zd[ln]||ec(ln,{}),fa=tc,un=fa;(rl.exports=function(i,e){return un[i]||(un[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var al=rl.exports,ic=da,sc=Object,Ss=function(i){return sc(ic(i))},rc=we,ac=Ss,nc=rc({}.hasOwnProperty),je=Object.hasOwn||function(e,t){return nc(ac(e),t)},oc=we,lc=0,uc=Math.random(),dc=oc(1 .toString),nl=function(i){return"Symbol("+(i===void 0?"":i)+")_"+dc(++lc+uc,36)},cc=le,hc=al,dn=je,fc=nl,pc=tl,mc=il,Ft=cc.Symbol,zs=hc("wks"),vc=mc?Ft.for||Ft:Ft&&Ft.withoutSetter||fc,ce=function(i){return dn(zs,i)||(zs[i]=pc&&dn(Ft,i)?Ft[i]:vc("Symbol."+i)),zs[i]},bc=ge,cn=Qe,hn=sl,Sc=bs,gc=Qd,yc=ce,Tc=TypeError,Ec=yc("toPrimitive"),$c=function(i,e){if(!cn(i)||hn(i))return i;var t=Sc(i,Ec),s;if(t){if(e===void 0&&(e="default"),s=bc(t,i,e),!cn(s)||hn(s))return s;throw Tc("Can't convert object to primitive value")}return e===void 0&&(e="number"),gc(i,e)},kc=$c,Pc=sl,pa=function(i){var e=kc(i,"string");return Pc(e)?e:e+""},wc=ot,Ac=Jo,_c=Xo,Ii=Ke,fn=pa,Cc=TypeError,Ws=Object.defineProperty,Rc=Object.getOwnPropertyDescriptor,Qs="enumerable",Ks="configurable",Js="writable";Et.f=wc?_c?function(e,t,s){if(Ii(e),t=fn(t),Ii(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Js in s&&!s[Js]){var r=Rc(e,t);r&&r[Js]&&(e[t]=s.value,s={configurable:Ks in s?s[Ks]:r[Ks],enumerable:Qs in s?s[Qs]:r[Qs],writable:!1})}return Ws(e,t,s)}:Ws:function(e,t,s){if(Ii(e),t=fn(t),Ii(s),Ac)try{return Ws(e,t,s)}catch(r){}if("get"in s||"set"in s)throw Cc("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var gs=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Dc=ot,Ic=Et,Nc=gs,vi=Dc?function(i,e,t){return Ic.f(i,e,Nc(1,t))}:function(i,e,t){return i[e]=t,i},xc=al,Lc=nl,pn=xc("keys"),ma=function(i){return pn[i]||(pn[i]=Lc(i))},va={},Oc=bd,ol=le,Bc=Qe,Mc=vi,Xs=je,Zs=fa,Vc=ma,Fc=va,mn="Object already initialized",Fr=ol.TypeError,Uc=ol.WeakMap,ss,ui,rs,jc=function(i){return rs(i)?ui(i):ss(i,{})},Hc=function(i){return function(e){var t;if(!Bc(e)||(t=ui(e)).type!==i)throw Fr("Incompatible receiver, "+i+" required");return t}};if(Oc||Zs.state){var Oe=Zs.state||(Zs.state=new Uc);Oe.get=Oe.get,Oe.has=Oe.has,Oe.set=Oe.set,ss=function(i,e){if(Oe.has(i))throw Fr(mn);return e.facade=i,Oe.set(i,e),e},ui=function(i){return Oe.get(i)||{}},rs=function(i){return Oe.has(i)}}else{var It=Vc("state");Fc[It]=!0,ss=function(i,e){if(Xs(i,It))throw Fr(mn);return e.facade=i,Mc(i,It,e),e},ui=function(i){return Xs(i,It)?i[It]:{}},rs=function(i){return Xs(i,It)}}var ll={set:ss,get:ui,has:rs,enforce:jc,getterFor:Hc},Gc=fs,ul=Function.prototype,vn=ul.apply,bn=ul.call,dl=typeof Reflect=="object"&&Reflect.apply||(Gc?bn.bind(vn):function(){return bn.apply(vn,arguments)}),Yc=fi,qc=we,cl=function(i){if(Yc(i)==="Function")return qc(i)},ba={},hl={},fl={}.propertyIsEnumerable,pl=Object.getOwnPropertyDescriptor,zc=pl&&!fl.call({1:2},1);hl.f=zc?function(e){var t=pl(this,e);return!!t&&t.enumerable}:fl;var Wc=ot,Qc=ge,Kc=hl,Jc=gs,Xc=mi,Zc=pa,eh=je,th=Jo,Sn=Object.getOwnPropertyDescriptor;ba.f=Wc?Sn:function(e,t){if(e=Xc(e),t=Zc(t),th)try{return Sn(e,t)}catch(s){}if(eh(e,t))return Jc(!Qc(Kc.f,e,t),e[t])};var ih=Pe,sh=ae,rh=/#|\.prototype\./,bi=function(i,e){var t=nh[ah(i)];return t==lh?!0:t==oh?!1:sh(e)?ih(e):!!e},ah=bi.normalize=function(i){return String(i).replace(rh,".").toLowerCase()},nh=bi.data={},oh=bi.NATIVE="N",lh=bi.POLYFILL="P",ml=bi,gn=cl,uh=kt,dh=fs,ch=gn(gn.bind),ys=function(i,e){return uh(i),e===void 0?i:dh?ch(i,e):function(){return i.apply(e,arguments)}},Ni=le,hh=dl,fh=cl,ph=ae,mh=ba.f,vh=ml,Nt=ha,bh=ys,xt=vi,yn=je,Sh=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 hh(i,this,arguments)};return e.prototype=i.prototype,e},Ne=function(i,e){var t=i.target,s=i.global,r=i.stat,n=i.proto,o=s?Ni:r?Ni[t]:(Ni[t]||{}).prototype,l=s?Nt:Nt[t]||xt(Nt,t,{})[t],d=l.prototype,u,c,h,f,p,m,b,y,S;for(f in e)u=vh(s?f:t+(r?".":"#")+f,i.forced),c=!u&&o&&yn(o,f),m=l[f],c&&(i.dontCallGetSet?(S=mh(o,f),b=S&&S.value):b=o[f]),p=c&&b?b:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?y=bh(p,Ni):i.wrap&&c?y=Sh(p):n&&ph(p)?y=fh(p):y=p,(i.sham||p&&p.sham||m&&m.sham)&&xt(y,"sham",!0),xt(l,f,y),n&&(h=t+"Prototype",yn(Nt,h)||xt(Nt,h,{}),xt(Nt[h],f,p),i.real&&d&&(u||!d[f])&&xt(d,f,p)))},Ur=ot,gh=je,vl=Function.prototype,yh=Ur&&Object.getOwnPropertyDescriptor,Sa=gh(vl,"name"),Th=Sa&&function(){}.name==="something",Eh=Sa&&(!Ur||Ur&&yh(vl,"name").configurable),$h={EXISTS:Sa,PROPER:Th,CONFIGURABLE:Eh},bl={},kh=Math.ceil,Ph=Math.floor,wh=Math.trunc||function(e){var t=+e;return(t>0?Ph:kh)(t)},Ah=wh,ga=function(i){var e=+i;return e!==e||e===0?0:Ah(e)},_h=ga,Ch=Math.max,Rh=Math.min,Dh=function(i,e){var t=_h(i);return t<0?Ch(t+e,0):Rh(t,e)},Ih=ga,Nh=Math.min,xh=function(i){return i>0?Nh(Ih(i),9007199254740991):0},Lh=xh,ya=function(i){return Lh(i.length)},Oh=mi,Bh=Dh,Mh=ya,Tn=function(i){return function(e,t,s){var r=Oh(e),n=Mh(r),o=Bh(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}},Vh={includes:Tn(!0),indexOf:Tn(!1)},Fh=we,er=je,Uh=mi,jh=Vh.indexOf,Hh=va,En=Fh([].push),Gh=function(i,e){var t=Uh(i),s=0,r=[],n;for(n in t)!er(Hh,n)&&er(t,n)&&En(r,n);for(;e.length>s;)er(t,n=e[s++])&&(~jh(r,n)||En(r,n));return r},Sl=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Yh=Gh,qh=Sl,zh=Object.keys||function(e){return Yh(e,qh)},Wh=ot,Qh=Xo,Kh=Et,Jh=Ke,Xh=mi,Zh=zh;bl.f=Wh&&!Qh?Object.defineProperties:function(e,t){Jh(e);for(var s=Xh(t),r=Zh(t),n=r.length,o=0,l;n>o;)Kh.f(e,l=r[o++],s[l]);return e};var ef=$t,gl=ef("document","documentElement"),tf=Ke,sf=bl,$n=Sl,rf=va,af=gl,nf=ca,of=ma,kn=">",Pn="<",jr="prototype",Hr="script",yl=of("IE_PROTO"),tr=function(){},Tl=function(i){return Pn+Hr+kn+i+Pn+"/"+Hr+kn},wn=function(i){i.write(Tl("")),i.close();var e=i.parentWindow.Object;return i=null,e},lf=function(){var i=nf("iframe"),e="java"+Hr+":",t;return i.style.display="none",af.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(Tl("document.F=Object")),t.close(),t.F},xi,Xi=function(){try{xi=new ActiveXObject("htmlfile")}catch(e){}Xi=typeof document!="undefined"?document.domain&&xi?wn(xi):lf():wn(xi);for(var i=$n.length;i--;)delete Xi[jr][$n[i]];return Xi()};rf[yl]=!0;var El=Object.create||function(e,t){var s;return e!==null?(tr[jr]=tf(e),s=new tr,tr[jr]=null,s[yl]=e):s=Xi(),t===void 0?s:sf.f(s,t)},uf=Pe,df=!uf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),cf=je,hf=ae,ff=Ss,pf=ma,mf=df,An=pf("IE_PROTO"),Gr=Object,vf=Gr.prototype,$l=mf?Gr.getPrototypeOf:function(i){var e=ff(i);if(cf(e,An))return e[An];var t=e.constructor;return hf(t)&&e instanceof t?t.prototype:e instanceof Gr?vf:null},bf=vi,Ta=function(i,e,t,s){return s&&s.enumerable?i[e]=t:bf(i,e,t),i},Sf=Pe,gf=ae,yf=Qe,Tf=El,_n=$l,Ef=Ta,$f=ce,Yr=$f("iterator"),kl=!1,ze,ir,sr;[].keys&&(sr=[].keys(),"next"in sr?(ir=_n(_n(sr)),ir!==Object.prototype&&(ze=ir)):kl=!0);var kf=!yf(ze)||Sf(function(){var i={};return ze[Yr].call(i)!==i});kf?ze={}:ze=Tf(ze);gf(ze[Yr])||Ef(ze,Yr,function(){return this});var Pl={IteratorPrototype:ze,BUGGY_SAFARI_ITERATORS:kl},Pf=ce,wf=Pf("toStringTag"),wl={};wl[wf]="z";var Ea=String(wl)==="[object z]",Af=Ea,_f=ae,Zi=fi,Cf=ce,Rf=Cf("toStringTag"),Df=Object,If=Zi(function(){return arguments}())=="Arguments",Nf=function(i,e){try{return i[e]}catch(t){}},Si=Af?Zi:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Nf(e=Df(i),Rf))=="string"?t:If?Zi(e):(s=Zi(e))=="Object"&&_f(e.callee)?"Arguments":s},xf=Ea,Lf=Si,Of=xf?{}.toString:function(){return"[object "+Lf(this)+"]"},Bf=Ea,Mf=Et.f,Vf=vi,Ff=je,Uf=Of,jf=ce,Cn=jf("toStringTag"),$a=function(i,e,t,s){if(i){var r=t?i:i.prototype;Ff(r,Cn)||Mf(r,Cn,{configurable:!0,value:e}),s&&!Bf&&Vf(r,"toString",Uf)}},Hf=Pl.IteratorPrototype,Gf=El,Yf=gs,qf=$a,zf=Qt,Wf=function(){return this},Qf=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Gf(Hf,{next:Yf(+!s,t)}),qf(i,r,!1,!0),zf[r]=Wf,i},Kf=Ne,Jf=ge,Al=$h,Xf=Qf,Zf=$l,ep=$a,Rn=Ta,tp=ce,Dn=Qt,_l=Pl,ip=Al.PROPER;Al.CONFIGURABLE;_l.IteratorPrototype;var Li=_l.BUGGY_SAFARI_ITERATORS,rr=tp("iterator"),In="keys",Oi="values",Nn="entries",sp=function(){return this},rp=function(i,e,t,s,r,n,o){Xf(t,e,s);var l=function(S){if(S===r&&f)return f;if(!Li&&S in c)return c[S];switch(S){case In:return function(){return new t(this,S)};case Oi:return function(){return new t(this,S)};case Nn:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[rr]||c["@@iterator"]||r&&c[r],f=!Li&&h||l(r),p=e=="Array"&&c.entries||h,m,b,y;if(p&&(m=Zf(p.call(new i)),m!==Object.prototype&&m.next&&(ep(m,d,!0,!0),Dn[d]=sp)),ip&&r==Oi&&h&&h.name!==Oi&&(u=!0,f=function(){return Jf(h,this)}),r)if(b={values:l(Oi),keys:n?f:l(In),entries:l(Nn)},o)for(y in b)(Li||u||!(y in c))&&Rn(c,y,b[y]);else Kf({target:e,proto:!0,forced:Li||u},b);return o&&c[rr]!==f&&Rn(c,rr,f,{name:r}),Dn[e]=f,b},ap=function(i,e){return{value:i,done:e}},np=mi,xn=Qt,Cl=ll;Et.f;var op=rp,Bi=ap,Rl="Array Iterator",lp=Cl.set,up=Cl.getterFor(Rl);op(Array,"Array",function(i,e){lp(this,{type:Rl,target:np(i),index:0,kind:e})},function(){var i=up(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Bi(void 0,!0)):t=="keys"?Bi(s,!1):t=="values"?Bi(e[s],!1):Bi([s,e[s]],!1)},"values");xn.Arguments=xn.Array;var dp=ce,cp=Qt,hp=dp("iterator"),fp=Array.prototype,pp=function(i){return i!==void 0&&(cp.Array===i||fp[hp]===i)},mp=Si,Ln=bs,vp=pi,bp=Qt,Sp=ce,gp=Sp("iterator"),Dl=function(i){if(!vp(i))return Ln(i,gp)||Ln(i,"@@iterator")||bp[mp(i)]},yp=ge,Tp=kt,Ep=Ke,$p=vs,kp=Dl,Pp=TypeError,wp=function(i,e){var t=arguments.length<2?kp(i):e;if(Tp(t))return Ep(yp(t,i));throw Pp($p(i)+" is not iterable")},Ap=ge,On=Ke,_p=bs,Cp=function(i,e,t){var s,r;On(i);try{if(s=_p(i,"return"),!s){if(e==="throw")throw t;return t}s=Ap(s,i)}catch(n){r=!0,s=n}if(e==="throw")throw t;if(r)throw s;return On(s),t},Rp=ys,Dp=ge,Ip=Ke,Np=vs,xp=pp,Lp=ya,Bn=ps,Op=wp,Bp=Dl,Mn=Cp,Mp=TypeError,es=function(i,e){this.stopped=i,this.result=e},Vn=es.prototype,ka=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=Rp(e,s),u,c,h,f,p,m,b,y=function($){return u&&Mn(u,"normal",$),new es(!0,$)},S=function($){return r?(Ip($),l?d($[0],$[1],y):d($[0],$[1])):l?d($,y):d($)};if(n)u=i.iterator;else if(o)u=i;else{if(c=Bp(i),!c)throw Mp(Np(i)+" is not iterable");if(xp(c)){for(h=0,f=Lp(i);f>h;h++)if(p=S(i[h]),p&&Bn(Vn,p))return p;return new es(!1)}u=Op(i,c)}for(m=n?i.next:u.next;!(b=Dp(m,u)).done;){try{p=S(b.value)}catch($){Mn(u,"throw",$)}if(typeof p=="object"&&p&&Bn(Vn,p))return p}return new es(!1)},Vp=pa,Fp=Et,Up=gs,jp=function(i,e,t){var s=Vp(e);s in i?Fp.f(i,s,Up(0,t)):i[s]=t},Hp=Ne,Gp=ka,Yp=jp;Hp({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Gp(e,function(s,r){Yp(t,s,r)},{AS_ENTRIES:!0}),t}});var qp=ha,zp=qp.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},Qp=Wp,Kp=le,Jp=Si,Xp=vi,Fn=Qt,Zp=ce,Un=Zp("toStringTag");for(var ar in Qp){var jn=Kp[ar],nr=jn&&jn.prototype;nr&&Jp(nr)!==Un&&Xp(nr,Un,ar),Fn[ar]=Fn.Array}var em=zp,tm=em,im=tm,sm=im,gi=hs(sm),rm=fi,Ts=typeof process!="undefined"&&rm(process)=="process",am=Et,nm=function(i,e,t){return am.f(i,e,t)},om=$t,lm=nm,um=ce,dm=ot,Hn=um("species"),cm=function(i){var e=om(i);dm&&e&&!e[Hn]&&lm(e,Hn,{configurable:!0,get:function(){return this}})},hm=ps,fm=TypeError,pm=function(i,e){if(hm(e,i))return i;throw fm("Incorrect invocation")},mm=we,vm=ae,qr=fa,bm=mm(Function.toString);vm(qr.inspectSource)||(qr.inspectSource=function(i){return bm(i)});var Il=qr.inspectSource,Sm=we,gm=Pe,Nl=ae,ym=Si,Tm=$t,Em=Il,xl=function(){},$m=[],Ll=Tm("Reflect","construct"),Pa=/^\s*(?:class|function)\b/,km=Sm(Pa.exec),Pm=!Pa.exec(xl),ti=function(e){if(!Nl(e))return!1;try{return Ll(xl,$m,e),!0}catch(t){return!1}},Ol=function(e){if(!Nl(e))return!1;switch(ym(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return Pm||!!km(Pa,Em(e))}catch(t){return!0}};Ol.sham=!0;var wm=!Ll||gm(function(){var i;return ti(ti.call)||!ti(Object)||!ti(function(){i=!0})||i})?Ol:ti,Am=wm,_m=vs,Cm=TypeError,Rm=function(i){if(Am(i))return i;throw Cm(_m(i)+" is not a constructor")},Gn=Ke,Dm=Rm,Im=pi,Nm=ce,xm=Nm("species"),Bl=function(i,e){var t=Gn(i).constructor,s;return t===void 0||Im(s=Gn(t)[xm])?e:Dm(s)},Lm=we,Om=Lm([].slice),Bm=TypeError,Mm=function(i,e){if(i<e)throw Bm("Not enough arguments");return i},Vm=ms,Ml=/(?:ipad|iphone|ipod).*applewebkit/i.test(Vm),Se=le,Fm=dl,Um=ys,Yn=ae,jm=je,Vl=Pe,qn=gl,Hm=Om,zn=ca,Gm=Mm,Ym=Ml,qm=Ts,zr=Se.setImmediate,Wr=Se.clearImmediate,zm=Se.process,or=Se.Dispatch,Wm=Se.Function,Wn=Se.MessageChannel,Qm=Se.String,lr=0,ni={},Qn="onreadystatechange",di,St,ur,dr;Vl(function(){di=Se.location});var wa=function(i){if(jm(ni,i)){var e=ni[i];delete ni[i],e()}},cr=function(i){return function(){wa(i)}},Kn=function(i){wa(i.data)},Jn=function(i){Se.postMessage(Qm(i),di.protocol+"//"+di.host)};(!zr||!Wr)&&(zr=function(e){Gm(arguments.length,1);var t=Yn(e)?e:Wm(e),s=Hm(arguments,1);return ni[++lr]=function(){Fm(t,void 0,s)},St(lr),lr},Wr=function(e){delete ni[e]},qm?St=function(i){zm.nextTick(cr(i))}:or&&or.now?St=function(i){or.now(cr(i))}:Wn&&!Ym?(ur=new Wn,dr=ur.port2,ur.port1.onmessage=Kn,St=Um(dr.postMessage,dr)):Se.addEventListener&&Yn(Se.postMessage)&&!Se.importScripts&&di&&di.protocol!=="file:"&&!Vl(Jn)?(St=Jn,Se.addEventListener("message",Kn,!1)):Qn in zn("script")?St=function(i){qn.appendChild(zn("script"))[Qn]=function(){qn.removeChild(this),wa(i)}}:St=function(i){setTimeout(cr(i),0)});var Fl={set:zr,clear:Wr},Ul=function(){this.head=null,this.tail=null};Ul.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 jl=Ul,Km=ms,Jm=/ipad|iphone|ipod/i.test(Km)&&typeof Pebble!="undefined",Xm=ms,Zm=/web0s(?!.*chrome)/i.test(Xm),Tt=le,Xn=ys,ev=ba.f,hr=Fl.set,tv=jl,iv=Ml,sv=Jm,rv=Zm,fr=Ts,Zn=Tt.MutationObserver||Tt.WebKitMutationObserver,eo=Tt.document,to=Tt.process,Mi=Tt.Promise,io=ev(Tt,"queueMicrotask"),Qr=io&&io.value,Lt,pr,mr,Vi,so;if(!Qr){var Fi=new tv,Ui=function(){var i,e;for(fr&&(i=to.domain)&&i.exit();e=Fi.get();)try{e()}catch(t){throw Fi.head&&Lt(),t}i&&i.enter()};!iv&&!fr&&!rv&&Zn&&eo?(pr=!0,mr=eo.createTextNode(""),new Zn(Ui).observe(mr,{characterData:!0}),Lt=function(){mr.data=pr=!pr}):!sv&&Mi&&Mi.resolve?(Vi=Mi.resolve(void 0),Vi.constructor=Mi,so=Xn(Vi.then,Vi),Lt=function(){so(Ui)}):fr?Lt=function(){to.nextTick(Ui)}:(hr=Xn(hr,Tt),Lt=function(){hr(Ui)}),Qr=function(i){Fi.head||Lt(),Fi.add(i)}}var av=Qr,nv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Aa=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},ov=le,Kt=ov.Promise,Hl=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",lv=Hl,uv=Ts,dv=!lv&&!uv&&typeof window=="object"&&typeof document=="object",cv=le,oi=Kt,hv=ae,fv=ml,pv=Il,mv=ce,vv=dv,bv=Hl,vr=el,ro=oi&&oi.prototype,Sv=mv("species"),Kr=!1,Gl=hv(cv.PromiseRejectionEvent),gv=fv("Promise",function(){var i=pv(oi),e=i!==String(oi);if(!e&&vr===66||!(ro.catch&&ro.finally))return!0;if(!vr||vr<51||!/native code/.test(i)){var t=new oi(function(n){n(1)}),s=function(n){n(function(){},function(){})},r=t.constructor={};if(r[Sv]=s,Kr=t.then(function(){})instanceof s,!Kr)return!0}return!e&&(vv||bv)&&!Gl}),yi={CONSTRUCTOR:gv,REJECTION_EVENT:Gl,SUBCLASSING:Kr},Jt={},ao=kt,yv=TypeError,Tv=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw yv("Bad Promise constructor");e=s,t=r}),this.resolve=ao(e),this.reject=ao(t)};Jt.f=function(i){return new Tv(i)};var Ev=Ne,as=Ts,nt=le,Ti=ge,$v=Ta,kv=$a,Pv=cm,wv=kt,Jr=ae,Av=Qe,_v=pm,Cv=Bl,Yl=Fl.set,_a=av,Rv=nv,Dv=Aa,Iv=jl,ql=ll,Xr=Kt,Ca=yi,zl=Jt,Es="Promise",Wl=Ca.CONSTRUCTOR,Nv=Ca.REJECTION_EVENT;Ca.SUBCLASSING;var br=ql.getterFor(Es),xv=ql.set,Lv=Xr&&Xr.prototype,Ut=Xr,Sr=Lv,Ql=nt.TypeError,Zr=nt.document,Ra=nt.process,ea=zl.f,Ov=ea,Bv=!!(Zr&&Zr.createEvent&&nt.dispatchEvent),Kl="unhandledrejection",Mv="rejectionhandled",no=0,Jl=1,Vv=2,Da=1,Xl=2,ji,oo,Fv,Zl=function(i){var e;return Av(i)&&Jr(e=i.then)?e:!1},eu=function(i,e){var t=e.value,s=e.state==Jl,r=s?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{r?(s||(e.rejection===Xl&&jv(e),e.rejection=Da),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===i.promise?o(Ql("Promise-chain cycle")):(u=Zl(d))?Ti(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},tu=function(i,e){i.notified||(i.notified=!0,_a(function(){for(var t=i.reactions,s;s=t.get();)eu(s,i);i.notified=!1,e&&!i.rejection&&Uv(i)}))},iu=function(i,e,t){var s,r;Bv?(s=Zr.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),nt.dispatchEvent(s)):s={promise:e,reason:t},!Nv&&(r=nt["on"+i])?r(s):i===Kl&&Rv("Unhandled promise rejection",t)},Uv=function(i){Ti(Yl,nt,function(){var e=i.facade,t=i.value,s=lo(i),r;if(s&&(r=Dv(function(){as?Ra.emit("unhandledRejection",t,e):iu(Kl,e,t)}),i.rejection=as||lo(i)?Xl:Da,r.error))throw r.value})},lo=function(i){return i.rejection!==Da&&!i.parent},jv=function(i){Ti(Yl,nt,function(){var e=i.facade;as?Ra.emit("rejectionHandled",e):iu(Mv,e,i.value)})},jt=function(i,e,t){return function(s){i(e,s,t)}},Gt=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Vv,tu(i,!0))},ta=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Ql("Promise can't be resolved itself");var s=Zl(e);s?_a(function(){var r={done:!1};try{Ti(s,e,jt(ta,r,i),jt(Gt,r,i))}catch(n){Gt(r,n,i)}}):(i.value=e,i.state=Jl,tu(i,!1))}catch(r){Gt({done:!1},r,i)}}};Wl&&(Ut=function(e){_v(this,Sr),wv(e),Ti(ji,this);var t=br(this);try{e(jt(ta,t),jt(Gt,t))}catch(s){Gt(t,s)}},Sr=Ut.prototype,ji=function(e){xv(this,{type:Es,done:!1,notified:!1,parent:!1,reactions:new Iv,rejection:!1,state:no,value:void 0})},ji.prototype=$v(Sr,"then",function(e,t){var s=br(this),r=ea(Cv(this,Ut));return s.parent=!0,r.ok=Jr(e)?e:!0,r.fail=Jr(t)&&t,r.domain=as?Ra.domain:void 0,s.state==no?s.reactions.add(r):_a(function(){eu(r,s)}),r.promise}),oo=function(){var i=new ji,e=br(i);this.promise=i,this.resolve=jt(ta,e),this.reject=jt(Gt,e)},zl.f=ea=function(i){return i===Ut||i===Fv?new oo(i):Ov(i)});Ev({global:!0,constructor:!0,wrap:!0,forced:Wl},{Promise:Ut});kv(Ut,Es,!1,!0);Pv(Es);var Hv=ce,su=Hv("iterator"),ru=!1;try{var Gv=0,uo={next:function(){return{done:!!Gv++}},return:function(){ru=!0}};uo[su]=function(){return this},Array.from(uo,function(){throw 2})}catch(i){}var Yv=function(i,e){if(!e&&!ru)return!1;var t=!1;try{var s={};s[su]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},qv=Kt,zv=Yv,Wv=yi.CONSTRUCTOR,au=Wv||!zv(function(i){qv.all(i).then(void 0,function(){})}),Qv=Ne,Kv=ge,Jv=kt,Xv=Jt,Zv=Aa,eb=ka,tb=au;Qv({target:"Promise",stat:!0,forced:tb},{all:function(e){var t=this,s=Xv.f(t),r=s.resolve,n=s.reject,o=Zv(function(){var l=Jv(t.resolve),d=[],u=0,c=1;eb(e,function(h){var f=u++,p=!1;c++,Kv(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||r(d))},n)}),--c||r(d)});return o.error&&n(o.value),s.promise}});var ib=Ne,sb=yi.CONSTRUCTOR,co=Kt;co&&co.prototype;ib({target:"Promise",proto:!0,forced:sb,real:!0},{catch:function(i){return this.then(void 0,i)}});var rb=Ne,ab=ge,nb=kt,ob=Jt,lb=Aa,ub=ka,db=au;rb({target:"Promise",stat:!0,forced:db},{race:function(e){var t=this,s=ob.f(t),r=s.reject,n=lb(function(){var o=nb(t.resolve);ub(e,function(l){ab(o,t,l).then(s.resolve,r)})});return n.error&&r(n.value),s.promise}});var cb=Ne,hb=ge,fb=Jt,pb=yi.CONSTRUCTOR;cb({target:"Promise",stat:!0,forced:pb},{reject:function(e){var t=fb.f(this);return hb(t.reject,void 0,e),t.promise}});var mb=Ke,vb=Qe,bb=Jt,nu=function(i,e){if(mb(i),vb(e)&&e.constructor===i)return e;var t=bb.f(i),s=t.resolve;return s(e),t.promise},Sb=Ne,gb=$t,yb=Kd,Tb=Kt,Eb=yi.CONSTRUCTOR,$b=nu,kb=gb("Promise"),Pb=!Eb;Sb({target:"Promise",stat:!0,forced:yb},{resolve:function(e){return $b(Pb&&this===kb?Tb:this,e)}});var wb=Ne,ia=Kt,Ab=Pe,_b=$t,Cb=ae,Rb=Bl,ho=nu,Db=ia&&ia.prototype,Ib=!!ia&&Ab(function(){Db.finally.call({then:function(){}},function(){})});wb({target:"Promise",proto:!0,real:!0,forced:Ib},{finally:function(i){var e=Rb(this,_b("Promise")),t=Cb(i);return this.then(t?function(s){return ho(e,i()).then(function(){return s})}:i,t?function(s){return ho(e,i()).then(function(){throw s})}:i)}});var Nb=$t,Ia=Nb,xb=Ia,Lb=xb("Promise","finally"),Ob=Lb,Bb=Ob,Mb=Bb,Vb=Mb,$s=hs(Vb),ne;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ne||(ne={}));var Ue=(i,e=0,t=ne.OFFSET_P)=>{switch(t){case ne.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ne.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ne.DASH_CMAF_OFFSET_P:{const s=new URL(i);return s.searchParams.set("offset_p",e.toFixed(0)),s.toString()}default:a.assertNever(t)}return i};const fo=(i,e)=>{var t;switch(e){case ne.OFFSET_P:return NaN;case ne.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ne.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var k=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.setState(e)};class X{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e}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 Fb=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var x;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(x||(x={}));const Ub=5,jb=5,Hb=500,po=7e3;class Gb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new X(x.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!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&s!==x.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case x.PLAYING:case x.PAUSED:case x.READY:break;case x.STOPPED:this.videoState.startTransitionTo(x.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case x.PLAYING:break;case x.PAUSED:this.videoState.startTransitionTo(x.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case x.READY:this.videoState.startTransitionTo(x.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case x.STOPPED:this.videoState.startTransitionTo(x.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case x.PLAYING:this.videoState.startTransitionTo(x.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case x.PAUSED:break;case x.READY:this.videoState.startTransitionTo(x.PAUSED),this.videoState.setState(x.PAUSED);break;case x.STOPPED:this.videoState.startTransitionTo(x.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(Fb(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(Hb)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===B.Applying||Math.abs(l-n)>Ub)&&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<jb&&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),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(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(x.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:B.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===x.PAUSED||e===x.PLAYING)&&(this.videoState.setState(x.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)===x.PLAYING||e===x.PAUSED)&&(this.videoState.setState(x.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===x.READY&&this.videoState.setState(x.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()!==x.STOPPED&&this.videoState.setState(x.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=s[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=Ue(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===B.Applying||s.state===B.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(po).subscribe(()=>n(`timeout(${po})`)))});$s(Promise.race([t,s]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},r=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${r}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:a.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:r})}),()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var Yb=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)},qb=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,s=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,b;const y=gi(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in y||"x-playback-duration-millis"in y){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),g=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=g!=null?g:v*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const S=(m=y["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,$=(b={1:!0,0:!1}[y["x-reused"]])!==null&&b!==void 0?b:void 0;s.next(S),r.next($)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...b){return d(this),p(...b)},f.progress=function(...b){return u(this),m(...b)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},qt=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},zb=i=>i.extend("RequestModifier",()=>({modifyRequestURL:qt}),!0),Wb=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 Ie=(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},Pt=(i,e,t)=>Ie(e,()=>i.loop,s=>{a.isNonNullable(s)&&(i.loop=s)},{onError:t}),Je=(i,e,t,s)=>Ie(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}),lt=(i,e,t,s)=>Ie(e,()=>i.playbackRate,r=>{a.isNonNullable(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Qb=i=>["__",i.language,i.label].join("|"),Kb=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.label===r};class He{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(Ie(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{a.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>a.isNonNullable(n)&&a.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(a.map(n=>n.filter(({type:o})=>o==="internal"))),onError:r})),this.subscription.add(Ie(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(Ie(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(Ie(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),a.filterChanged((s,r)=>s.length===r.length&&s.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),a.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),a.filterChanged()).subscribe(this.current$));const t=s=>{var r,n;return this.applyCueSettings((n=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(s=>{var r,n;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(He.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:s}=e,r=e.id?e.id:Qb(e),n=this.externalTracks.has(r),o=r.includes("auto");return n?{id:r,type:"external",isAuto:o,language:t,label:s,url:this.externalTracks.get(r).url}:{id:r,type:"internal",isAuto:o,language:t,label:s,url:this.internalTracks.get(r).url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){this.externalTracks.size===0&&(e.filter(({id:t})=>!this.internalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.internalTracks).filter(([t])=>!e.find(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)&&Kb(t,e)?t.mode="showing":t.mode="disabled"}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Na=i=>{i.removeAttribute("src"),i.load()},Jb=i=>{try{i.pause(),i.playbackRate=0,Na(i),i.remove()}catch(e){console.error(e)}};class Xb{constructor(){this.attribute="data-pool-reused"}get(e){return e.hasAttribute(this.attribute)}set(e,t){e.toggleAttribute(this.attribute,t)}delete(e){e.removeAttribute(this.attribute)}}const sa=window.WeakMap?new WeakMap:new Xb,Xe=i=>{let e=i.querySelector("video");const t=!!e;return e?Na(e):(e=document.createElement("video"),i.appendChild(e)),sa.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ze=i=>{const e=sa.get(i);sa.delete(i),e?Na(i):Jb(i)};class ks{constructor(){this.pausedTime=0,this.streamOffset=0,this.pauseTimestamp=0}getTotalPausedTime(){return this.pausedTime+this.getCurrentPausedTime()}getCurrentPausedTime(){return this.pauseTimestamp>0?Date.now()-this.pauseTimestamp:0}getStreamOffset(){return this.streamOffset}getTotalOffset(){return this.getTotalPausedTime()+this.streamOffset}pause(){this.pauseTimestamp===0&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(e,t=!1){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0,t&&this.pause()}}const ou=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},mo=i=>{const e=ou(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Zb=i=>{const e=ou(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},ra=3;class eS{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<ra&&(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||ra))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 lu=(i,e,t=ra)=>{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 et=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(()=>lu(i.buffered,i.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>!!(i.error||i.played.length)),a.map(()=>{var v;const g=i.error;return{id:g?`MediaError#${g.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:g?g.message:"Error event from HTML video element",thrown:(v=i.error)!==null&&v!==void 0?v:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(v=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(v)&&p>=i.duration-f&&v<=f&&h.next(p),p=v});const m=a.fromEvent(i,"enterpictureinpicture"),b=a.fromEvent(i,"leavepictureinpicture"),y=new a.ValueSubject(Zb(i));m.subscribe(()=>y.next(!0)),b.subscribe(()=>y.next(!1));const S=new a.ValueSubject(mo(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>mo(i))).subscribe(S),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:y,inFullscreen$:S}},xa=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var tS=Ne,iS=Ss,sS=ya,rS=ga;tS({target:"Array",proto:!0},{at:function(e){var t=iS(this),s=sS(t),r=rS(e),n=r>=0?r:s+r;return n<0||n>=s?void 0:t[n]}});var aS=Ia,nS=aS("Array","at"),oS=nS,lS=oS,uS=lS,dS=uS,Ge=hs(dS);let La=!1,qe={};const cS=i=>{La=i},hS=()=>{qe={}},fS=i=>{i(qe)},Hi=(i,e)=>{var t;La&&(qe.meta=(t=qe.meta)!==null&&t!==void 0?t:{},qe.meta[i]=e)};class Me{constructor(e){this.name=e}next(e){var t,s;if(!La)return;qe.series=(t=qe.series)!==null&&t!==void 0?t:{};const r=(s=qe.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),qe.series[this.name]=r}}const pS=new Me("best_bitrate"),mS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class vS{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Xt=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c})=>{var h,f,p,m;const b=s.usePixelRatio&&(h=window.devicePixelRatio)!==null&&h!==void 0?h:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*s.containerSizeFactor,height:e.height*b*s.containerSizeFactor},S=y&&a.videoSizeToQuality(y),$=s.considerPlaybackRate&&a.isNonNullable(l)?l:1,v=i.filter(P=>!a.isInvariantQuality(P.quality)).sort((P,I)=>a.isHigher(P.quality,I.quality)?-1:1),g=(f=Ge(v,-1))===null||f===void 0?void 0:f.quality,E=(p=Ge(v,0))===null||p===void 0?void 0:p.quality,w=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&a.isLower(r.max,r.min)||a.isNonNullable(r.min)&&E&&a.isHigher(r.min,E)||a.isNonNullable(r.max)&&g&&a.isLower(r.max,g),N=$*mS(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),C=v.filter(P=>{const I=S?a.isLower(P.quality,S):!0,Y=a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(P.bitrate)?t-n>=P.bitrate*N:!0,Q=s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<s.minBufferToSwitchUp&&a.isHigher(P.quality,d.quality),_=!!c&&a.isHigherOrEqual(P.quality,c),j=w||(a.isNullable(r.max)||a.isLowerOrEqual(P.quality,r.max))&&(a.isNullable(r.min)||a.isHigherOrEqual(P.quality,r.min));return I&&Y&&!Q&&j&&!_})[0];C&&C.bitrate&&pS.next(C.bitrate);const D=(m=C!=null?C:v[Math.ceil((v.length-1)/2)])!==null&&m!==void 0?m:i[0],M=D&&u&&u.history[D.id]&&a.now()-u.history[D.id]<=s.trackCooldown&&(!u.last||D.id!==u.last.id);if(D!=null&&D.id&&u&&!M&&u.recordSelection(D),M&&(u!=null&&u.last)){const P=u.last;return u==null||u.recordSwitch(P),P}return u==null||u.recordSwitch(D),D};var pe=i=>new URL(i).hostname;const bS=300,ns=(i,e=bS)=>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(Ku(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()});class Ps{constructor(){this.onDroopedVideoFramesLimit$=new a.Subject,this.subscription=new a.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new a.Subject,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!a.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(r-n)/r;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),s=a.merge(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>a.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&!!this.video.getVideoPlaybackQuality}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const ii={};var V;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(V||(V={}));const se=(i,e)=>new a.Observable(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class vo{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(V.DOWNLOADING_LIB),this.textTracksManager=new He,this.droppedFramesManager=new Ps,this.videoTracks$=new a.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new ks,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===V.DOWNLOADING_LIB||t===V.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&t!==V.STOPPED&&s!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),s){case exports.PlaybackState.STOPPED:{switch(t){case V.STOPPED:break;case V.PLAYING:case V.PAUSED:case V.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case V.STOPPED:this.prepare();break;case V.PLAYING:case V.PAUSED:case V.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case V.PLAYING:break;case V.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case V.READY:this.play();break;case V.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case V.PLAYING:this.pause(),this.liveOffset.pause();break;case V.PAUSED:break;case V.READY:this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case V.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(s)}},this.video=Xe(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(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);$s(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(ii.MediaPlayer=r.MediaPlayer,ii.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(ii.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(ii.Debug,"dashjs not loaded"),this.player=ii.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?xa(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Wb(this.player),Yb(this.player),this.params.tuning.requestQuick&&zb(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(V.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=v=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},r=(v,g)=>this.subscription.add(v.subscribe(g,s));r(ns(this.video),this.elementSize$),r(se(this.player,"error").pipe(a.map(v=>{const g=typeof v.error=="object"?v.error.code:v.error,E=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${g}`,message:E}})),e.error$),r(se(this.player,"playbackError").pipe(a.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=se(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({newQuality:v})=>{var g;return(g=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===v))===null||g===void 0?void 0:g.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:v})=>v===V.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Ie(t.videoTrack,()=>{var v,g;const E=this.player.getQualityFor("video");return(g=(v=this.videoTracks$.getValue().find(({bitrateInfo:w})=>w.qualityIndex===E))===null||v===void 0?void 0:v.track)===null||g===void 0?void 0:g.id},v=>{var g;if(a.isNullable(v))return;const E=(g=this.videoTracks$.getValue().find(({track:w})=>w.id===v))===null||g===void 0?void 0:g.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n.pipe(a.map(v=>v==null?void 0:v.id)),onError:s}))},s)),this.subscription.add(Ie(t.autoVideoTrackSwitching,()=>{var v,g,E;return(E=(g=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||g===void 0?void 0:g.autoSwitchBitrate)===null||E===void 0?void 0:E.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:s})),r(se(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:v})=>v==="video"),a.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),r(se(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:g}})=>{var E,w;const N=this.player.getDashMetrics(),U=N.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),C=(E=N.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,D=(w={1:!0,0:!1}[U])!==null&&w!==void 0?w:void 0;this.params.output.httpConnectionType$.next(C),this.params.output.httpConnectionReused$.next(D),e.hostname$.next(pe(g))}),r(se(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:g,availableFrom:E}}})=>{this.isLive$.next(g),this.availableFrom$.next(E.getTime()),g||e.duration$.next(v);const w=[],N=this.player.getQualityFor("video");let U;for(const C of this.player.getBitrateInfoListFor("video")){const D=C.qualityIndex.toString(10),M=a.videoSizeToQuality(C),P=C.bitrate/1e3,I={width:C.width,height:C.height},Y=this.frameRatesByFrameHeight[C.height];if(M){const Q={id:D,quality:M,bitrate:P,size:I,fps:Y};w.push({track:Q,bitrateInfo:C}),C.qualityIndex===N&&(U=Q)}}this.videoTracks$.next(w),e.availableVideoTracks$.next(w.map(({track:C})=>C)),U&&e.currentVideoTrack$.next(U),this.videoState.setState(V.STREAM_INITIALIZED),this.videoState.startTransitionTo(V.READY)}),r(se(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const g=v.requestEndDate.getTime()-v.firstByteDate.getTime(),E=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,g)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),g=Xt(this.videoTracks$.getValue().map(({track:N})=>N),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}),E=t.autoVideoTrackLimits.getTransition();E&&e.autoVideoTrackLimits$.next(E.to);const w=this.videoTracks$.getValue().find(({track:N})=>N===g);w!=null&&w.bitrateInfo&&this.player.setQualityFor("video",w==null?void 0:w.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:v})=>v),a.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=se(this.player,"playbackTimeUpdated").pipe(a.map(({time:v})=>v!=null?v:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:g})=>this.params.output.liveTime$.next(v+g*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(()=>lu(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(se(this.player,"playbackPlaying"),()=>{this.videoState.setState(V.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),r(se(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(V.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(se(this.player,"playbackPaused"),()=>{this.videoState.setState(V.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),r(se(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===V.READY&&this.videoState.setState(V.READY)}),r(this.isLive$,e.isLive$),r(ns(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=qb(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(v=>v<60))}),({isLive:v,isShort:g})=>{const E=!v&&g;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),r(o.pipe(a.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(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)),r(se(this.player,"manifestLoaded"),v=>{var g,E,w,N,U,C,D;if(!((E=(g=v.data)===null||g===void 0?void 0:g.Period)===null||E===void 0)&&E.AdaptationSet){const M=[];for(const P of(N=(w=v.data)===null||w===void 0?void 0:w.Period)===null||N===void 0?void 0:N.AdaptationSet)if(P.contentType==="text"){const I=(U=P.Representation)===null||U===void 0?void 0:U.id,Y=new URL((C=P.Representation)===null||C===void 0?void 0:C.BaseURL,(D=v.data)===null||D===void 0?void 0:D.baseUri).toString(),Q="internal",_=P.lang;M.push({id:I,url:Y,type:Q,language:_})}t.internalTextTracks.startTransitionTo(M)}}),this.subscription.add(Pt(this.video,t.isLooped,s));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:b,inFullscreen$:y,pause$:S,playing$:$}=et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:$,pause$:S,tracks$:this.videoTracks$.pipe(a.map(v=>v.map(({track:g})=>g)))}),this.subscription.add(Je(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(lt(this.video,t.playbackRate,m,s)),this.subscription.add(b.subscribe(e.inPiP$)),this.subscription.add(y.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(V.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(V.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Ue(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ne.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(V.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(V.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}Ze(this.video),this.params.output.element$.next(void 0)}}var Ei=i=>{switch(i){case"mobile":return a.VideoQuality.Q_144P;case"lowest":return a.VideoQuality.Q_240P;case"low":return a.VideoQuality.Q_360P;case"sd":case"medium":return a.VideoQuality.Q_480P;case"hd":case"high":return a.VideoQuality.Q_720P;case"fullhd":case"full":return a.VideoQuality.Q_1080P;case"quadhd":case"quad":return a.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return a.VideoQuality.Q_2160P}};const bo=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var ut=i=>q(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!bo(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return bo(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function de(){return a.now()}function uu(i){return de()-i}function So(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 SS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function ts(i,e,t,s){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,b=2e3,y=()=>{if(d)return;a.assertNonNullable(c);const P=uu(c);let I;if(P<b){I=b-P,setTimeout(y,I);return}b*=2,b>m&&(b=m),o&&o.abort(),o=new r,w()};const S=P=>(n=P,M),$=P=>(h=P,M),v=()=>(p="json",M),g=()=>{if(!d){if(--u>=0){y(),s&&s();return}d=!0,h&&h(),t&&t()}},E=P=>(f=P,M),w=()=>{c=de(),o=new r,o.open("get",i);let P=0,I,Y=0;const Q=()=>(a.assertNonNullable(c),Math.max(c,Math.max(I||0,Y||0)));if(n&&o.addEventListener("progress",_=>{const j=de();n.updateChunk&&_.loaded>P&&(n.updateChunk(Q(),_.loaded-P),P=_.loaded,I=j)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>g())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const _=o.status;if(_>=200&&_<300){if(o.response.byteLength&&n){const j=o.response.byteLength-P;j&&n.updateChunk&&n.updateChunk(Q(),j)}h&&h(),o&&e(o.response)}else g()}),o.addEventListener("error",()=>{g()}),f){const _=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Y=de(),o.removeEventListener("readystatechange",_))};o.addEventListener("readystatechange",_)}return o.responseType=p,o.send(),M},M={withBitrateReporting:S,withParallel:E,withJSONResponse:v,withRetryCount:P=>(u=P,M),withRetryInterval:(P,I)=>(a.isNonNullable(P)&&(b=P),a.isNonNullable(I)&&(m=I),M),withTimeout:P=>(l=P,M),withFinally:$,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return M}const gS=100,yS=2e3,TS=500;let ES=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-TS;if(t-e>yS){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>gS&&(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 $S{constructor(e,t,s,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=de(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=de()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=ts(t,n,()=>r("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=de()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=de();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=r,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Gi=1e4,Yi=3,kS=300,PS=2e3,wS=6e4,AS=10,_S=1,CS=500;class RS{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 ES(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=So(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=So(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!r||n.bitrate>r.bitrate)&&(r=n):(!s||s.bitrate>n.bitrate)&&(s=n));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{SS(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 $S(Yi,Gi,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 g=n&&(!c||c===this.rep);return g||t("Not running!"),g},f=(g,E,w)=>{d&&d.abort(),d=ts(this.urlResolver.resolve(g,!1),E,w,()=>this._retryCallback()).withTimeout(Gi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Yi).withFinally(()=>{d=null}).send()},p=(g,E,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(g,!1),E,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=g=>{const E=s.playbackRate;s.playbackRate!==g&&(t(`Playback rate switch: ${E}=>${g}`),s.playbackRate=g)},b=g=>{this.lowLatency=g,t(`lowLatency changed to ${g}`),y()},y=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let g=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const w=de()-1e4;let N=0;for(let C=0;C<this.bufferStates.length;C++){const D=this.bufferStates[C];g=Math.min(g,D.buf),D.ts<w&&N++}this.bufferStates.splice(0,N),t(`update playback rate; minBuffer=${g} drop=${N} jitter=${this.sourceJitter}`);let U=g-_S;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?m(1.15):U>1?m(1.1):U>.3?m(1.05):m(1)}},S=g=>{let E;const w=()=>E&&E.start?E.start.length:0,N=_=>E.start[_]/1e3,U=_=>E.dur[_]/1e3,C=_=>E.fragIndex+_,D=(_,j)=>({chunkIdx:C(_),startTS:N(_),dur:U(_),discontinuity:j}),M=()=>{let _=0;if(E&&E.dur){let j=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,K=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=j;this.sourceJitter>1&&(te+=this.sourceJitter-1);let re=E.dur.length-1;for(;re>=0&&(te-=E.dur[re],!(te<=0));--re);_=Math.min(re,E.dur.length-1-K),_=Math.max(_,0)}return D(_,!0)},P=_=>{const j=w();if(!(j<=0)){if(a.isNonNullable(_)){for(let K=0;K<j;K++)if(N(K)>_)return D(K)}return M()}},I=_=>{const j=w(),K=_?_.chunkIdx+1:0,te=K-E.fragIndex;if(!(j<=0)){if(!_||te<0||te-j>AS)return t(`Resync: offset=${te} bChunks=${j} chunk=`+JSON.stringify(_)),M();if(!(te>=j))return D(K-E.fragIndex,!1)}},Y=(_,j,K)=>{u&&u.abort(),u=ts(this.urlResolver.resolve(_,!0,this.lowLatency),j,K,()=>this._retryCallback()).withTimeout(Gi).withRetryCount(Yi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(_,j)=>{Y(g,K=>{if(!h())return;E=K;const te=!!E.lowLatency;te!==this.lowLatency&&b(te);let re=0;for(let me=0;me<E.dur.length;++me)re+=E.dur[me];re>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(re/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,_(P(j))},()=>this._handleNetworkError())},nextChunk:I}},$=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:g=>{const{videoElement:E,logger:w}=this.params;let N=S(e.jidxUrl),U,C,D,M,P=0,I,Y,Q;const _=()=>{I&&(clearTimeout(I),I=void 0);const H=Math.max(CS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),he=P+H,ye=de(),ve=Math.min(1e4,he-ye);P=ye;const Te=()=>{u||h()&&N.seek(()=>{h()&&(P=de(),j(),_())})};ve>0?I=window.setTimeout(()=>{this.paused?_():Te()},ve):Te()},j=()=>{let H;for(;H=N.nextChunk(M);)M=H,xe(H);const he=N.nextChunk(D);if(he){if(D&&he.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?_():($(),this._initPlayerWith(e));return}me(he)}else _()},K=(H,he)=>{if(!h()||!this.sourceBuffer)return;let ye,ve,Te;const wt=ct=>{window.setTimeout(()=>{h()&&K(H,he)},ct)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),wt(100);else{const ct=de(),At=E.currentTime;!this.paused&&E.buffered.length>1&&Y===At&&ct-Q>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),Y!==At&&(Y=At,Q=ct);const _t=this._getBufferSizeSec();if(_t>30)w(`Buffered ${_t} seconds; delaying appendBuffer`),wt(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:ct,buf:_t}),y(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),he&&he()}catch($i){if($i.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),Te=this.sourceBuffer.buffered.length,Te!==0&&(ye=this.sourceBuffer.buffered.start(0),ve=At,ve-ye>4&&this.sourceBuffer.remove(ye,ve-3)),wt(1e3);else throw $i}}},te=()=>{C&&U&&(w([`Appending chunk, sz=${C.byteLength}:`,JSON.stringify(D)]),K(C,function(){C=null,j()}))},re=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),me=H=>{h()&&p(re(H),(he,ye)=>{if(h()){if(ye/=1e3,C=he,D=H,o=H.startTS,ye){const ve=Math.min(10,H.dur/ye);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}te()}},()=>this._handleNetworkError())},xe=H=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(re(H),!1)))},it=H=>{h()&&(e.cachedHeader=H,K(H,()=>{U=!0,te()}))};n=!0,N.seek(H=>{if(h()){if(P=de(),!H){_();return}M=H,!a.isNullable(g)||H.startTS>g?me(H):(D=H,j())}},g),e.cachedHeader?it(e.cachedHeader):f(e.headerUrl,it,()=>this._handleNetworkError())},stop:$,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const m=de();if(this.chunkRateEstimator.addInterval(f,m,p)){const y=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:y}),!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&&uu(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=de();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=ts(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Gi).withRetryCount(Yi).withRetryInterval(kS,PS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;ut(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement: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))},wS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var O;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(O||(O={}));const DS=[O.PAUSED,O.PLAYING,O.READY],IS=[O.PAUSED,O.PLAYING,O.READY];class NS{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(O.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new He,this.droppedFramesManager=new Ps,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ks,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Ei(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,b=Object.assign({},h.video);if(!p)continue;const y={id:f,quality:p,bitrate:m,size:b};c.push({track:y,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)===O.MANIFEST_READY&&this.videoState.setState(O.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){r!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(O.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(IS.includes(r)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===B.Requested&&DS.includes(r)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(r){case O.STOPPED:this.videoState.startTransitionTo(O.MANIFEST_READY),this.dash.attachSource(Ue(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(O.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(O.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return a.assertNever(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=Xe(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=et(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(a.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===O.READY&&this.videoState.setState(O.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(O.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(O.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(Pt(this.video,this.params.desiredState.isLooped,t)).add(Je(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(lt(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const n=r&&a.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var n;switch(r.to){case O.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case O.MANIFEST_READY:case O.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 O.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case O.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}createLiveDashPlayer(){const e=new RS({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=Xt(l.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}))===null||n===void 0?void 0:n.id,h=this.params.desiredState.videoTrack.getTransition(),f=this.params.desiredState.videoTrack.getState(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((h&&c||c!==f)&&this.setVideoTrack(c),p&&this.setAutoQuality(u),h||p||c!==f){const m=(o=l.find(({track:b})=>b.id===c))===null||o===void 0?void 0:o.representation;a.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e))===null||t===void 0?void 0:t.representation;a.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===O.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ue(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}}var du=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}},rt=(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 xS=i=>{const e=document.createElement("a");return e.href=i,e.origin},LS=i=>{const e=document.createElement("a");return e.href=i,e.host};class cu{constructor(e,t=[],s,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,n,o,l,d,u;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=gi(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(LS(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class os{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=b=>{r(os._str2ua(b.substr(d))),d=b.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=qt(m)),this._lastXhr=new cu(m,e.failoverHosts,b=>{this._lastXhr=void 0,p(b);const y=Date.now()-u;this._params.onBandwidthChange({size:b.length,duration:y,speed:8*b.length/(y/1e3)}),this._onDashCallback("loading",{size:b.length,done:!0}),n==null||n()},b=>{if(b.length-d>l&&p(b),h===0){h=Date.now();return}f=b.length-c;const y=Date.now()-h;f>=100*1024&&y>=1e3&&(this._params.onBandwidthChange({size:f,duration:y,speed:8*f/(y/1e3)}),f=0,c=b.length,h=Date.now()),this._onDashCallback("loading",{size:b.length,done:!1})},o,(b,y,S)=>this._params.onError(b,y,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 OS{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=qt(s)),new cu(s,t,r=>{this.attachManifest(r,t,xS(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,m,b,y,S,$,v,g,E,w,N,U,C,D,M,P;const I=u.getElementsByTagName("SegmentBase")[0],Y=I&&o(I,"indexRange").split("-"),Q=I&&I.getElementsByTagName("Initialization")[0],_=Q&&o(Q,"range").split("-");if(!_||!Y){const xe=u.parentElement;if((xe==null?void 0:xe.getAttribute("contentType"))==="text"){const it=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,H=(s?s+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),he=(b=xe.getAttribute("lang"))!==null&&b!==void 0?b:void 0;H&&d.push({id:it,url:H,language:he})}return}const j=.1,K=Number((y=u.attributes.getNamedItem("bandwidth"))===null||y===void 0?void 0:y.value),te=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let re;const me=($=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&$!==void 0?$:void 0;re=me?xa(me):void 0,l.push({width:Number((v=u.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((g=u.attributes.getNamedItem("height"))===null||g===void 0?void 0:g.value),bandwidth:K,baseURL:te,failoverHosts:t,indexFrom:Number(Y[0]),indexTo:Number(Y[1]),initFrom:Number(_[0]),initTo:Number(_[1]),codecs:(w=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&w!==void 0?w:void 0,mimeType:(U=(N=u.attributes.getNamedItem("mimeType"))===null||N===void 0?void 0:N.value)!==null&&U!==void 0?U:void 0,fps:re,bufferSize:j*K/8,bufferLength:j,name:(D=(C=u.attributes.getNamedItem("okQuality"))===null||C===void 0?void 0:C.value)!==null&&D!==void 0?D:void 0,id:(P=(M=u.attributes.getNamedItem("id"))===null||M===void 0?void 0:M.value)!==null&&P!==void 0?P:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),m=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,d=m}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new os({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||l(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<s.to+n){const o=this._findRef(r.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<s.length;n++){const o=s[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=s[s.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var F;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(F||(F={}));const BS=[F.PAUSED,F.PLAYING];class MS{constructor(e){this.videoState=new X(F.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new He,this.droppedFramesManager=new Ps,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,n,o;const l=[];for(const d of t){const u=(n=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Ei(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(s==null?void 0:s.length)>0){const d=[];for(const u of s){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(F.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!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(F.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!s)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===B.Requested&&BS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_LOADED),this.prepare();return;case F.MANIFEST_LOADED:this.videoState.startTransitionTo(F.INITIAL_REPRESENTATION_SELECTED);return;case F.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(F.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case F.METADATA_LOADED:this.videoState.startTransitionTo(F.READY),this.dash.updateRefsForCurrentTime();return;case F.READY:r===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed());return;case F.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(F.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case F.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=Xe(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(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new eS(this.video),this.dash=new OS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=et(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===F.PLAYING||this.videoState.getState()===F.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Pt(this.video,t.isLooped,s)),this.subscription.add(Je(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(lt(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(a.map(l=>l.map(({track:d})=>d)))}),o(ns(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===F.READY&&this.videoState.setState(F.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(F.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(F.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),p=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),b=this.elementSize$.getValue(),y=r();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!y&&a.isNonNullable(p))S=p;else{const $=rt(this.video.buffered,this.video.currentTime*1e3),v=y?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,g=Math.min($/v,1);S=(d=Xt(h.map(({track:w})=>w),{container:b,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:g,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:w})=>w===c))===null||l===void 0?void 0:l.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}))===null||d===void 0?void 0:d.id;const E=t.autoVideoTrackLimits.getTransition();E&&e.autoVideoTrackLimits$.next(E.to)}return a.isNonNullable(S)?(u=h.find(({track:$})=>$.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===F.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(F.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=rt(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(pe(l.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=du(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(F.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}var oe;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(oe||(oe={}));var Ee;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.ActiveLive=1]="ActiveLive",i[i.LiveWithTargetOffset=2]="LiveWithTargetOffset",i[i.LiveForwardBuffering=3]="LiveForwardBuffering",i[i.None=4]="None"})(Ee||(Ee={}));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 ke;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(ke||(ke={}));var L;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(L||(L={}));var zt;(function(i){i.MP4="mp4",i.WEBM="webm"})(zt||(zt={}));var us;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(us||(us={}));var Z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Z||(Z={}));class go{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 hu extends go{constructor(){super(),this.listeners||go.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 fu=class{constructor(){Object.defineProperty(this,"signal",{value:new hu,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&&(fu.prototype[Symbol.toStringTag]="AbortController",hu.prototype[Symbol.toStringTag]="AbortSignal");function pu(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 VS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!pu({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const ws=pu({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),mu=ws?VS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,ci=ws?mu.fetch:window.fetch;ws?mu.Request:window.Request;const Yt=ws?fu:window.AbortController;var aa=(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 FS=(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)},US=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",yo=US?FS:window.requestIdleCallback;var gr,yr;let vu=!1;try{vu=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((yr=(gr=navigator.userAgent.match(/Version\/(\d+)/))===null||gr===void 0?void 0:gr[1])!==null&&yr!==void 0?yr:"",10)<16}catch(i){console.error(i)}class jS{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 q(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 q(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 q(this,void 0,void 0,function*(){return new Promise(t=>{let s;vu&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}var To=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};class Ae{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 bu extends Ae{}class HS extends Ae{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 GS extends Ae{parseChildrenBoxes(){return dt(this.content)}}class YS extends Ae{parseChildrenBoxes(){return dt(this.content)}}class qS extends Ae{constructor(e){super(e),this.data=this.content}}class tt extends Ae{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class zS extends tt{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 WS extends Ae{parseChildrenBoxes(){return dt(this.content)}}class QS extends Ae{parseChildrenBoxes(){return dt(this.content)}}var yt;(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"})(yt||(yt={}));class KS extends tt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=yt.MONOSCOPIC;break;case 1:this.stereoMode=yt.TOP_BOTTOM;break;case 2:this.stereoMode=yt.LEFT_RIGHT;break;case 3:this.stereoMode=yt.STEREO_CUSTOM;break;case 4:this.stereoMode=yt.RIGHT_LEFT;break}this.cursor+=1}}class JS extends tt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class XS extends tt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class ZS extends Ae{parseChildrenBoxes(){return dt(this.content)}}class eg extends tt{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 tg extends Ae{parseChildrenBoxes(){return dt(this.content)}}class ig extends Ae{parseChildrenBoxes(){return dt(this.content)}}class sg extends tt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class rg extends Ae{parseChildrenBoxes(){return dt(this.content)}}class ag extends tt{constructor(e){super(e),this.trackId=this.readUint32(),this.flags&1&&(this.baseDataOffset=this.readUint64()),this.flags&2&&(this.sampleDescriptionIndex=this.readUint32()),this.flags&8&&(this.defaultSampleDuration=this.readUint32()),this.flags&16&&(this.defaultSampleSize=this.readUint32()),this.flags&32&&(this.defaultSampleFlags=this.readUint32())}}class ng extends tt{get baseMediaDecodeTime(){return this.version===1?this.baseMediaDecodeTime64:this.baseMediaDecodeTime32}constructor(e){super(e),this.baseMediaDecodeTime32=0,this.baseMediaDecodeTime64=BigInt(0),this.version===1?this.baseMediaDecodeTime64=this.readUint64():this.baseMediaDecodeTime32=this.readUint32()}}class og extends tt{constructor(e){super(e),this.sampleDuration=[],this.sampleSize=[],this.sampleFlags=[],this.sampleCompositionTimeOffset=[],this.optionalFields=0,this.sampleCount=this.readUint32(),this.flags&1&&(this.dataOffset=this.readUint32()),this.flags&4&&(this.firstSampleFlags=this.readUint32());for(let t=0;t<this.sampleCount;t++)this.flags&256&&this.sampleDuration.push(this.readUint32()),this.flags&512&&this.sampleSize.push(this.readUint32()),this.flags&1024&&this.sampleFlags.push(this.readUint32()),this.flags&2048&&this.sampleCompositionTimeOffset.push(this.readUint32())}}const lg={ftyp:HS,moov:GS,moof:YS,mdat:qS,sidx:zS,trak:WS,mdia:ZS,mfhd:sg,tkhd:eg,traf:rg,tfhd:ag,tfdt:ng,trun:og,minf:tg,sv3d:QS,st3d:KS,prhd:JS,proj:ig,equi:XS,unknown:bu};class ug{createBox(e,t){const s=lg[e];return s?new s(t):new bu(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return As.createBox(s,new DataView(e.buffer,e.byteOffset))}}const As=new ug;function ai(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(o=>o.charCodeAt(0));let r=i.byteOffset,n=[];for(;r<t.byteLength;){if(t[r]===s[n.length]?n.push(t[r]):n=[],n.length===4){const l=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+l>i.buffer.byteLength?null:As.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function na(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=ai(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function dt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=As.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const dg=new TextDecoder("ascii"),cg=i=>dg.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",hg=i=>{const e=As.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:L.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},fg=i=>{const e=na(i,"mdat"),t=na(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],n=s.source.byteOffset,l=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,n,l)},pg=(i,e)=>{const t=na(i,"traf"),s=t[t.length-1].children.find(d=>d.type==="tfhd"),r=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,u)=>d+u,0):o=s.defaultSampleDuration*n.sampleCount,(Number(r.baseMediaDecodeTime)+o)/e*1e3},mg=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:us.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ai(i,"sv3d")){e.is3dVideo=!0;const s=ai(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=ai(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=ai(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},vg={validateData:cg,parseInit:mg,getIndexRange:()=>{},parseSegments:hg,parseFeedableSegmentChunk:fg,getSegmentEndTime:pg};var T;(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"})(T||(T={}));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 Eo={[T.EBML]:{type:A.Master},[T.EBMLVersion]:{type:A.UnsignedInteger},[T.EBMLReadVersion]:{type:A.UnsignedInteger},[T.EBMLMaxIDLength]:{type:A.UnsignedInteger},[T.EBMLMaxSizeLength]:{type:A.UnsignedInteger},[T.DocType]:{type:A.String},[T.DocTypeVersion]:{type:A.UnsignedInteger},[T.DocTypeReadVersion]:{type:A.UnsignedInteger},[T.Void]:{type:A.Binary},[T.Segment]:{type:A.Master},[T.SeekHead]:{type:A.Master},[T.Seek]:{type:A.Master},[T.SeekID]:{type:A.Binary},[T.SeekPosition]:{type:A.UnsignedInteger},[T.Info]:{type:A.Master},[T.TimestampScale]:{type:A.UnsignedInteger},[T.Duration]:{type:A.Float},[T.Tracks]:{type:A.Master},[T.TrackEntry]:{type:A.Master},[T.Video]:{type:A.Master},[T.Projection]:{type:A.Master},[T.ProjectionType]:{type:A.UnsignedInteger},[T.ProjectionPrivate]:{type:A.Master},[T.Chapters]:{type:A.Master},[T.Cluster]:{type:A.Master},[T.Timestamp]:{type:A.UnsignedInteger},[T.SilentTracks]:{type:A.Master},[T.SilentTrackNumber]:{type:A.UnsignedInteger},[T.Position]:{type:A.UnsignedInteger},[T.PrevSize]:{type:A.UnsignedInteger},[T.SimpleBlock]:{type:A.Binary},[T.BlockGroup]:{type:A.Master},[T.EncryptedBlock]:{type:A.Binary},[T.Attachments]:{type:A.Master},[T.Tags]:{type:A.Master},[T.Cues]:{type:A.Master},[T.CuePoint]:{type:A.Master},[T.CueTime]:{type:A.UnsignedInteger},[T.CueTrackPositions]:{type:A.Master},[T.CueTrack]:{type:A.UnsignedInteger},[T.CueClusterPosition]:{type:A.UnsignedInteger},[T.CueRelativePosition]:{type:A.UnsignedInteger},[T.CueDuration]:{type:A.UnsignedInteger},[T.CueBlockNumber]:{type:A.UnsignedInteger},[T.CueCodecState]:{type:A.UnsignedInteger},[T.CueReference]:{type:A.Master},[T.CueRefTime]:{type:A.UnsignedInteger}},Su=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 Eo,n=r?Eo[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 p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},ds=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},Ve=(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)}},Wt=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Su(s);if(!e(r))return;r.type===A.Master&&Wt(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},bg=i=>{if(i.getUint32(0)!==T.EBML)return!1;let e,t,s;const r=Su(i);return Wt(r.value,({tag:n,type:o,value:l})=>(n===T.EBMLReadVersion?e=Ve(l,o):n===T.DocType?t=Ve(l,o):n===T.DocTypeReadVersion&&(s=Ve(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},gu=[T.Info,T.SeekHead,T.Tracks,T.TrackEntry,T.Video,T.Projection,T.ProjectionType,T.ProjectionPrivate,T.Chapters,T.Cluster,T.Cues,T.Attachments,T.Tags],Sg=[T.Timestamp,T.SilentTracks,T.SilentTrackNumber,T.Position,T.PrevSize,T.SimpleBlock,T.BlockGroup,T.EncryptedBlock],gg=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Wt(i,({tag:f,type:p,value:m,valueSize:b})=>{if(f===T.SeekID){const y=Ve(m,p);u=ds(y)}else f!==T.SeekPosition&&(u=void 0);return f===T.Segment?(e=m.byteOffset,t=m.byteOffset+b):f===T.Info?n=!0:f===T.SeekHead?o=!0:f===T.TimestampScale?s=Ve(m,p):f===T.Duration?r=Ve(m,p):f===T.SeekPosition&&u===T.Cues?d=Ve(m,p):f===T.Tracks?Wt(m,({tag:y,type:S,value:$})=>y===T.ProjectionType?(c=Ve($,S)===1,!1):!0):n&&o&&gu.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}}}},yg=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Tg=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Wt(i,({tag:l,type:d,value:u})=>{switch(l){case T.Cues:t=!0;break;case T.CuePoint:o&&r(o)&&n.push(o),o={};break;case T.CueTime:o&&(o.time=Ve(u,d));break;case T.CueTrackPositions:break;case T.CueClusterPosition:o&&(o.position=Ve(u,d));break;default:t&&gu.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:L.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}}})},Eg=i=>{let e=0,t=!1;try{Wt(i,s=>s.tag===T.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=[T.SimpleBlock,T.BlockGroup,T.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},$g={validateData:bg,parseInit:gg,getIndexRange:yg,parseSegments:Tg,parseFeedableSegmentChunk:Eg};var kg=Qe,Pg=fi,wg=ce,Ag=wg("match"),_g=function(i){var e;return kg(i)&&((e=i[Ag])!==void 0?!!e:Pg(i)=="RegExp")},Cg=Si,Rg=String,Dg=function(i){if(Cg(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Rg(i)},Ig=Ke,Ng=function(){var i=Ig(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},xg=ge,Lg=je,Og=ps,Bg=Ng,$o=RegExp.prototype,Mg=function(i){var e=i.flags;return e===void 0&&!("flags"in $o)&&!Lg(i,"flags")&&Og($o,i)?xg(Bg,i):e},Oa=we,Vg=Ss,Fg=Math.floor,Tr=Oa("".charAt),Ug=Oa("".replace),Er=Oa("".slice),jg=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Hg=/\$([$&'`]|\d{1,2})/g,Gg=function(i,e,t,s,r,n){var o=t+i.length,l=s.length,d=Hg;return r!==void 0&&(r=Vg(r),d=jg),Ug(n,d,function(u,c){var h;switch(Tr(c,0)){case"$":return"$";case"&":return i;case"`":return Er(e,0,t);case"'":return Er(e,o);case"<":h=r[Er(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Fg(f/10);return p===0?u:p<=l?s[p-1]===void 0?Tr(c,1):s[p-1]+Tr(c,1):u}h=s[f-1]}return h===void 0?"":h})},Yg=Ne,qg=ge,Ba=we,ko=da,zg=ae,Wg=pi,Qg=_g,Ot=Dg,Kg=bs,Jg=Mg,Xg=Gg,Zg=ce,ey=Zg("replace"),ty=TypeError,yu=Ba("".indexOf),iy=Ba("".replace),Po=Ba("".slice),sy=Math.max,wo=function(i,e,t){return t>i.length?-1:e===""?t:yu(i,e,t)};Yg({target:"String",proto:!0},{replaceAll:function(e,t){var s=ko(this),r,n,o,l,d,u,c,h,f,p=0,m=0,b="";if(!Wg(e)){if(r=Qg(e),r&&(n=Ot(ko(Jg(e))),!~yu(n,"g")))throw ty("`.replaceAll` does not allow non-global regexes");if(o=Kg(e,ey),o)return qg(o,e,s,t);if(r)return iy(Ot(s),e,t)}for(l=Ot(s),d=Ot(e),u=zg(t),u||(t=Ot(t)),c=d.length,h=sy(1,c),p=wo(l,d,0);p!==-1;)f=u?Ot(t(d,p,l)):Xg(d,l,p,[],void 0,t),b+=Po(l,m,p)+f,m=p+c,p=wo(l,d,p+h);return m<l.length&&(b+=Po(l,m)),b}});var ry=Ia,ay=ry("String","replaceAll"),ny=ay,oy=ny,ly=oy,uy=ly,Ao=hs(uy);const _o=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},Vt=(i,e)=>{let t=i;t=Ao(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=Ao(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},dy=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,p,m,b,y,S,$,v,g,E,w,N,U,C,D,M,P,I,Y,Q,_,j,K,te,re,me,xe,it,H;const ye=new DOMParser().parseFromString(i,"application/xml"),ve={video:[],audio:[],text:[]},Te=ye.children[0],wt=Te.getElementsByTagName("Period")[0],ct=wt.children,At=Te.getAttribute("type")==="dynamic",_t=Te.getAttribute("availabilityStartTime"),$i=_t?new Date(_t).getTime():void 0;let ht;const Va=Te.getAttribute("mediaPresentationDuration"),Fa=wt.getAttribute("duration"),_s=Te.getElementsByTagName("vk:Attrs")[0],Ua=_s==null?void 0:_s.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Va)ht=_o(Va);else if(Fa){const _e=_o(Fa);a.isNonNullable(_e)&&(ht=_e)}else Ua&&(ht=parseInt(Ua,10));let Au=0;const Cs=(s=(t=Te.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],_u=Cs.includes(ls.WEBM_AS_IN_FFMPEG)||Cs.includes(ls.WEBM_AS_IN_SPEC)?zt.WEBM:zt.MP4;for(const _e of ct){const ki=_e.getAttribute("mimeType"),Cu=_e.getAttribute("codecs"),ja=(r=_e.getAttribute("contentType"))!==null&&r!==void 0?r:ki==null?void 0:ki.split("/")[0],Ru=(o=(n=_e.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Ha=_e.querySelectorAll("Representation"),Du=_e.querySelector("SegmentTemplate");if(ja===oe.TEXT){for(const ie of Ha){const ft=ie.getAttribute("id")||"",Pi=_e.getAttribute("lang"),Ct=(u=(d=(l=ie.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Rs=new URL(Ct,e).toString();ve[oe.TEXT].push({id:ft,lang:Pi,kind:oe.TEXT,url:Rs})}continue}for(const ie of Ha){const ft=(c=ie.getAttribute("mimeType"))!==null&&c!==void 0?c:ki,Pi=(f=(h=ie.getAttribute("codecs"))!==null&&h!==void 0?h:Cu)!==null&&f!==void 0?f:"",Ct=(m=(p=ie.getAttribute("contentType"))!==null&&p!==void 0?p:ft==null?void 0:ft.split("/")[0])!==null&&m!==void 0?m:ja,Rs=(y=(b=_e.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&y!==void 0?y:[],Iu=parseInt((S=ie.getAttribute("width"))!==null&&S!==void 0?S:"",10),Ga=parseInt(($=ie.getAttribute("height"))!==null&&$!==void 0?$:"",10),Ya=parseInt((v=ie.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,qa=(g=ie.getAttribute("frameRate"))!==null&&g!==void 0?g:"",Nu=(E=ie.getAttribute("quality"))!==null&&E!==void 0?E:void 0,xu=qa?xa(qa):void 0,Lu=(w=ie.getAttribute("id"))!==null&&w!==void 0?w:(Au++).toString(10),Ou=Ct==="video"?`${Ga}p`:Ct==="audio"?`${Ya}Kbps`:Pi,Bu=`${Lu}@${Ou}`,Mu=(C=(U=(N=ie.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||U===void 0?void 0:U.trim())!==null&&C!==void 0?C:"",za=new URL(Mu,e).toString(),Vu=[...Cs,...Ru,...Rs];let Ds;const Fu=ie.querySelector("SegmentBase"),pt=(D=ie.querySelector("SegmentTemplate"))!==null&&D!==void 0?D:Du;if(Fu){const mt=(P=(M=ie.querySelector("SegmentBase Initialization"))===null||M===void 0?void 0:M.getAttribute("range"))!==null&&P!==void 0?P:"",[vt,Ns]=mt.split("-").map(Rt=>parseInt(Rt,10)),st={from:vt,to:Ns},Zt=(I=ie.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[xs,wi]=Zt?Zt.split("-").map(Rt=>parseInt(Rt,10)):[],ei=Zt?{from:xs,to:wi}:void 0;Ds={type:ke.BYTE_RANGE,url:za,initRange:st,indexRange:ei}}else if(pt){const mt={representationId:(Y=ie.getAttribute("id"))!==null&&Y!==void 0?Y:void 0,bandwidth:(Q=ie.getAttribute("bandwidth"))!==null&&Q!==void 0?Q:void 0},vt=parseInt((_=pt.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Ns=(j=pt.getAttribute("initialization"))!==null&&j!==void 0?j:"",st=pt.getAttribute("media"),Zt=(te=parseInt((K=pt.getAttribute("startNumber"))!==null&&K!==void 0?K:"",10))!==null&&te!==void 0?te:1,xs=Vt(Ns,mt);if(!st)throw new ReferenceError("No media attribute in SegmentTemplate");const wi=(re=pt.querySelectorAll("SegmentTimeline S"))!==null&&re!==void 0?re:[],ei=[];let Rt=0,Ls="",Os=0;if(wi.length){let Ai=Zt,Ce=0;for(const Dt of wi){const Le=parseInt((me=Dt.getAttribute("d"))!==null&&me!==void 0?me:"",10),bt=parseInt((xe=Dt.getAttribute("r"))!==null&&xe!==void 0?xe:"",10)||0,_i=parseInt((it=Dt.getAttribute("t"))!==null&&it!==void 0?it:"",10);Ce=Number.isFinite(_i)?_i:Ce;const Bs=Le/vt*1e3,Ms=Ce/vt*1e3;for(let Ci=0;Ci<bt+1;Ci++){const ju=Vt(st,Object.assign(Object.assign({},mt),{segmentNumber:Ai.toString(10),segmentTime:(Ce+Ci*Le).toString(10)})),Wa=(Ms!=null?Ms:0)+Ci*Bs,Hu=Wa+Bs;Ai++,ei.push({time:{from:Wa,to:Hu},url:ju})}Ce+=(bt+1)*Le,Rt+=(bt+1)*Bs}Os=Ce/vt*1e3,Ls=Vt(st,Object.assign(Object.assign({},mt),{segmentNumber:Ai.toString(10),segmentTime:Ce.toString(10)}))}else if(a.isNonNullable(ht)){const Ce=parseInt((H=pt.getAttribute("duration"))!==null&&H!==void 0?H:"",10)/vt*1e3,Dt=Math.ceil(ht/Ce);let Le=0;for(let bt=1;bt<Dt;bt++){const _i=Vt(st,Object.assign(Object.assign({},mt),{segmentNumber:bt.toString(10),segmentTime:Le.toString(10)}));ei.push({time:{from:Le,to:Le+Ce},url:_i}),Le+=Ce}Os=Le,Ls=Vt(st,Object.assign(Object.assign({},mt),{segmentNumber:Dt.toString(10),segmentTime:Le.toString(10)}))}const Uu={time:{from:Os,to:1/0},url:Ls};Ds={type:ke.TEMPLATE,baseUrl:za,segmentTemplateUrl:st,initUrl:xs,totalSegmentsDurationMs:Rt,segments:ei,nextSegmentBeyondManifest:Uu,timescale:vt}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ct||!ft)continue;const Is={video:oe.VIDEO,audio:oe.AUDIO,text:oe.TEXT}[Ct];Is&&ve[Is].push({id:Bu,kind:Is,segmentReference:Ds,profiles:Vu,duration:ht,bitrate:Ya,mime:ft,codecs:Pi,width:Iu,height:Ga,fps:xu,quality:Nu})}}return{dynamic:At,liveAvailabilityStartTime:$i,duration:ht,container:_u,representations:ve}},cy=({id:i,width:e,height:t,bitrate:s,fps:r,quality:n})=>{var o;const l=(o=n?Ei(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},hy=({id:i,bitrate:e})=>({id:i,bitrate:e}),fy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=Ge(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:Ge(i,-1)},py=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Co=i=>"size"in i,Bt=i=>i.type===ke.TEMPLATE,oa=i=>!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20);class Ro{constructor(e,t,s,r,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:d,compatibilityMode:u=!1,manifest:c}){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 Yt,this.destroyAbortController=new Yt,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.liveInitialAdditionalOffset=0,this.isSeekingLive=!1,this.index=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(h){return fe(this,arguments,function*(){const f=this.representations.get(h);a.assertNonNullable(f,`Cannot find representation ${h}`),this.playingRepresentationId=h,this.downloadingRepresentationId=h,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${f.mime}; codecs="${f.codecs}"`),this.sourceBufferTaskQueue=new jS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},y=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:y}))),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(y=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,To(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),y)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(y=>this.error$.next(y))),yield yield R(this.loadInit(f,"high",!0));const p=this.initData.get(f.id),m=this.segments.get(f.id),b=this.parsedInitData.get(f.id);if(a.assertNonNullable(p,"No init buffer for starting representation"),a.assertNonNullable(m,"No segments for starting representation"),!(p instanceof ArrayBuffer))return yield R(void 0);this.searchGaps(m,f),yield yield R(this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(b)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(h){return fe(this,arguments,function*(){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return yield R(void 0);this.switchingToRepresentationId=h;const f=this.representations.get(h);a.assertNonNullable(f,`No such representation ${h}`);let p=this.segments.get(h),m=this.initData.get(h);if(a.isNullable(m)||a.isNullable(p)?yield yield R(this.loadInit(f,"high",!1)):m instanceof Promise&&(yield yield R(m)),p=this.segments.get(h),a.assertNonNullable(p,"No segments for starting representation"),m=this.initData.get(h),!m||!(m instanceof ArrayBuffer)||!this.sourceBuffer)return yield R(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield yield R(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const b=this.getCurrentPosition();a.isNonNullable(b)&&(this.searchGaps(p,f),this.maintain(b))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(h){var f;return fe(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return yield R(void 0);for(const $ of this.representations.keys()){const v=h.find(w=>w.id===$);v&&this.representations.set($,v);const g=this.representations.get($);if(!g||!Bt(g.segmentReference))return yield R(void 0);const E=this.getActualLiveStartingSegments(g.segmentReference);this.segments.set(g.id,E)}const p=(f=this.switchingToRepresentationId)!==null&&f!==void 0?f:this.downloadingRepresentationId,m=this.representations.get(p);a.assertNonNullable(m);const b=this.segments.get(p);a.assertNonNullable(b,"No segments for starting representation");const y=this.initData.get(p);if(a.assertNonNullable(y,"No init buffer for starting representation"),!(y instanceof ArrayBuffer))return yield R(void 0);const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield yield R(this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal))),this.searchGaps(b,m),yield yield R(this.sourceBufferTaskQueue.append(y,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isActiveLowLatency=d,this.isLive=!!(c!=null&&c.dynamic),this.container=s,s){case zt.MP4:this.containerParser=vg;break;case zt.WEBM:this.containerParser=$g;break;default:a.assertNever(s)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Yt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=rt(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=rt(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=Ge(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===L.FED&&!l.length&&rt(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Ge(s,-1);d&&d.status===L.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)n.time.from-s>0&&this.gaps.push({representation:t.id,from:s,to:n.time.from+r}),s=n.time.to;a.isNonNullable(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let n=0,o=t.length-1;do r.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<s&&o>=0);return this.liveInitialAdditionalOffset=n-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Bt(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:L.NONE,size:void 0})),d=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(r=Ge(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.floor(u)>=Math.floor(h.time.from)&&Math.floor(u)<=Math.floor(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!Bt(r))return;const n=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),o=Vt(r.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(s.id))!==null&&t!==void 0?t:[],d=l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));d&&(d.time.to=e.segment.time.to),!!l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||l.push({status:L.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const b=f<=s&&p>=s,y=f>s||b||m===0&&s===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),$=this.preloadOnly&&f<=s+S||p<=s+S;return(h===L.NONE||h===L.PARTIALLY_EJECTED&&y&&$&&this.sourceBuffer&&!aa(this.sourceBuffer.buffered,s))&&y&&$});if(r===-1)return[];if(t!==ke.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===L.NONE||f.status===L.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,s="auto"){return q(this,void 0,void 0,function*(){t.segmentReference.type===ke.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return q(this,void 0,void 0,function*(){e.status=L.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:n,url:o,signal:l,onProgress:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(yield a.abortable(l,function(){return fe(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const u=yield this.fetcher.fetch(o,{range:n,signal:l,onProgress:d,priority:s,isLowLatency:this.isActiveLowLatency()});if(!u)return;const c=new DataView(u);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}d&&r.feedingBytes?r.segment.status=L.DOWNLOADED:this.sourceBufferTaskQueue.append(c,l).then(h=>{this.onSegmentFullyAppended(r,t.id)}),this.failedDownloads=0}catch(u){if(oa(u))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(u)}})}loadByteRangeSegments(e,t,s="auto"){return q(this,void 0,void 0,function*(){if(!e.length)return;for(const d of e)d.status=L.DOWNLOADING,this.activeSegments.add({segment:d,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{range:r,url:n,signal:o,onProgress:l}=this.prepareByteRangeFetchSegmentParams(e,t);this.failedDownloads&&o&&(yield a.abortable(o,function(){return fe(this,arguments,function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield R(new Promise(u=>setTimeout(u,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(n,{range:r,onProgress:l,signal:o,priority:s}),this.failedDownloads=0}catch(d){if(oa(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}})}prepareByteRangeFetchSegmentParams(e,t){if(Bt(t.segmentReference))throw new Error("Representation is not byte range type");const s=t.segmentReference.url,r={from:Ge(e,0).byte.from,to:Ge(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:s,range:r,signal:n,onProgress:(d,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Bt(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl).toString(),{signal:r}=this.downloadAbortController,n=()=>{this.abort()},l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,u)=>{if(!r.aborted)try{this.onSomeTemplateDataLoaded({dataView:d,loaded:u,signal:r,onSegmentAppendFailed:n,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:s,signal:r,onProgress:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=rt((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})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(o)for(const l of this.activeSegments){const{segment:d}=l;if(l.representationId===t){if(n.aborted){r();continue}if(l.loadedBytes=s,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u);c!=null&&c.byteLength&&(d.status=L.PARTIALLY_FED,l.feedingBytes+=c.byteLength,this.sourceBufferTaskQueue.append(c,n).then(h=>{h?(l.fedBytes+=c.byteLength,d.status===L.DOWNLOADED&&this.onSegmentFullyAppended(l,o.id)):r()}))}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const d=l.segmentReference.type,u=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===ke.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const b=f?h.byte.from-s:0,y=f?h.byte.to-s:e.byteLength,S=b<r,$=y<=r;if(h.status===L.DOWNLOADING&&S&&$){h.status=L.DOWNLOADED,this.activeSegments.delete(c);const v=new DataView(e.buffer,e.byteOffset+b,p);this.sourceBufferTaskQueue.append(v,n).then(g=>g&&!n.aborted?this.onSegmentFullyAppended(c,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&S&&(c.loadedBytes=Math.min(p,r-b),c.loadedBytes>c.feedingBytes)){const v=new DataView(e.buffer,e.byteOffset+b+c.feedingBytes,c.loadedBytes-c.feedingBytes),g=c.loadedBytes===p?v:this.containerParser.parseFeedableSegmentChunk(v);g!=null&&g.byteLength&&(h.status=L.PARTIALLY_FED,c.feedingBytes+=g.byteLength,this.sourceBufferTaskQueue.append(g,n).then(E=>{if(n.aborted)o();else if(E)c.fedBytes+=g.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){var s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=L.FED,Co(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const n of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])n.status===L.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=L.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e)}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===L.PARTIALLY_FED||e.status===L.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=L.NONE),e.status=L.PARTIALLY_EJECTED):e.status=L.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[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=yo(()=>$s(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return q(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 fe(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=>q(this,void 0,void 0,function*(){if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h);let f=c;this.isLive&&Bt(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)})).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,s=!1){return q(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=Co(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===L.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===L.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===L.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===L.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=yo(()=>{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!==L.FED&&n!==L.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=L.PARTIALLY_EJECTED:r.status=L.NONE)}}}var Ht;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Ht||(Ht={}));class my{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 Yt,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(r){return fe(this,arguments,function*(){let n=r;this.requestQuic&&(n=qt(n));const o=yield yield R(ci(n,{signal:this.abortAllController.signal}).catch(si));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?Ht.HEADER:Ht.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0,isLowLatency:h=!1}={}){var f,p;return fe(this,arguments,function*(){let m=r;const b=new Headers;if(o)switch(n){case Ht.HEADER:{b.append("Range",`bytes=${o.from}-${o.to}`);break}case Ht.PARAM:{const I=new URL(m,location.href);I.searchParams.append("bytes",`${o.from}-${o.to}`),m=I.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=qt(m));let y=this.abortAllController.signal,S;if(u){const I=new Yt;if(S=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{I.abort()}catch(Y){si(Y)}}),this.abortAllController.signal.aborted||u.aborted)try{I.abort()}catch(Y){si(Y)}y=I.signal}const $=a.now(),v=yield yield R(ci(m,{priority:d,headers:b,signal:y}).catch(si)),g=a.now();if(!v)return S==null||S.unsubscribe(),yield R(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(g-$),!v.ok||!v.body)return S==null||S.unsubscribe(),yield R(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));if(this.onHeadersReceived(v.headers),!l&&!c)return S==null||S.unsubscribe(),yield R(v.arrayBuffer());const[E,w]=v.body.tee(),N=E.getReader();c&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(w,h));let U=0,C=new Uint8Array(0),D=!1;const M=I=>{S==null||S.unsubscribe(),D=!0,si(I)},P=a.abortable(y,function({done:I,value:Y}){return fe(this,arguments,function*(){if(U===0&&this.lastRequestFirstBytes$.next(a.now()-$),y.aborted)return S==null||S.unsubscribe(),yield R(void 0);if(!I&&Y){const Q=new Uint8Array(C.length+Y.length);Q.set(C),Q.set(Y,C.length),C=Q,U+=Y.byteLength,l==null||l(new DataView(C.buffer),U),yield yield R(N==null?void 0:N.read().then(P,M))}})}.bind(this));return yield yield R(N==null?void 0:N.read().then(P,M)),S==null||S.unsubscribe(),yield R(D?null:C.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return fe(this,arguments,function*(){if(r.type!==ke.BYTE_RANGE)return yield R(null);const{from:d,to:u}=r.initRange;let c=d,h=u,f=!1,p,m;r.indexRange&&(p=r.indexRange.from,m=r.indexRange.to,f=u+1===p,f&&(c=Math.min(p,d),h=Math.max(m,u))),c=Math.min(c,0);const b=yield yield R(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!b)return yield R(null);const y=new DataView(b,d-c,u-c+1);if(!n.validateData(y))throw new Error("Invalid media file");const S=n.parseInit(y),$=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!$)throw new ReferenceError("No way to load representation index");let v;if(f)v=new DataView(b,$.from-c,$.to-$.from+1);else{const E=yield yield R(this.fetch(r.url,{range:$,priority:o,measureThroughput:!1}));if(!E)return yield R(null);v=new DataView(E)}const g=n.parseSegments(v,S,$);return yield R({init:S,dataView:new DataView(b),segments:g})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return fe(this,arguments,function*(){if(r.type!==ke.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:L.NONE,size:void 0}));return yield R({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=du(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,n;return q(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case ke.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case ke.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 si=i=>{if(oa(i))throw i},la=1e3,cs=(i,e,t)=>t*e+(1-t)*i,Tu=(i,e)=>i.reduce((t,s)=>t+s,0)/e,vy=(i,e,t,s)=>{let r=0,n=t;const o=Tu(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 Ma{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 Me(`raw_${s}`),this.smoothedSeries$=new Me(`smoothed_${s}`),this.reportedSeries$=new Me(`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 by extends Ma{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cs(this.slow,e,this.params.emaAlphaSlow),this.fast=cs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Sy extends Ma{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Tu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cs(this.emaSmoothed,e,this.params.emaAlpha);const s=vy(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class gy extends Ma{constructor(e){super(e),this.furtherValues=[],this.currentTopExtremumValue=0,this.extremumInterval=e.extremumInterval}next(e){this.currentTopExtremumValue<=e?(this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.length===this.extremumInterval?(super.next(this.currentTopExtremumValue),this.currentTopExtremumValue=e,this.furtherValues=[]):this.furtherValues.push(e)}updateSmoothedValue(e){this.smoothed=this.smoothed?cs(this.smoothed,e,this.params.emaAlpha):e}}class ua{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new by({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new Sy({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new gy(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const yy=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},Do=["timeupdate","progress","play","seeked","stalled","waiting"];var $e;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})($e||($e={}));let Ty=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new X($e.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Yt,this.initManifest=a.abortable(this.destroyController.signal,function(t,s,r){var n;return fe(this,arguments,function*(){this.element=t,this.manifestUrlString=Ue(s,r,ne.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo($e.MANIFEST_READY),this.manifest=yield yield R(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState($e.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:a.ErrorCategory.PARSER,message:"No playable video representations"})})}.bind(this)),this.updateManifest=a.abortable(this.destroyController.signal,function(){var t;return fe(this,arguments,function*(){const s=yield yield R(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!s)return yield R(this.manifest);let r;try{r=dy(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return yield R(null);const n=({kind:o,mime:l,codecs:d})=>{var u,c,h,f;return!!(!((c=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||c===void 0)&&c.call(u,l)&&(!((f=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||f===void 0)&&f.call(h,`${l}; codecs="${d}"`))||o===oe.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive,this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield R(Object.assign(Object.assign({},r),{representations:gi(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,s){return fe(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo($e.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,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new Ro(oe.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new Ro(oe.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,r),this.bufferManagers.push(this.audioBufferManager)),this.representationSubscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.representationSubscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.representationSubscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$)),this.representationSubscription.add(a.interval(la).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=fo(this.manifestUrlString,ne.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ue(this.manifestUrlString,u+la,ne.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Do.map(l=>a.fromEvent(this.element,l))).pipe(a.map(l=>this.element?rt(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(l=>!!l)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(a.filter(d=>this.isActiveLowLatency&&!!d)).subscribe(d=>this.liveEstimatedDelay.next(d))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(d=>{if(!this.isActiveLowLatency)return;const u=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,f=d-u;let p=1+Math.sign(f)*h;Math.abs(f)<c?p=1:Math.abs(f)>c*2&&(p=1+Math.sign(f)*h*2),yy(this.element,p)})),this.representationSubscription.add(this.bufferLength$.subscribe(d=>{var u,c;let h=0;if(d){const f=((c=(u=this.element)===null||u===void 0?void 0:u.currentTime)!==null&&c!==void 0?c:0)*1e3;h=Math.min(...this.bufferManagers.map(m=>{var b,y;return(y=(b=m.getLiveSegmentsToLoadState(this.manifest))===null||b===void 0?void 0:b.to)!==null&&y!==void 0?y:0}))-f}h&&this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(a.combine({liveLoadBufferLength:this.liveLoadBufferLength$}).subscribe(({liveLoadBufferLength:d})=>q(this,void 0,void 0,function*(){if(a.assertNonNullable(this.element),this.isUpdatingLive)return;const u=this.element.playbackRate,c=fo(this.manifestUrlString,ne.DASH_CMAF_OFFSET_P),h=this.tuning.dashCmafLive.lowLatency.isActive,f=this.tuning.dashCmafLive.normalizedTargetMinBufferSize*u,p=this.tuning.dashCmafLive.normalizedActualBufferOffset*u,m=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*u;l=d>l?d:l;let b=Ee.None;if(h&&c===0?b=Ee.ActiveLowLatency:!h&&c===0&&d<m?b=Ee.ActiveLive:c!==0&&d<f+m&&d>=f?b=Ee.LiveWithTargetOffset:c!==0&&d<f&&(b=Ee.LiveForwardBuffering),this.isActiveLowLatency=b===Ee.ActiveLowLatency,b===Ee.LiveForwardBuffering||b===Ee.LiveWithTargetOffset){const y=l-(f+p),S=Math.trunc(c+y/u);let $;d?S>0?$=S:$=0:$=c,this.manifestUrlString=Ue(this.manifestUrlString,$,ne.DASH_CMAF_OFFSET_P)}b!==Ee.None&&b!==Ee.ActiveLowLatency&&(l=0,this.updateLive())})))}const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield R(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield R(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield R(this.videoBufferManager.startWith(t)),this.state$.setState($e.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new my({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=ua.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,n;return q(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.manifestUrlString=Ue(this.manifestUrlString,e,ne.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState($e.RUNNING),this.subscription.add(a.merge(...Do.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&&aa(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 s={[oe.VIDEO]:this.videoBufferManager,[oe.AUDIO]:this.audioBufferManager,[oe.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),aa(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($e.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}updateLive(){var e;return q(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class Ey{constructor(e,t){this.fov=e,this.orientation=t}}class $y{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var ky=`#define GLSLIFY 1
|
|
7
|
+
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,Py=`#ifdef GL_ES
|
|
8
8
|
precision highp float;precision highp int;
|
|
9
9
|
#else
|
|
10
10
|
precision highp float;
|
|
11
11
|
#define GLSLIFY 1
|
|
12
12
|
#endif
|
|
13
13
|
#define PI 3.14159265358979323846264
|
|
14
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class hy{constructor(e,t,r){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=r,this.canvas=this.createCanvas();const s=this.canvas.getContext("webgl");if(!s)throw new Error("Could not initialize WebGL context");this.gl=s,this.container.appendChild(this.canvas),this.camera=new ly(this.params.fov,this.params.orientation),this.cameraRotationManager=new uy(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),r=this.gl.getAttribLocation(this.program,"a_texel"),s=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(r),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(r,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(s,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(r),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const r=this.gl.createShader(t);if(!r)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(r,e),this.gl.compileShader(r),!this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(r));return r}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(dy,this.gl.VERTEX_SHADER),r=this.createShader(cy,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,r),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,r=1;const s=this.frameHeight/(this.frameWidth/this.viewportWidth);return s>this.viewportHeight?t=this.viewportHeight/s:r=s/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-r,t,-r,t,r,-t,r]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,r=this.camera.fov.x/360/2,s=this.camera.fov.y/180/2,n=e-r,o=t-s,l=e+r,d=t-s,u=e+r,c=t+s,h=e-r,f=t+s;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)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class mu{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(Z.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Fe,this.droppedFramesManager=new Tr,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new dS,this.textTracks=[],this.syncPlayback=()=>{var t,r,s;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===B.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==Z.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(r=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&r!==void 0?r:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case Z.STOPPED:this.videoState.startTransitionTo(Z.READY),this.prepare();return;case Z.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),(s=this.liveOffset)===null||s===void 0||s.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var r,s,n;if(this.scene3D)return;this.scene3D=new hy(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((r=t.projectionData)===null||r===void 0?void 0:r.pose.yaw)||0,y:((s=t.projectionData)===null||s===void 0?void 0:s.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Ke(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new oy({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,r=Xe(this.video),s=this.constructor.name,n=l=>{e.error$.next({id:s,category:a.ErrorCategory.WTF,message:`${s} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:r,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:r,genericErrorListener:s,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:r.playing$,pause$:r.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(r.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(gt(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(at(this.video,t.playbackRate,r.playbackRateState$,s)),n(rr(this.video),this.elementSize$),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},s)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Ee.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();a.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((T,g)=>g.bitrate-T.bitrate),m=Array.from(f.video).sort((T,g)=>g.bitrate-T.bitrate),b=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const T of p){const g=vg(T);g&&this.audioTracks.push({track:g,representation:T})}for(const T of m){const g=mg(T);if(g){h.push({track:g,representation:T});const v=!this.params.tuning.isAudioDisabled&&bg(p,m,T);v&&this.audioRepresentations.set(T.id,v)}}this.videoTracks$.next(h);for(const T of b){const g=Sg(T);g&&this.textTracks.push({track:g,representation:T})}this.params.output.availableVideoTracks$.next(h.map(({track:T})=>T)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:T})=>T)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:T})=>T));const y=this.selectVideoRepresentation();a.assertNonNullable(y),this.player.initRepresentations(y.id,(c=this.audioRepresentations.get(y.id))===null||c===void 0?void 0:c.id)}else u===Ee.REPRESENTATIOS_READY&&(this.videoState.setState(Z.READY),this.player.initBuffer())},s));const o=u=>e.error$.next({id:"RepresentationSwitch",category:a.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(a.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==Ee.RUNNING||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),h){this.player.switchRepresentation(oe.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(oe.AUDIO,p.id).catch(o)}},s)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,s)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},s)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const 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$.getValue().find(({track:{id:T}})=>T===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=tt(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),b=Ht(this.videoTracks$.getValue().map(({track:T})=>T),{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,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}),y=l?b!=null?b:u:u!=null?u:b;return y&&((o=this.videoTracks$.getValue().find(({track:T})=>T===y))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){nt(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Je(this.video)}}class fy extends mu{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();r(t.timeUpdate$,e.position$),r(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class py extends mu{constructor(e){super(e),this.liveOffset=new yr}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:r}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),r(t.timeUpdate$,e.liveBufferTime$),r(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(ta),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:s})=>{var n;if(this.videoState.getState()===Z.PLAYING){const o=e.position$.getValue()+(s-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:s,liveAvailabilityStartTime:n})=>s&&n?s+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),r=this.videoState.getState(),s=t===exports.PlaybackState.PAUSED&&r===Z.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,s)})}}const Ne={};var G;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(G||(G={}));const ei=(i,e)=>new a.Observable(t=>{const r=(s,n)=>t.next(n);return i.on(e,r),()=>i.off(e,r)});class my{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(G.INITIALIZING),this.textTracksManager=new Fe,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!==G.INITIALIZING)switch((s==null?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&this.seek(n.position),r){case exports.PlaybackState.STOPPED:switch(t){case G.STOPPED:break;case G.READY:case G.PLAYING:case G.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case G.STOPPED:this.prepare();break;case G.READY:case G.PLAYING:case G.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case G.PLAYING:break;case G.STOPPED:this.prepare();break;case G.READY:case G.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case G.PAUSED:break;case G.STOPPED:this.prepare();break;case G.READY:this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case G.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(r)}},this.video=Ke(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(fe(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),Je(this.video)}loadHlsJs(){let e=!1;const t=s=>{e||this.params.output.error$.next({id:s==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:s}),e=!0},r=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);gr(import("hls.js").then(s=>{e||(Ne.Hls=s.default,Ne.Events=s.default.Events,this.init())},t),()=>{window.clearTimeout(r),e=!0})}init(){a.assertNonNullable(Ne.Hls,"hls.js not loaded"),this.hls=new Ne.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(G.STOPPED)}subscribe(){a.assertNonNullable(Ne.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,r=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},s=Xe(this.video),n=(u,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.inPiP$,t.inPiP$),n(s.inFullscreen$,t.inFullscreen$),this.subscription.add(gt(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(at(this.video,e.playbackRate,s.playbackRateState$,r)),this.subscription.add(ei(this.hls,Ne.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(G.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(G.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)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.PLAYING&&this.playIfAllowed()},r)),n(ei(this.hls,Ne.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:b,height:y}=h,T=(p=Si((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:b,height:y});if(!T)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:T,bitrate:h.bitrate/1e3,size:{width:b,height:y},fps:g};return this.trackLevels.set(m,{track:v,level:h}),c.push(v),c},[]))),t.availableVideoTracks$),n(ei(this.hls,Ne.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const c=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI||"",m=h.lang,b="internal";c.push({id:f,url:p,language:m,type:b})}e.internalTextTracks.startTransitionTo(c)}}),n(ei(this.hls,Ne.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>fe(u))),t.hostname$),this.subscription.add(Re(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError: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=ei(this.hls,Ne.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(Re(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(G.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(G.PLAYING),(yield nt(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(G.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(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const ko="X-Playback-Duration";var Po=i=>Q(void 0,void 0,void 0,function*(){var e;const t=yield oi(i,{method:"HEAD"}),r=yield t.text(),s=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(r))===null||e===void 0?void 0:e[1];return s?parseInt(s,10):t.headers.has(ko)?parseInt(t.headers.get(ko),10):void 0});const vy=i=>{let e=null;if(i.QUALITY&&(e=Si(i.QUALITY)),!e&&i.RESOLUTION){const[t,r]=i.RESOLUTION.split("x").map(s=>parseInt(s,10));e=a.videoSizeToQuality({width:t,height:r})}return e!=null?e:null},vu=(i,e=i)=>Q(void 0,void 0,void 0,function*(){var t;const n=(yield(yield oi(i)).text()).split(`
|
|
15
|
-
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=mi(u[1].split(",").map(T=>T.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=vy(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 b;if(c.RESOLUTION){const[T,g]=c.RESOLUTION.split("x").map(v=>parseInt(v,10));T&&g&&(b={width:T,height:g})}const y=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:y,bandwidth:p,size:b,fps:m})}return o});var z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(z||(z={}));class by{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(z.STOPPED),this.textTracksManager=new Fe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new yr,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(o===exports.PlaybackState.STOPPED){n!==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 h=this.params.desiredState.seekState.getState();if(n===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(d||u){const f=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested){this.videoState.startTransitionTo(z.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(n){case z.READY:o===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.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())):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case z.CHANGING_MANIFEST:break;default:return a.assertNever(n)}},this.params=e,this.video=Ke(e.container),this.params.output.element$.next(this.video);const r={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url};vu(Me(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.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),this.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.length)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=Xe(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.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),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(at(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),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),this.videoState.getState()===z.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(fe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===B.Requested&&this.seek(l.position)},r)),this.subscription.add(s.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},r)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:s.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),r)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Je(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Me(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Po(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{oi(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();Po(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,r=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(r),this.params.output.position$.next(-r/1e3),this.params.output.seekedEvent$.next()}}var K;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(K||(K={}));class Sy{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(K.STOPPED),this.textTracksManager=new Fe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const s=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){s!==K.STOPPED&&(this.videoState.startTransitionTo(K.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(K.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===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(K.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),c.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:f*1e3,forcePrecise:!0});return}switch((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===B.Requested&&this.seek(c.position),s){case K.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case K.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=Ke(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(fe(this.params.source.url)),vu(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.length)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=Xe(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.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gt(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(at(this.video,t.playbackRate,s.playbackRateState$,r)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(K.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)===K.READY&&this.videoState.setState(K.READY),this.videoState.getState()===K.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(fe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===K.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===B.Requested&&this.seek(l.position)},r))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,r));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Je(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ee||(ee={}));class gy{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(ee.STOPPED),this.trackUrls={},this.textTracksManager=new Fe,this.syncPlayback=()=>{var t,r,s;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.seekState.getState();if(u&&n!==ee.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(c){const{currentTime:f}=this.video;this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:f*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((s=(r=this.trackUrls[c.to])===null||r===void 0?void 0:r.track)===null||s===void 0?void 0:s.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested&&this.seek(h.position),n){case ee.READY:o===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=Ke(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,r],s)=>{const n=s.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:r}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,r=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},s=Xe(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.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),this.subscription.add(gt(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(at(this.video,t.playbackRate,s.playbackRateState$,r)),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ee.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)===ee.READY&&this.videoState.setState(ee.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()===ee.PLAYING&&this.playIfAllowed()},r)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Je(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();a.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];a.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Bt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(fe(t))}playIfAllowed(){nt(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,r,s;let n;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const o=(r=Object.values(this.trackUrls).find(u=>a.isLowerOrEqual(u.track.quality,e)))===null||r===void 0?void 0:r.track,l=this.params.desiredState.videoTrack.getState(),d=(s=this.trackUrls[l!=null?l:"0"])===null||s===void 0?void 0:s.track;o&&d&&a.isHigherOrEqual(d.quality,o.quality)&&(n=o)}else if(!e){const o=Object.values(this.trackUrls).map(l=>l.track);n=Ht(o,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const wo=["stun:videostun.mycdn.me:80"],yy=1e3,Ty=3,Ss=()=>null;class Ey{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ss,this.externalStopCallback=Ss,this.externalErrorCallback=Ss,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:wo}]};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),yy)}normalizeOptions(e={}){const t={stunServerList:wo,maxRetryNumber:Ty,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));class $y{constructor(e){this.videoState=new J(W.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!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.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===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case W.READY:r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),k(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()):(s==null?void 0:s.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.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=Ke(e.container),this.liveStreamClient=new Ey(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),Je(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,r=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const s=Xe(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,r));n(s.timeUpdate$,e.liveTime$),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),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)===W.READY&&this.videoState.setState(W.READY)},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},r)).add(s.playing$.subscribe(()=>{this.videoState.setState(W.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 W.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.READY:break;case W.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},r)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),r)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),r)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),r))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(fe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:a.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(W.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(){nt(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Ao{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var gs,ys,Ts,Es,$s,ks,Hi,Ps,Gi,ws,Yi,As,qi,_s,zi,Rs,Wi,Cs;const bu=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,it=document.createElement("video"),ky='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Py='video/mp4; codecs="hev1.1.6.L93.B0"',Su='video/webm; codecs="vp09.00.10.08"',gu='video/webm; codecs="av01.0.00M.08"',wy='audio/mp4; codecs="mp4a.40.2"',Ay='audio/webm; codecs="opus"',Ae={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((ys=(gs=window.SourceBuffer)===null||gs===void 0?void 0:gs.prototype)===null||ys===void 0)&&ys.appendBuffer)),hls:!!(!((Ts=it.canPlayType)===null||Ts===void 0)&&Ts.call(it,"application/x-mpegurl")||!((Es=it.canPlayType)===null||Es===void 0)&&Es.call(it,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ve={mp4:!!(!(($s=it.canPlayType)===null||$s===void 0)&&$s.call(it,"video/mp4")),webm:!!(!((ks=it.canPlayType)===null||ks===void 0)&&ks.call(it,"video/webm")),cmaf:!0},Be={h264:!!(!((Ps=(Hi=window.MediaSource)===null||Hi===void 0?void 0:Hi.isTypeSupported)===null||Ps===void 0)&&Ps.call(Hi,ky)),h265:!!(!((ws=(Gi=window.MediaSource)===null||Gi===void 0?void 0:Gi.isTypeSupported)===null||ws===void 0)&&ws.call(Gi,Py)),vp9:!!(!((As=(Yi=window.MediaSource)===null||Yi===void 0?void 0:Yi.isTypeSupported)===null||As===void 0)&&As.call(Yi,Su)),av1:!!(!((_s=(qi=window.MediaSource)===null||qi===void 0?void 0:qi.isTypeSupported)===null||_s===void 0)&&_s.call(qi,gu)),aac:!!(!((Rs=(zi=window.MediaSource)===null||zi===void 0?void 0:zi.isTypeSupported)===null||Rs===void 0)&&Rs.call(zi,wy)),opus:!!(!((Cs=(Wi=window.MediaSource)===null||Wi===void 0?void 0:Wi.isTypeSupported)===null||Cs===void 0)&&Cs.call(Wi,Ay))},Ct=(Be.h264||Be.h265)&&Be.aac;var He;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(He||(He={}));let ft;const _y=()=>Q(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:gu})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Su})}))]);ft={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{_y()}catch(i){console.error(i)}const li=Ae.hls&&ve.mp4,Ry=()=>Object.keys(Be).filter(i=>Be[i]),Cy=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Ae.mse&&ve.mp4&&Ct;case exports.VideoFormat.DASH_SEP:return Ae.mse&&ve.mp4&&Ct;case exports.VideoFormat.DASH_WEBM:return Ae.mse&&ve.webm&&Be.vp9&&Be.opus;case exports.VideoFormat.DASH_WEBM_AV1:return Ae.mse&&ve.webm&&Be.av1&&Be.opus;case exports.VideoFormat.DASH_LIVE:return Ae.mse&&ve.mp4&&Ct;case exports.VideoFormat.DASH_LIVE_CMAF:return Ae.mse&&ve.mp4&&Ct&&ve.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Ae.mse&&ve.mp4&&Ct;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return li||e&&Ae.mse&&ve.mp4&&Ct;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return li;case exports.VideoFormat.MPEG:return ve.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Ae.webrtc&&Ae.ws&&Be.h264&&(ve.mp4||ve.webm);default:return a.assertNever(t)}}),Is=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case He.VP9:return[e,t];case He.AV1:return[t,e];case He.NONE:return[];case He.SMOOTH:return ft?ft[t].smooth?[t,e]:ft[e].smooth?[e,t]:[t,e]:[e,t];case He.POWER_EFFICIENT:return ft?ft[t].powerEfficient?[t,e]:ft[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(i)}return[e,t]},Iy=(i=He.VP9)=>bu?[exports.VideoFormat.MPEG,...Is(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:li?[...Is(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Is(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Dy=()=>bu?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:li?[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],_o=i=>i?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Ny=i=>new a.Observable(e=>{const t=new a.Subscription,r=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),s=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(r.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(s.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const xy={cacheDuration:12e4},Ly={chunkDuration:5e3,maxParallelRequests:5};class Oy{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),autoVideoTrackLimits$:new a.ValueSubject(void 0),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,warning$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),isLowLatency$:new a.ValueSubject(!1),canChangePlaybackSpeed$:new a.ValueSubject(!0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Cy([...Dy(),...Iy(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:r,formatsToAvoid:s}=this.params.tuning;let n=[];r?n=[r]:s.length?n=[...t.filter(l=>!s.includes(l)),...t.filter(l=>s.includes(l))]:n=t,this.screenFormatsIterator=new Ao(n);const o=[..._o(!0),..._o(!1)];this.chromecastFormatsIterator=new Ao(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let r;try{r=this.createProvider(e,t)}catch(s){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:s})}r?this.current$.next({type:t,provider:r,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,r=this.params.desiredState.seekState.getState(),s=r.state!==B.None;if(this.params.desiredState.seekState.setState({state:B.Requested,position:s?r.position:t,forcePrecise:s?r.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ue.SCREEN:return this.createScreenProvider(t);case ue.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 DS(Object.assign(Object.assign({},o),{source:l,config:xy}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new lo(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new fy(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJsCMAF?new lo(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new py(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),li||!this.params.tuning.useHlsJs?new Sy(Object.assign(Object.assign({},o),{source:l})):new my(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 by(Object.assign(Object.assign({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new gy(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:Object.assign(Object.assign({},Ly),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new $y({container:r,source:l,desiredState:s,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:r,desiredState:s,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Mb({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()?ue.CHROMECAST:ue.SCREEN}chooseFormat(e){switch(e){case ue.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ue.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case ue.SCREEN:return this.screenFormatsIterator.next();case ue.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case ue.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ue.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 mi(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$,Ny({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(s=>({id:`ProviderHangup:${s}`,category:a.ErrorCategory.WTF,message:`A ${s} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const s=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(s)})),e.add(this.providerError$.subscribe(s=>{const n=this.current$.getValue().destination;if(n===ue.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ue.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=s.category===a.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=r<this.params.tuning.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(r++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:ue.SCREEN)}})),e}}const ia=(i,e,t)=>t*e+(1-t)*i,yu=(i,e)=>i.reduce((t,r)=>t+r,0)/e,By=(i,e,t,r)=>{let s=0,n=t;const o=yu(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 Tu{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const r=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new Le(`raw_${r}`),this.smoothedSeries$=new Le(`smoothed_${r}`),this.reportedSeries$=new Le(`reported_${r}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,r=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),r++);this.takenMeasures=r,t/=r;const s=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*s,o=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class My extends Tu{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ia(this.slow,e,this.params.emaAlphaSlow),this.fast=ia(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Vy extends Tu{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=yu(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ia(this.emaSmoothed,e,this.params.emaAlpha);const r=By(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=r?this.emaSmoothed:t}}class Ro{static getSmoothedValue(e,t,r){return r.type==="TwoEma"?new My({initial:e,emaAlphaSlow:r.emaAlphaSlow,emaAlphaFast:r.emaAlphaFast,changeThreshold:r.changeThreshold,fastDirection:t,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"}):new Vy({initial:e,emaAlpha:r.emaAlpha,basisTrendChangeCount:r.basisTrendChangeCount,changeThreshold:r.changeThreshold,deviationDepth:r.deviationDepth,deviationFactor:r.deviationFactor,label:"throughput"})}}const Fy=5e3,Co="one_video_throughput",Io="one_video_rtt",qe=window.navigator.connection,Do=()=>{const i=qe==null?void 0:qe.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},No=()=>{const i=qe==null?void 0:qe.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},xo=(i,e,t)=>{const r=t*8,s=r/i;return r/(s+e)};class si{constructor(e){var t,r;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const s=si.load(Co)||(e.useBrowserEstimation?Do():void 0)||Fy,n=(r=(t=si.load(Io))!==null&&t!==void 0?t:e.useBrowserEstimation?No():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(xo(s,n,e.rttPenaltyRequestSize)),this.throughput=Ro.getSmoothedValue(s,-1,e),this.rtt=Ro.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Do();d&&this.throughput.next(d);const u=No();a.isNonNullable(u)&&this.rtt.next(u)};qe&&"onchange"in qe&&this.subscription.add(a.fromEvent(qe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(Co,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(Io,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})=>xo(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(si.sanityCheck(e,t)){const s=e*8/t;this.throughput.next(s*r)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||e<10*1024||t<=20)}static load(e){var t;const r=a.safeStorage.get(e);if(a.isNonNullable(r))return(t=parseInt(r,10))!==null&&t!==void 0?t:void 0}}const Lo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3},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,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:He.VP9,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,isAudioDisabled:!1,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Uy=i=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(i,Lo)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Lo.configName]})};var Oo=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var r;return t.state===B.None?void 0:((r=t.position)!==null&&r!==void 0?r:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===B.None))),jy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};class Hy{constructor(e={configName:[]}){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:B.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([]),internalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({}),cameraOrientation:new J({x:0,y:0})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),canChangePlaybackSpeed$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),atLiveDurationEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:oS},this.initLogs(),this.tuning=Uy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new qu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new si(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=jy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Oy({sources:e.sources,meta:(r=e.meta)!==null&&r!==void 0?r:{},failoverHosts:(s=e.failoverHosts)!==null&&s!==void 0?s:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const r=this.info.duration$.getValue(),s=this.info.isLive$.getValue();return e>=r&&!s&&(e=r-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const r=t.find(s=>s.quality===e);return r&&this.desiredState.videoTrack.startTransitionTo(r.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const r=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return r&&(this.desiredState.playbackRate.setState(e),r.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return(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()}startCameraManualRotation(e,t){const r=this.getScene3D();return r&&r.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const r=this.getScene3D();if(r){const s=r.getCameraRotation(),n=r.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:s.x+n.x,y:s.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),r=t.state===B.None?void 0:t.position;return a.isNonNullable(r)?r/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const r=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=r==null?void 0:r.provider)===null||t===void 0)&&t.scene3D)return r.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((r,{width:s})=>r||s||0,0),height:e.reduce((r,{height:s})=>r||s||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===B.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:B.Applying})):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:l})=>l).sort((l,d)=>a.isInvariantQuality(l)?1:a.isInvariantQuality(d)?-1:a.isHigher(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(a.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(a.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Oo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(a.map(({isLive:o,position:l,isLowLatency:d})=>{const u=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(l)<u/1e3}),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(a.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(a.map(({isLive:o,position:l,duration:d})=>o&&Math.abs(d)-Math.abs(l)<this.tuning.live.activeLiveDelay),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Oo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const r=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>r.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>r.next(!1)));let s=0;const n=a.merge(e.providerOutput.isBuffering$,t,r).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||r.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?s=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(s),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((r,s)=>r.provider===s.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{this.setStartingVideoTrack(r)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:r})=>r===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Ht(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),nS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(r=>aS(r)),this.providerContainer.current$.subscribe(({type:r})=>Vi("provider",r)),t.duration$.subscribe(r=>Vi("duration",r)),t.availableVideoTracks$.pipe(a.filter(r=>!!r.length),a.once()).subscribe(r=>Vi("tracks",r)),this.events.fatalError$.subscribe(new Le("fatalError")),this.events.managedError$.subscribe(new Le("managedError")),t.position$.subscribe(new Le("position")),t.currentVideoTrack$.pipe(a.map(r=>r==null?void 0:r.quality)).subscribe(new Le("quality")),this.info.currentBuffer$.subscribe(new Le("buffer")),t.isBuffering$.subscribe(new Le("isBuffering"))].forEach(r=>this.subscription.add(r)),Vi("codecs",Ry())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},r=()=>Q(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(s=>{s instanceof DOMException&&s.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(s)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const s=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);s&&n?o||r():t()})).add(this.events.willDestruct$.subscribe(t))}}const Gy=`@vkontakte/videoplayer-core@${Bo}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return a.VideoQuality}});exports.Player=Hy;exports.SDK_VERSION=Gy;exports.VERSION=Bo;
|
|
14
|
+
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class wy{constructor(e,t,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new Ey(this.params.fov,this.params.orientation),this.cameraRotationManager=new $y(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),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.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(ky,this.gl.VERTEX_SHADER),s=this.createShader(Py,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.orientation.x/360,t=.5-this.camera.orientation.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)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class Eu{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(Z.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new He,this.droppedFramesManager=new Ps,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new vS,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===B.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==Z.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case Z.STOPPED:this.videoState.startTransitionTo(Z.READY),this.prepare();return;case Z.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case Z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var s,r,n;if(this.scene3D)return;this.scene3D=new wy(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=Xe(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ty({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=et(this.video),r=this.constructor.name,n=l=>{e.error$.next({id:r,category:a.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:s,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Pt(this.video,t.isLooped,r)),this.subscription.add(Je(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(lt(this.video,t.playbackRate,s.playbackRateState$,r)),n(ns(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===$e.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();a.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((S,$)=>$.bitrate-S.bitrate),m=Array.from(f.video).sort((S,$)=>$.bitrate-S.bitrate),b=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const S of p){const $=hy(S);$&&this.audioTracks.push({track:$,representation:S})}for(const S of m){const $=cy(S);if($){h.push({track:$,representation:S});const v=!this.params.tuning.isAudioDisabled&&fy(p,m,S);v&&this.audioRepresentations.set(S.id,v)}}this.videoTracks$.next(h);for(const S of b){const $=py(S);$&&this.textTracks.push({track:$,representation:S})}this.params.output.availableVideoTracks$.next(h.map(({track:S})=>S)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:S})=>S)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:S})=>S));const y=this.selectVideoRepresentation();a.assertNonNullable(y),this.player.initRepresentations(y.id,(c=this.audioRepresentations.get(y.id))===null||c===void 0?void 0:c.id)}else u===$e.REPRESENTATIOS_READY&&(this.videoState.setState(Z.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.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==$e.RUNNING||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),f=this.params.desiredState.autoVideoTrackLimits.getTransition();if(f&&this.params.output.autoVideoTrackLimits$.next(f.to),h){this.player.switchRepresentation(oe.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(oe.AUDIO,p.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().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=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},r)),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$.getValue().find(({track:{id:S}})=>S===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=rt(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&&(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),b=Xt(this.videoTracks$.getValue().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,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit}),y=l?b!=null?b:u:u!=null?u:b;return y&&((o=this.videoTracks$.getValue().find(({track:S})=>S===y))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){ut(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(Z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}}class Ay extends Eu{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class _y extends Eu{constructor(e){super(e),this.liveOffset=new ks}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(la),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===Z.PLAYING){const o=e.position$.getValue()+(r-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===Z.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,r)})}}const Be={};var G;(function(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(G||(G={}));const ri=(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 X(G.INITIALIZING),this.textTracksManager=new He,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!==G.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&this.seek(n.position),s){case exports.PlaybackState.STOPPED:switch(t){case G.STOPPED:break;case G.READY:case G.PLAYING:case G.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case G.STOPPED:this.prepare();break;case G.READY:case G.PLAYING:case G.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case G.PLAYING:break;case G.STOPPED:this.prepare();break;case G.READY:case G.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case G.PAUSED:break;case G.STOPPED:this.prepare();break;case G.READY:this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case G.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(s)}},this.video=Xe(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}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"),this.params.tuning.dynamicImportTimeout);$s(import("hls.js").then(r=>{e||(Be.Hls=r.default,Be.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(Be.Hls,"hls.js not loaded"),this.hls=new Be.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(G.STOPPED)}subscribe(){a.assertNonNullable(Be.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=et(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.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Pt(this.video,e.isLooped,s)),this.subscription.add(Je(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(lt(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(ri(this.hls,Be.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(G.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.PLAYING&&this.playIfAllowed()},s)),n(ri(this.hls,Be.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:b,height:y}=h,S=(p=Ei((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:b,height:y});if(!S)return c;const $=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:b,height:y},fps:$};return this.trackLevels.set(m,{track:v,level:h}),c.push(v),c},[]))),t.availableVideoTracks$),n(ri(this.hls,Be.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const c=[];for(const h of u.subtitleTracks){const f=h.name,p=h.attrs.URI||"",m=h.lang,b="internal";c.push({id:f,url:p,language:m,type:b})}e.internalTextTracks.startTransitionTo(c)}}),n(ri(this.hls,Be.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>pe(u))),t.hostname$),this.subscription.add(Ie(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=ri(this.hls,Be.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(Ie(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: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(G.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(G.PLAYING),(yield ut(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:t})))||(this.videoState.setState(G.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(G.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(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Io="X-Playback-Duration";var No=i=>q(void 0,void 0,void 0,function*(){var e;const t=yield ci(i,{method:"HEAD"}),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(Io)?parseInt(t.headers.get(Io),10):void 0});const Ry=i=>{let e=null;if(i.QUALITY&&(e=Ei(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=a.videoSizeToQuality({width:t,height:s})}return e!=null?e:null},$u=(i,e=i)=>q(void 0,void 0,void 0,function*(){var t;const n=(yield(yield ci(i)).text()).split(`
|
|
15
|
+
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=gi(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Ry(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 b;if(c.RESOLUTION){const[S,$]=c.RESOLUTION.split("x").map(v=>parseInt(v,10));S&&$&&(b={width:S,height:$})}const y=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:y,bandwidth:p,size:b,fps:m})}return o});var z;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(z||(z={}));class Dy{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new X(z.STOPPED),this.textTracksManager=new He,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ks,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(o===exports.PlaybackState.STOPPED){n!==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 h=this.params.desiredState.seekState.getState();if(n===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(d||u){const f=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested){this.videoState.startTransitionTo(z.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(n){case z.READY:o===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.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())):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case z.CHANGING_MANIFEST:break;default:return a.assertNever(n)}},this.params=e,this.video=Xe(e.container),this.params.output.element$.next(this.video);const s={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url};$u(Ue(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.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),this.maxSeekBackTime$=new 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.length)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=et(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.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(Je(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),k(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),this.videoState.getState()===z.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(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(pe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===B.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$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=Ue(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),No(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{ci(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();No(u).then(c=>{a.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var J;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(J||(J={}));class Iy{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(J.STOPPED),this.textTracksManager=new He,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;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!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===J.STOPPED){this.videoState.startTransitionTo(J.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(J.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),c.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:f*1e3,forcePrecise:!0});return}switch((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===B.Requested&&this.seek(c.position),r){case J.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed());return;case J.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case J.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=Xe(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(pe(this.params.source.url)),$u(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.length)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=et(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.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Pt(this.video,t.isLooped,s)),this.subscription.add(Je(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===J.READY&&this.videoState.setState(J.READY),this.videoState.getState()===J.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(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(pe(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===J.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===B.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$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ze(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var ee;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ee||(ee={}));class Ny{constructor(e){this.subscription=new a.Subscription,this.videoState=new X(ee.STOPPED),this.trackUrls={},this.textTracksManager=new He,this.syncPlayback=()=>{var t,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.seekState.getState();if(u&&n!==ee.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(c){const{currentTime:f}=this.video;this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:f*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(s=this.trackUrls[c.to])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested&&this.seek(h.position),n){case ee.READY:o===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=Xe(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().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.params.output.autoVideoTrackLimitingAvailable$.next(!0),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=et(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.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Pt(this.video,t.isLooped,s)),this.subscription.add(Je(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},s)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===ee.READY&&this.videoState.setState(ee.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()===ee.PLAYING&&this.playIfAllowed()},s)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ze(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();a.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];a.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=qt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(pe(t))}playIfAllowed(){ut(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r;let n;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const o=(s=Object.values(this.trackUrls).find(u=>a.isLowerOrEqual(u.track.quality,e)))===null||s===void 0?void 0:s.track,l=this.params.desiredState.videoTrack.getState(),d=(r=this.trackUrls[l!=null?l:"0"])===null||r===void 0?void 0:r.track;o&&d&&a.isHigherOrEqual(d.quality,o.quality)&&(n=o)}else if(!e){const o=Object.values(this.trackUrls).map(l=>l.track);n=Xt(o,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const xo=["stun:videostun.mycdn.me:80"],xy=1e3,Ly=3,$r=()=>null;class Oy{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=$r,this.externalStopCallback=$r,this.externalErrorCallback=$r,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 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:xo}]};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),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),xy)}normalizeOptions(e={}){const t={stunServerList:xo,maxRetryNumber:Ly,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var W;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));class By{constructor(e){this.videoState=new X(W.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!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.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===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case W.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()):(r==null?void 0:r.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()):(r==null?void 0:r.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=Xe(e.container),this.liveStreamClient=new Oy(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),Ze(this.video)}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=et(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$),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)===W.READY&&this.videoState.setState(W.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Je(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case W.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.READY:break;case W.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.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.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(pe(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:a.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(W.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(){ut(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Lo{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var kr,Pr,wr,Ar,_r,Cr,qi,Rr,zi,Dr,Wi,Ir,Qi,Nr,Ki,xr,Ji,Lr;const ku=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,at=document.createElement("video"),My='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Vy='video/mp4; codecs="hev1.1.6.L93.B0"',Pu='video/webm; codecs="vp09.00.10.08"',wu='video/webm; codecs="av01.0.00M.08"',Fy='audio/mp4; codecs="mp4a.40.2"',Uy='audio/webm; codecs="opus"',Re={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Pr=(kr=window.SourceBuffer)===null||kr===void 0?void 0:kr.prototype)===null||Pr===void 0)&&Pr.appendBuffer)),hls:!!(!((wr=at.canPlayType)===null||wr===void 0)&&wr.call(at,"application/x-mpegurl")||!((Ar=at.canPlayType)===null||Ar===void 0)&&Ar.call(at,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},be={mp4:!!(!((_r=at.canPlayType)===null||_r===void 0)&&_r.call(at,"video/mp4")),webm:!!(!((Cr=at.canPlayType)===null||Cr===void 0)&&Cr.call(at,"video/webm")),cmaf:!0},Fe={h264:!!(!((Rr=(qi=window.MediaSource)===null||qi===void 0?void 0:qi.isTypeSupported)===null||Rr===void 0)&&Rr.call(qi,My)),h265:!!(!((Dr=(zi=window.MediaSource)===null||zi===void 0?void 0:zi.isTypeSupported)===null||Dr===void 0)&&Dr.call(zi,Vy)),vp9:!!(!((Ir=(Wi=window.MediaSource)===null||Wi===void 0?void 0:Wi.isTypeSupported)===null||Ir===void 0)&&Ir.call(Wi,Pu)),av1:!!(!((Nr=(Qi=window.MediaSource)===null||Qi===void 0?void 0:Qi.isTypeSupported)===null||Nr===void 0)&&Nr.call(Qi,wu)),aac:!!(!((xr=(Ki=window.MediaSource)===null||Ki===void 0?void 0:Ki.isTypeSupported)===null||xr===void 0)&&xr.call(Ki,Fy)),opus:!!(!((Lr=(Ji=window.MediaSource)===null||Ji===void 0?void 0:Ji.isTypeSupported)===null||Lr===void 0)&&Lr.call(Ji,Uy))},Mt=(Fe.h264||Fe.h265)&&Fe.aac;var Ye;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Ye||(Ye={}));let gt;const jy=()=>q(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:wu})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Pu})}))]);gt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{jy()}catch(i){console.error(i)}const hi=Re.hls&&be.mp4,Hy=()=>Object.keys(Fe).filter(i=>Fe[i]),Gy=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return Re.mse&&be.mp4&&Mt;case exports.VideoFormat.DASH_SEP:return Re.mse&&be.mp4&&Mt;case exports.VideoFormat.DASH_WEBM:return Re.mse&&be.webm&&Fe.vp9&&Fe.opus;case exports.VideoFormat.DASH_WEBM_AV1:return Re.mse&&be.webm&&Fe.av1&&Fe.opus;case exports.VideoFormat.DASH_LIVE:return Re.mse&&be.mp4&&Mt;case exports.VideoFormat.DASH_LIVE_CMAF:return Re.mse&&be.mp4&&Mt&&be.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return Re.mse&&be.mp4&&Mt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return hi||e&&Re.mse&&be.mp4&&Mt;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return hi;case exports.VideoFormat.MPEG:return be.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Re.webrtc&&Re.ws&&Fe.h264&&(be.mp4||be.webm);default:return a.assertNever(t)}}),Or=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){case Ye.VP9:return[e,t];case Ye.AV1:return[t,e];case Ye.NONE:return[];case Ye.SMOOTH:return gt?gt[t].smooth?[t,e]:gt[e].smooth?[e,t]:[t,e]:[e,t];case Ye.POWER_EFFICIENT:return gt?gt[t].powerEfficient?[t,e]:gt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(i)}return[e,t]},Yy=(i=Ye.VP9)=>ku?[exports.VideoFormat.MPEG,...Or(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:hi?[...Or(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Or(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],qy=()=>ku?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:hi?[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_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var zy=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$.pipe(a.map(({type:u})=>u!==void 0)),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="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Wy={cacheDuration:12e4},Qy={chunkDuration:5e3,maxParallelRequests:5};class Ky{constructor(e){this.current$=new a.ValueSubject({type:void 0}),this.providerError$=new a.Subject,this.noAvailableProvidersError$=new a.Subject,this.providerOutput={position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),volume$:new a.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new a.ValueSubject(void 0),availableVideoTracks$:new a.ValueSubject([]),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new a.ValueSubject(!1),autoVideoTrackLimits$:new a.ValueSubject(void 0),currentBuffer$:new a.ValueSubject(void 0),isBuffering$:new a.ValueSubject(!0),error$:new a.Subject,warning$:new a.Subject,willSeekEvent$:new a.Subject,seekedEvent$:new a.Subject,loopedEvent$:new a.Subject,endedEvent$:new a.Subject,firstBytesEvent$:new a.Subject,firstFrameEvent$:new a.Subject,canplay$:new a.Subject,isLive$:new a.ValueSubject(void 0),isLowLatency$:new a.ValueSubject(!1),canChangePlaybackSpeed$:new a.ValueSubject(!0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),inPiP$:new a.ValueSubject(!1),inFullscreen$:new a.ValueSubject(!1),element$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Gy([...qy(),...Yy(this.params.tuning.webmCodec)],this.params.tuning.useHlsJs).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let n=[];s?n=[s]:r.length?n=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:n=t,this.screenFormatsIterator=new Lo(n);const o=[...Oo(!0),...Oo(!1)];this.chromecastFormatsIterator=new Lo(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let 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.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==B.None;if(this.params.desiredState.seekState.setState({state:B.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ue.SCREEN:return this.createScreenProvider(t);case ue.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 MS(Object.assign(Object.assign({},o),{source:l,config:Wy}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new vo(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new Ay(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJsCMAF?new vo(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):new _y(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),hi||!this.params.tuning.useHlsJs?new Iy(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 Dy(Object.assign(Object.assign({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Ny(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new NS(Object.assign(Object.assign({},o),{source:l,config:Object.assign(Object.assign({},Qy),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new By({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 Gb({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()?ue.CHROMECAST:ue.SCREEN}chooseFormat(e){switch(e){case ue.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ue.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case ue.SCREEN:return this.screenFormatsIterator.next();case ue.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case ue.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ue.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 gi(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$,zy({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).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=>{const n=this.current$.getValue().destination;if(n===ue.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ue.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=r.category===a.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:ue.SCREEN)}})),e}}const Jy=5e3,Bo="one_video_throughput",Mo="one_video_rtt",We=window.navigator.connection,Vo=()=>{const i=We==null?void 0:We.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},Fo=()=>{const i=We==null?void 0:We.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},Uo=(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(Bo)||(e.useBrowserEstimation?Vo():void 0)||Jy,n=(s=(t=li.load(Mo))!==null&&t!==void 0?t:e.useBrowserEstimation?Fo():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(Uo(r,n,e.rttPenaltyRequestSize)),this.throughput=ua.getSmoothedValue(r,-1,e),this.rtt=ua.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Vo();d&&this.throughput.next(d);const u=Fo();a.isNonNullable(u)&&this.rtt.next(u)};We&&"onchange"in We&&this.subscription.add(a.fromEvent(We,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(Bo,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(Mo,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})=>Uo(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,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,n=a.now(),o=0,l=a.now();const d=c=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=({done:c,value:h})=>q(this,void 0,void 0,function*(){c?(!t&&this.addRawSpeed(r,a.now()-n,1),this.concurrentDownloads.delete(e)):h&&(t?(a.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval&&a.now()-n<this.tuningConfig.lowLatency.separateByteSequenceInterval?o+=h.byteLength:(this.addRawSpeed(o,a.now()-n,this.concurrentDownloads.size,t),o=h.byteLength,n=a.now()),l=a.now()):(r+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&a.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,a.now()-l,this.concurrentDownloads.size),o=0,l=a.now())),yield s==null?void 0:s.read().then(u,d))});this.concurrentDownloads.add(e),s==null||s.read().then(u,d)}addRawSpeed(e,t,s=1,r=!1){if(r||li.sanityCheck(e,t)){const n=e*8/t;this.throughput.next(n*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){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=a.safeStorage.get(e);if(a.isNonNullable(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const jo={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:5,separateByteSequenceInterval:100}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3},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},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!0,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Ye.VP9,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,isAudioDisabled:!1,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Xy=i=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(i,jo)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...jo.configName]})};var Ho=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var s;return t.state===B.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===B.None))),Zy=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};class eT{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new X(exports.PlaybackState.STOPPED),seekState:new X({state:B.None}),volume:new X({volume:1,muted:!1}),videoTrack:new X(void 0),autoVideoTrackSwitching:new X(!0),autoVideoTrackLimits:new X({}),isLooped:new X(!1),playbackRate:new X(1),externalTextTracks:new X([]),internalTextTracks:new X([]),currentTextTrack:new X(void 0),textTrackCuesSettings:new X({}),cameraOrientation:new X({x:0,y:0})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),canChangePlaybackSpeed$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),atLiveDurationEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:fS},this.initLogs(),this.tuning=Xy(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Xu({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new 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,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),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=Zy(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Ky({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(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const 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.startTransitionTo(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()}startCameraManualRotation(e,t){const s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),n=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){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===B.None?void 0:t.position;return a.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width: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$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===B.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:B.Applying})):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:a.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(a.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(a.map(o=>o.destination),a.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(a.map(o=>o.map(({quality:l})=>l).sort((l,d)=>a.isInvariantQuality(l)?1:a.isInvariantQuality(d)?-1:a.isHigher(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(a.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(a.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(a.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(a.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:Ho({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(a.map(({isLive:o,position:l,isLowLatency:d})=>{const u=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(l)<u/1e3}),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(a.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(a.map(({isLive:o,position:l,duration:d})=>o&&Math.abs(d)-Math.abs(l)<this.tuning.live.activeLiveDelay),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Ho({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===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 o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||s.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((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=Xt(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),hS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>cS(s)),this.providerContainer.current$.subscribe(({type:s})=>Hi("provider",s)),t.duration$.subscribe(s=>Hi("duration",s)),t.availableVideoTracks$.pipe(a.filter(s=>!!s.length),a.once()).subscribe(s=>Hi("tracks",s)),this.events.fatalError$.subscribe(new Me("fatalError")),this.events.managedError$.subscribe(new Me("managedError")),t.position$.subscribe(new Me("position")),t.currentVideoTrack$.pipe(a.map(s=>s==null?void 0:s.quality)).subscribe(new Me("quality")),this.info.currentBuffer$.subscribe(new Me("buffer")),t.isBuffering$.subscribe(new Me("isBuffering"))].forEach(s=>this.subscription.add(s)),Hi("codecs",Hy())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>q(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||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.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);r&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}}const tT=`@vkontakte/videoplayer-core@${Go}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return a.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return a.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return a.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return a.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return a.VideoQuality}});exports.Player=eT;exports.SDK_VERSION=tT;exports.VERSION=Go;
|