@vkontakte/videoplayer-core 2.0.98-dev.97d8def3.0 → 2.0.98-dev.a3af0042.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 +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +7 -7
- package/evergreen.esm.js +5 -5
- package/package.json +2 -2
package/es2015.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.98-dev.
|
|
3
|
-
* Thu, 15 Feb 2024
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.a3af0042.0
|
|
3
|
+
* Thu, 15 Feb 2024 18:07:53 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Cd=Object.create;var zn=Object.defineProperty;var Ld=Object.getOwnPropertyDescriptor;var xd=Object.getOwnPropertyNames;var Nd=Object.getPrototypeOf,Od=Object.prototype.hasOwnProperty;var Bd=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xd(e))!Od.call(s,r)&&r!==t&&zn(s,r,{get:()=>e[r],enumerable:!(i=Ld(e,r))||i.enumerable});return s};var qn=(s,e,t)=>(t=s!=null?Cd(Nd(s)):{},Bd(e||!s||!s.__esModule?zn(t,"default",{value:s,enumerable:!0}):t,s));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js");const Fl="2.0.98-dev.97d8def3.0";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var Ae;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var Y;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(Y||(Y={}));exports.Surface=void 0;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(exports.Surface||(exports.Surface={}));function F(s,e,t,i){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(i.next(c))}catch(h){o(h)}}function d(c){try{u(i.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(l,d)}u((i=i.apply(s,e||[])).next())})}function w(s){return this instanceof w?(this.v=s,this):new w(s)}function Z(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){i[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(i[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof w?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 Md=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Vd{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 i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)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||Md("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 i,r,n;(n=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.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),i=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(i,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=i.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(i,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([i.getCastState()])).pipe(a.filterChanged(),a.map(Fd),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=i.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,i,r;try{t=cast.framework.CastContext.getInstance(),i=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:i,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Fd=s=>{switch(s){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(s)}};var Fr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function hr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Je=function(s){try{return!!s()}catch(e){return!0}},Ud=Je,fr=!Ud(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ul=fr,jl=Function.prototype,ja=jl.call,jd=Ul&&jl.bind.bind(ja,ja),Xe=Ul?jd:function(s){return function(){return ja.apply(s,arguments)}},Hl=Xe,Hd=Hl({}.toString),Gd=Hl("".slice),cs=function(s){return Gd(Hd(s),8,-1)},Yd=Xe,zd=Je,qd=cs,Ur=Object,Wd=Yd("".split),Qd=zd(function(){return!Ur("z").propertyIsEnumerable(0)})?function(s){return qd(s)=="String"?Wd(s,""):Ur(s)}:Ur,hs=function(s){return s==null},Kd=hs,Jd=TypeError,vn=function(s){if(Kd(s))throw Jd("Can't call method on "+s);return s},Xd=Qd,Zd=vn,fs=function(s){return Xd(Zd(s))},Ni={},$s=function(s){return s&&s.Math==Math&&s},Ee=$s(typeof globalThis=="object"&&globalThis)||$s(typeof window=="object"&&window)||$s(typeof self=="object"&&self)||$s(typeof Fr=="object"&&Fr)||function(){return this}()||Fr||Function("return this")(),Ha=typeof document=="object"&&document.all,ec=typeof Ha=="undefined"&&Ha!==void 0,Gl={all:Ha,IS_HTMLDDA:ec},Yl=Gl,tc=Yl.all,pe=Yl.IS_HTMLDDA?function(s){return typeof s=="function"||s===tc}:function(s){return typeof s=="function"},ic=Ee,sc=pe,Wn=ic.WeakMap,rc=sc(Wn)&&/native code/.test(String(Wn)),Qn=pe,zl=Gl,ac=zl.all,Ct=zl.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Qn(s)||s===ac}:function(s){return typeof s=="object"?s!==null:Qn(s)},nc=Je,jt=!nc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ui={},oc=Ee,Kn=Ct,Ga=oc.document,lc=Kn(Ga)&&Kn(Ga.createElement),gn=function(s){return lc?Ga.createElement(s):{}},uc=jt,dc=Je,cc=gn,ql=!uc&&!dc(function(){return Object.defineProperty(cc("div"),"a",{get:function(){return 7}}).a!=7}),hc=jt,fc=Je,Wl=hc&&fc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),pc=Ct,mc=String,vc=TypeError,Lt=function(s){if(pc(s))return s;throw vc(mc(s)+" is not an object")},gc=fr,ks=Function.prototype.call,Ge=gc?ks.bind(ks):function(){return ks.apply(ks,arguments)},bn={},jr=bn,Hr=Ee,bc=pe,Jn=function(s){return bc(s)?s:void 0},di=function(s,e){return arguments.length<2?Jn(jr[s])||Jn(Hr[s]):jr[s]&&jr[s][e]||Hr[s]&&Hr[s][e]},Sc=Xe,pr=Sc({}.isPrototypeOf),mr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Ql=Ee,Gr=mr,Xn=Ql.process,Zn=Ql.Deno,eo=Xn&&Xn.versions||Zn&&Zn.version,to=eo&&eo.v8,st,Ks;to&&(st=to.split("."),Ks=st[0]>0&&st[0]<4?1:+(st[0]+st[1]));!Ks&&Gr&&(st=Gr.match(/Edge\/(\d+)/),(!st||st[1]>=74)&&(st=Gr.match(/Chrome\/(\d+)/),st&&(Ks=+st[1])));var Kl=Ks,io=Kl,yc=Je,Tc=Ee,Ec=Tc.String,Jl=!!Object.getOwnPropertySymbols&&!yc(function(){var s=Symbol();return!Ec(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&io&&io<41}),$c=Jl,Xl=$c&&!Symbol.sham&&typeof Symbol.iterator=="symbol",kc=di,wc=pe,Ac=pr,Pc=Xl,_c=Object,Zl=Pc?function(s){return typeof s=="symbol"}:function(s){var e=kc("Symbol");return wc(e)&&Ac(e.prototype,_c(s))},Dc=String,vr=function(s){try{return Dc(s)}catch(e){return"Object"}},Ic=pe,Rc=vr,Cc=TypeError,ci=function(s){if(Ic(s))return s;throw Cc(Rc(s)+" is not a function")},Lc=ci,xc=hs,gr=function(s,e){var t=s[e];return xc(t)?void 0:Lc(t)},Yr=Ge,zr=pe,qr=Ct,Nc=TypeError,Oc=function(s,e){var t,i;if(e==="string"&&zr(t=s.toString)&&!qr(i=Yr(t,s))||zr(t=s.valueOf)&&!qr(i=Yr(t,s))||e!=="string"&&zr(t=s.toString)&&!qr(i=Yr(t,s)))return i;throw Nc("Can't convert object to primitive value")},eu={exports:{}},Bc=!0,so=Ee,Mc=Object.defineProperty,Vc=function(s,e){try{Mc(so,s,{value:e,configurable:!0,writable:!0})}catch(t){so[s]=e}return e},Fc=Ee,Uc=Vc,ro="__core-js_shared__",jc=Fc[ro]||Uc(ro,{}),Sn=jc,ao=Sn;(eu.exports=function(s,e){return ao[s]||(ao[s]=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 tu=eu.exports,Hc=vn,Gc=Object,br=function(s){return Gc(Hc(s))},Yc=Xe,zc=br,qc=Yc({}.hasOwnProperty),mt=Object.hasOwn||function(e,t){return qc(zc(e),t)},Wc=Xe,Qc=0,Kc=Math.random(),Jc=Wc(1 .toString),iu=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Jc(++Qc+Kc,36)},Xc=Ee,Zc=tu,no=mt,eh=iu,th=Jl,ih=Xl,ki=Xc.Symbol,Wr=Zc("wks"),sh=ih?ki.for||ki:ki&&ki.withoutSetter||eh,Ie=function(s){return no(Wr,s)||(Wr[s]=th&&no(ki,s)?ki[s]:sh("Symbol."+s)),Wr[s]},rh=Ge,oo=Ct,lo=Zl,ah=gr,nh=Oc,oh=Ie,lh=TypeError,uh=oh("toPrimitive"),dh=function(s,e){if(!oo(s)||lo(s))return s;var t=ah(s,uh),i;if(t){if(e===void 0&&(e="default"),i=rh(t,s,e),!oo(i)||lo(i))return i;throw lh("Can't convert object to primitive value")}return e===void 0&&(e="number"),nh(s,e)},ch=dh,hh=Zl,yn=function(s){var e=ch(s,"string");return hh(e)?e:e+""},fh=jt,ph=ql,mh=Wl,ws=Lt,uo=yn,vh=TypeError,Qr=Object.defineProperty,gh=Object.getOwnPropertyDescriptor,Kr="enumerable",Jr="configurable",Xr="writable";ui.f=fh?mh?function(e,t,i){if(ws(e),t=uo(t),ws(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xr in i&&!i[Xr]){var r=gh(e,t);r&&r[Xr]&&(e[t]=i.value,i={configurable:Jr in i?i[Jr]:r[Jr],enumerable:Kr in i?i[Kr]:r[Kr],writable:!1})}return Qr(e,t,i)}:Qr:function(e,t,i){if(ws(e),t=uo(t),ws(i),ph)try{return Qr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw vh("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Sr=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},bh=jt,Sh=ui,yh=Sr,ps=bh?function(s,e,t){return Sh.f(s,e,yh(1,t))}:function(s,e,t){return s[e]=t,s},Th=tu,Eh=iu,co=Th("keys"),Tn=function(s){return co[s]||(co[s]=Eh(s))},En={},$h=rc,su=Ee,kh=Ct,wh=ps,Zr=mt,ea=Sn,Ah=Tn,Ph=En,ho="Object already initialized",Ya=su.TypeError,_h=su.WeakMap,Js,os,Xs,Dh=function(s){return Xs(s)?os(s):Js(s,{})},Ih=function(s){return function(e){var t;if(!kh(e)||(t=os(e)).type!==s)throw Ya("Incompatible receiver, "+s+" required");return t}};if($h||ea.state){var lt=ea.state||(ea.state=new _h);lt.get=lt.get,lt.has=lt.has,lt.set=lt.set,Js=function(s,e){if(lt.has(s))throw Ya(ho);return e.facade=s,lt.set(s,e),e},os=function(s){return lt.get(s)||{}},Xs=function(s){return lt.has(s)}}else{var vi=Ah("state");Ph[vi]=!0,Js=function(s,e){if(Zr(s,vi))throw Ya(ho);return e.facade=s,wh(s,vi,e),e},os=function(s){return Zr(s,vi)?s[vi]:{}},Xs=function(s){return Zr(s,vi)}}var ru={set:Js,get:os,has:Xs,enforce:Dh,getterFor:Ih},Rh=fr,au=Function.prototype,fo=au.apply,po=au.call,nu=typeof Reflect=="object"&&Reflect.apply||(Rh?po.bind(fo):function(){return po.apply(fo,arguments)}),Ch=cs,Lh=Xe,ou=function(s){if(Ch(s)==="Function")return Lh(s)},$n={},lu={},uu={}.propertyIsEnumerable,du=Object.getOwnPropertyDescriptor,xh=du&&!uu.call({1:2},1);lu.f=xh?function(e){var t=du(this,e);return!!t&&t.enumerable}:uu;var Nh=jt,Oh=Ge,Bh=lu,Mh=Sr,Vh=fs,Fh=yn,Uh=mt,jh=ql,mo=Object.getOwnPropertyDescriptor;$n.f=Nh?mo:function(e,t){if(e=Vh(e),t=Fh(t),jh)try{return mo(e,t)}catch(i){}if(Uh(e,t))return Mh(!Oh(Bh.f,e,t),e[t])};var Hh=Je,Gh=pe,Yh=/#|\.prototype\./,ms=function(s,e){var t=qh[zh(s)];return t==Qh?!0:t==Wh?!1:Gh(e)?Hh(e):!!e},zh=ms.normalize=function(s){return String(s).replace(Yh,".").toLowerCase()},qh=ms.data={},Wh=ms.NATIVE="N",Qh=ms.POLYFILL="P",cu=ms,vo=ou,Kh=ci,Jh=fr,Xh=vo(vo.bind),yr=function(s,e){return Kh(s),e===void 0?s:Jh?Xh(s,e):function(){return s.apply(e,arguments)}},As=Ee,Zh=nu,ef=ou,tf=pe,sf=$n.f,rf=cu,gi=bn,af=yr,bi=ps,go=mt,nf=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Zh(s,this,arguments)};return e.prototype=s.prototype,e},at=function(s,e){var t=s.target,i=s.global,r=s.stat,n=s.proto,o=i?As:r?As[t]:(As[t]||{}).prototype,l=i?gi:gi[t]||bi(gi,t,{})[t],d=l.prototype,u,c,h,f,p,m,b,S,g;for(f in e)u=rf(i?f:t+(r?".":"#")+f,s.forced),c=!u&&o&&go(o,f),m=l[f],c&&(s.dontCallGetSet?(g=sf(o,f),b=g&&g.value):b=o[f]),p=c&&b?b:e[f],!(c&&typeof m==typeof p)&&(s.bind&&c?S=af(p,As):s.wrap&&c?S=nf(p):n&&tf(p)?S=ef(p):S=p,(s.sham||p&&p.sham||m&&m.sham)&&bi(S,"sham",!0),bi(l,f,S),n&&(h=t+"Prototype",go(gi,h)||bi(gi,h,{}),bi(gi[h],f,p),s.real&&d&&(u||!d[f])&&bi(d,f,p)))},za=jt,of=mt,hu=Function.prototype,lf=za&&Object.getOwnPropertyDescriptor,kn=of(hu,"name"),uf=kn&&function(){}.name==="something",df=kn&&(!za||za&&lf(hu,"name").configurable),cf={EXISTS:kn,PROPER:uf,CONFIGURABLE:df},fu={},hf=Math.ceil,ff=Math.floor,pf=Math.trunc||function(e){var t=+e;return(t>0?ff:hf)(t)},mf=pf,wn=function(s){var e=+s;return e!==e||e===0?0:mf(e)},vf=wn,gf=Math.max,bf=Math.min,Sf=function(s,e){var t=vf(s);return t<0?gf(t+e,0):bf(t,e)},yf=wn,Tf=Math.min,Ef=function(s){return s>0?Tf(yf(s),9007199254740991):0},$f=Ef,An=function(s){return $f(s.length)},kf=fs,wf=Sf,Af=An,bo=function(s){return function(e,t,i){var r=kf(e),n=Af(r),o=wf(i,n),l;if(s&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in r)&&r[o]===t)return s||o||0;return!s&&-1}},Pf={includes:bo(!0),indexOf:bo(!1)},_f=Xe,ta=mt,Df=fs,If=Pf.indexOf,Rf=En,So=_f([].push),Cf=function(s,e){var t=Df(s),i=0,r=[],n;for(n in t)!ta(Rf,n)&&ta(t,n)&&So(r,n);for(;e.length>i;)ta(t,n=e[i++])&&(~If(r,n)||So(r,n));return r},pu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Lf=Cf,xf=pu,Nf=Object.keys||function(e){return Lf(e,xf)},Of=jt,Bf=Wl,Mf=ui,Vf=Lt,Ff=fs,Uf=Nf;fu.f=Of&&!Bf?Object.defineProperties:function(e,t){Vf(e);for(var i=Ff(t),r=Uf(t),n=r.length,o=0,l;n>o;)Mf.f(e,l=r[o++],i[l]);return e};var jf=di,mu=jf("document","documentElement"),Hf=Lt,Gf=fu,yo=pu,Yf=En,zf=mu,qf=gn,Wf=Tn,To=">",Eo="<",qa="prototype",Wa="script",vu=Wf("IE_PROTO"),ia=function(){},gu=function(s){return Eo+Wa+To+s+Eo+"/"+Wa+To},$o=function(s){s.write(gu("")),s.close();var e=s.parentWindow.Object;return s=null,e},Qf=function(){var s=qf("iframe"),e="java"+Wa+":",t;return s.style.display="none",zf.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(gu("document.F=Object")),t.close(),t.F},Ps,zs=function(){try{Ps=new ActiveXObject("htmlfile")}catch(e){}zs=typeof document!="undefined"?document.domain&&Ps?$o(Ps):Qf():$o(Ps);for(var s=yo.length;s--;)delete zs[qa][yo[s]];return zs()};Yf[vu]=!0;var bu=Object.create||function(e,t){var i;return e!==null?(ia[qa]=Hf(e),i=new ia,ia[qa]=null,i[vu]=e):i=zs(),t===void 0?i:Gf.f(i,t)},Kf=Je,Jf=!Kf(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Xf=mt,Zf=pe,ep=br,tp=Tn,ip=Jf,ko=tp("IE_PROTO"),Qa=Object,sp=Qa.prototype,Su=ip?Qa.getPrototypeOf:function(s){var e=ep(s);if(Xf(e,ko))return e[ko];var t=e.constructor;return Zf(t)&&e instanceof t?t.prototype:e instanceof Qa?sp:null},rp=ps,Pn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:rp(s,e,t),s},ap=Je,np=pe,op=Ct,lp=bu,wo=Su,up=Pn,dp=Ie,Ka=dp("iterator"),yu=!1,Dt,sa,ra;[].keys&&(ra=[].keys(),"next"in ra?(sa=wo(wo(ra)),sa!==Object.prototype&&(Dt=sa)):yu=!0);var cp=!op(Dt)||ap(function(){var s={};return Dt[Ka].call(s)!==s});cp?Dt={}:Dt=lp(Dt);np(Dt[Ka])||up(Dt,Ka,function(){return this});var Tu={IteratorPrototype:Dt,BUGGY_SAFARI_ITERATORS:yu},hp=Ie,fp=hp("toStringTag"),Eu={};Eu[fp]="z";var _n=String(Eu)==="[object z]",pp=_n,mp=pe,qs=cs,vp=Ie,gp=vp("toStringTag"),bp=Object,Sp=qs(function(){return arguments}())=="Arguments",yp=function(s,e){try{return s[e]}catch(t){}},vs=pp?qs:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=yp(e=bp(s),gp))=="string"?t:Sp?qs(e):(i=qs(e))=="Object"&&mp(e.callee)?"Arguments":i},Tp=_n,Ep=vs,$p=Tp?{}.toString:function(){return"[object "+Ep(this)+"]"},kp=_n,wp=ui.f,Ap=ps,Pp=mt,_p=$p,Dp=Ie,Ao=Dp("toStringTag"),Dn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Pp(r,Ao)||wp(r,Ao,{configurable:!0,value:e}),i&&!kp&&Ap(r,"toString",_p)}},Ip=Tu.IteratorPrototype,Rp=bu,Cp=Sr,Lp=Dn,xp=Ni,Np=function(){return this},Op=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Rp(Ip,{next:Cp(+!i,t)}),Lp(s,r,!1,!0),xp[r]=Np,s},Bp=at,Mp=Ge,$u=cf,Vp=Op,Fp=Su,Up=Dn,Po=Pn,jp=Ie,_o=Ni,ku=Tu,Hp=$u.PROPER;$u.CONFIGURABLE;ku.IteratorPrototype;var _s=ku.BUGGY_SAFARI_ITERATORS,aa=jp("iterator"),Do="keys",Ds="values",Io="entries",Gp=function(){return this},Yp=function(s,e,t,i,r,n,o){Vp(t,e,i);var l=function(g){if(g===r&&f)return f;if(!_s&&g in c)return c[g];switch(g){case Do:return function(){return new t(this,g)};case Ds:return function(){return new t(this,g)};case Io:return function(){return new t(this,g)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[aa]||c["@@iterator"]||r&&c[r],f=!_s&&h||l(r),p=e=="Array"&&c.entries||h,m,b,S;if(p&&(m=Fp(p.call(new s)),m!==Object.prototype&&m.next&&(Up(m,d,!0,!0),_o[d]=Gp)),Hp&&r==Ds&&h&&h.name!==Ds&&(u=!0,f=function(){return Mp(h,this)}),r)if(b={values:l(Ds),keys:n?f:l(Do),entries:l(Io)},o)for(S in b)(_s||u||!(S in c))&&Po(c,S,b[S]);else Bp({target:e,proto:!0,forced:_s||u},b);return o&&c[aa]!==f&&Po(c,aa,f,{name:r}),_o[e]=f,b},zp=function(s,e){return{value:s,done:e}},qp=fs,Ro=Ni,wu=ru;ui.f;var Wp=Yp,Is=zp,Au="Array Iterator",Qp=wu.set,Kp=wu.getterFor(Au);Wp(Array,"Array",function(s,e){Qp(this,{type:Au,target:qp(s),index:0,kind:e})},function(){var s=Kp(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Is(void 0,!0)):t=="keys"?Is(i,!1):t=="values"?Is(e[i],!1):Is([i,e[i]],!1)},"values");Ro.Arguments=Ro.Array;var Jp=Ie,Xp=Ni,Zp=Jp("iterator"),em=Array.prototype,tm=function(s){return s!==void 0&&(Xp.Array===s||em[Zp]===s)},im=vs,Co=gr,sm=hs,rm=Ni,am=Ie,nm=am("iterator"),Pu=function(s){if(!sm(s))return Co(s,nm)||Co(s,"@@iterator")||rm[im(s)]},om=Ge,lm=ci,um=Lt,dm=vr,cm=Pu,hm=TypeError,fm=function(s,e){var t=arguments.length<2?cm(s):e;if(lm(t))return um(om(t,s));throw hm(dm(s)+" is not iterable")},pm=Ge,Lo=Lt,mm=gr,vm=function(s,e,t){var i,r;Lo(s);try{if(i=mm(s,"return"),!i){if(e==="throw")throw t;return t}i=pm(i,s)}catch(n){r=!0,i=n}if(e==="throw")throw t;if(r)throw i;return Lo(i),t},gm=yr,bm=Ge,Sm=Lt,ym=vr,Tm=tm,Em=An,xo=pr,$m=fm,km=Pu,No=vm,wm=TypeError,Ws=function(s,e){this.stopped=s,this.result=e},Oo=Ws.prototype,In=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=gm(e,i),u,c,h,f,p,m,b,S=function(y){return u&&No(u,"normal",y),new Ws(!0,y)},g=function(y){return r?(Sm(y),l?d(y[0],y[1],S):d(y[0],y[1])):l?d(y,S):d(y)};if(n)u=s.iterator;else if(o)u=s;else{if(c=km(s),!c)throw wm(ym(s)+" is not iterable");if(Tm(c)){for(h=0,f=Em(s);f>h;h++)if(p=g(s[h]),p&&xo(Oo,p))return p;return new Ws(!1)}u=$m(s,c)}for(m=n?s.next:u.next;!(b=bm(m,u)).done;){try{p=g(b.value)}catch(y){No(u,"throw",y)}if(typeof p=="object"&&p&&xo(Oo,p))return p}return new Ws(!1)},Am=yn,Pm=ui,_m=Sr,Dm=function(s,e,t){var i=Am(e);i in s?Pm.f(s,i,_m(0,t)):s[i]=t},Im=at,Rm=In,Cm=Dm;Im({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Rm(e,function(i,r){Cm(t,i,r)},{AS_ENTRIES:!0}),t}});var Lm=bn,xm=Lm.Object.fromEntries,Nm={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},Om=Nm,Bm=Ee,Mm=vs,Vm=ps,Bo=Ni,Fm=Ie,Mo=Fm("toStringTag");for(var na in Om){var Vo=Bm[na],oa=Vo&&Vo.prototype;oa&&Mm(oa)!==Mo&&Vm(oa,Mo,na),Bo[na]=Bo.Array}var Um=xm,jm=Um,Hm=jm,Gm=Hm,ni=hr(Gm),Ym=cs,Tr=typeof process!="undefined"&&Ym(process)=="process",zm=ui,qm=function(s,e,t){return zm.f(s,e,t)},Wm=di,Qm=qm,Km=Ie,Jm=jt,Fo=Km("species"),Xm=function(s){var e=Wm(s);Jm&&e&&!e[Fo]&&Qm(e,Fo,{configurable:!0,get:function(){return this}})},Zm=pr,ev=TypeError,tv=function(s,e){if(Zm(e,s))return s;throw ev("Incorrect invocation")},iv=Xe,sv=pe,Ja=Sn,rv=iv(Function.toString);sv(Ja.inspectSource)||(Ja.inspectSource=function(s){return rv(s)});var _u=Ja.inspectSource,av=Xe,nv=Je,Du=pe,ov=vs,lv=di,uv=_u,Iu=function(){},dv=[],Ru=lv("Reflect","construct"),Rn=/^\s*(?:class|function)\b/,cv=av(Rn.exec),hv=!Rn.exec(Iu),Ki=function(e){if(!Du(e))return!1;try{return Ru(Iu,dv,e),!0}catch(t){return!1}},Cu=function(e){if(!Du(e))return!1;switch(ov(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return hv||!!cv(Rn,uv(e))}catch(t){return!0}};Cu.sham=!0;var fv=!Ru||nv(function(){var s;return Ki(Ki.call)||!Ki(Object)||!Ki(function(){s=!0})||s})?Cu:Ki,pv=fv,mv=vr,vv=TypeError,gv=function(s){if(pv(s))return s;throw vv(mv(s)+" is not a constructor")},Uo=Lt,bv=gv,Sv=hs,yv=Ie,Tv=yv("species"),Lu=function(s,e){var t=Uo(s).constructor,i;return t===void 0||Sv(i=Uo(t)[Tv])?e:bv(i)},Ev=Xe,$v=Ev([].slice),kv=TypeError,wv=function(s,e){if(s<e)throw kv("Not enough arguments");return s},Av=mr,xu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Av),He=Ee,Pv=nu,_v=yr,jo=pe,Dv=mt,Nu=Je,Ho=mu,Iv=$v,Go=gn,Rv=wv,Cv=xu,Lv=Tr,Xa=He.setImmediate,Za=He.clearImmediate,xv=He.process,la=He.Dispatch,Nv=He.Function,Yo=He.MessageChannel,Ov=He.String,ua=0,rs={},zo="onreadystatechange",ls,ti,da,ca;Nu(function(){ls=He.location});var Cn=function(s){if(Dv(rs,s)){var e=rs[s];delete rs[s],e()}},ha=function(s){return function(){Cn(s)}},qo=function(s){Cn(s.data)},Wo=function(s){He.postMessage(Ov(s),ls.protocol+"//"+ls.host)};(!Xa||!Za)&&(Xa=function(e){Rv(arguments.length,1);var t=jo(e)?e:Nv(e),i=Iv(arguments,1);return rs[++ua]=function(){Pv(t,void 0,i)},ti(ua),ua},Za=function(e){delete rs[e]},Lv?ti=function(s){xv.nextTick(ha(s))}:la&&la.now?ti=function(s){la.now(ha(s))}:Yo&&!Cv?(da=new Yo,ca=da.port2,da.port1.onmessage=qo,ti=_v(ca.postMessage,ca)):He.addEventListener&&jo(He.postMessage)&&!He.importScripts&&ls&&ls.protocol!=="file:"&&!Nu(Wo)?(ti=Wo,He.addEventListener("message",qo,!1)):zo in Go("script")?ti=function(s){Ho.appendChild(Go("script"))[zo]=function(){Ho.removeChild(this),Cn(s)}}:ti=function(s){setTimeout(ha(s),0)});var Ou={set:Xa,clear:Za},Bu=function(){this.head=null,this.tail=null};Bu.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var Mu=Bu,Bv=mr,Mv=/ipad|iphone|ipod/i.test(Bv)&&typeof Pebble!="undefined",Vv=mr,Fv=/web0s(?!.*chrome)/i.test(Vv),oi=Ee,Qo=yr,Uv=$n.f,fa=Ou.set,jv=Mu,Hv=xu,Gv=Mv,Yv=Fv,pa=Tr,Ko=oi.MutationObserver||oi.WebKitMutationObserver,Jo=oi.document,Xo=oi.process,Rs=oi.Promise,Zo=Uv(oi,"queueMicrotask"),en=Zo&&Zo.value,Si,ma,va,Cs,el;if(!en){var Ls=new jv,xs=function(){var s,e;for(pa&&(s=Xo.domain)&&s.exit();e=Ls.get();)try{e()}catch(t){throw Ls.head&&Si(),t}s&&s.enter()};!Hv&&!pa&&!Yv&&Ko&&Jo?(ma=!0,va=Jo.createTextNode(""),new Ko(xs).observe(va,{characterData:!0}),Si=function(){va.data=ma=!ma}):!Gv&&Rs&&Rs.resolve?(Cs=Rs.resolve(void 0),Cs.constructor=Rs,el=Qo(Cs.then,Cs),Si=function(){el(xs)}):pa?Si=function(){Xo.nextTick(xs)}:(fa=Qo(fa,oi),Si=function(){fa(xs)}),en=function(s){Ls.head||Si(),Ls.add(s)}}var zv=en,qv=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},Ln=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Wv=Ee,Oi=Wv.Promise,Vu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Qv=Vu,Kv=Tr,Jv=!Qv&&!Kv&&typeof window=="object"&&typeof document=="object",Xv=Ee,as=Oi,Zv=pe,eg=cu,tg=_u,ig=Ie,sg=Jv,rg=Vu,ga=Kl,tl=as&&as.prototype,ag=ig("species"),tn=!1,Fu=Zv(Xv.PromiseRejectionEvent),ng=eg("Promise",function(){var s=tg(as),e=s!==String(as);if(!e&&ga===66||!(tl.catch&&tl.finally))return!0;if(!ga||ga<51||!/native code/.test(s)){var t=new as(function(n){n(1)}),i=function(n){n(function(){},function(){})},r=t.constructor={};if(r[ag]=i,tn=t.then(function(){})instanceof i,!tn)return!0}return!e&&(sg||rg)&&!Fu}),gs={CONSTRUCTOR:ng,REJECTION_EVENT:Fu,SUBCLASSING:tn},Bi={},il=ci,og=TypeError,lg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw og("Bad Promise constructor");e=i,t=r}),this.resolve=il(e),this.reject=il(t)};Bi.f=function(s){return new lg(s)};var ug=at,Zs=Tr,Ft=Ee,bs=Ge,dg=Pn,cg=Dn,hg=Xm,fg=ci,sn=pe,pg=Ct,mg=tv,vg=Lu,Uu=Ou.set,xn=zv,gg=qv,bg=Ln,Sg=Mu,ju=ru,rn=Oi,Nn=gs,Hu=Bi,Er="Promise",Gu=Nn.CONSTRUCTOR,yg=Nn.REJECTION_EVENT;Nn.SUBCLASSING;var ba=ju.getterFor(Er),Tg=ju.set,Eg=rn&&rn.prototype,wi=rn,Sa=Eg,Yu=Ft.TypeError,an=Ft.document,On=Ft.process,nn=Hu.f,$g=nn,kg=!!(an&&an.createEvent&&Ft.dispatchEvent),zu="unhandledrejection",wg="rejectionhandled",sl=0,qu=1,Ag=2,Bn=1,Wu=2,Ns,rl,Pg,Qu=function(s){var e;return pg(s)&&sn(e=s.then)?e:!1},Ku=function(s,e){var t=e.value,i=e.state==qu,r=i?s.ok:s.fail,n=s.resolve,o=s.reject,l=s.domain,d,u,c;try{r?(i||(e.rejection===Wu&&Dg(e),e.rejection=Bn),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===s.promise?o(Yu("Promise-chain cycle")):(u=Qu(d))?bs(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Ju=function(s,e){s.notified||(s.notified=!0,xn(function(){for(var t=s.reactions,i;i=t.get();)Ku(i,s);s.notified=!1,e&&!s.rejection&&_g(s)}))},Xu=function(s,e,t){var i,r;kg?(i=an.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Ft.dispatchEvent(i)):i={promise:e,reason:t},!yg&&(r=Ft["on"+s])?r(i):s===zu&&gg("Unhandled promise rejection",t)},_g=function(s){bs(Uu,Ft,function(){var e=s.facade,t=s.value,i=al(s),r;if(i&&(r=bg(function(){Zs?On.emit("unhandledRejection",t,e):Xu(zu,e,t)}),s.rejection=Zs||al(s)?Wu:Bn,r.error))throw r.value})},al=function(s){return s.rejection!==Bn&&!s.parent},Dg=function(s){bs(Uu,Ft,function(){var e=s.facade;Zs?On.emit("rejectionHandled",e):Xu(wg,e,s.value)})},Ai=function(s,e,t){return function(i){s(e,i,t)}},Di=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=Ag,Ju(s,!0))},on=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw Yu("Promise can't be resolved itself");var i=Qu(e);i?xn(function(){var r={done:!1};try{bs(i,e,Ai(on,r,s),Ai(Di,r,s))}catch(n){Di(r,n,s)}}):(s.value=e,s.state=qu,Ju(s,!1))}catch(r){Di({done:!1},r,s)}}};Gu&&(wi=function(e){mg(this,Sa),fg(e),bs(Ns,this);var t=ba(this);try{e(Ai(on,t),Ai(Di,t))}catch(i){Di(t,i)}},Sa=wi.prototype,Ns=function(e){Tg(this,{type:Er,done:!1,notified:!1,parent:!1,reactions:new Sg,rejection:!1,state:sl,value:void 0})},Ns.prototype=dg(Sa,"then",function(e,t){var i=ba(this),r=nn(vg(this,wi));return i.parent=!0,r.ok=sn(e)?e:!0,r.fail=sn(t)&&t,r.domain=Zs?On.domain:void 0,i.state==sl?i.reactions.add(r):xn(function(){Ku(r,i)}),r.promise}),rl=function(){var s=new Ns,e=ba(s);this.promise=s,this.resolve=Ai(on,e),this.reject=Ai(Di,e)},Hu.f=nn=function(s){return s===wi||s===Pg?new rl(s):$g(s)});ug({global:!0,constructor:!0,wrap:!0,forced:Gu},{Promise:wi});cg(wi,Er,!1,!0);hg(Er);var Ig=Ie,Zu=Ig("iterator"),ed=!1;try{var Rg=0,nl={next:function(){return{done:!!Rg++}},return:function(){ed=!0}};nl[Zu]=function(){return this},Array.from(nl,function(){throw 2})}catch(s){}var Cg=function(s,e){if(!e&&!ed)return!1;var t=!1;try{var i={};i[Zu]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},Lg=Oi,xg=Cg,Ng=gs.CONSTRUCTOR,td=Ng||!xg(function(s){Lg.all(s).then(void 0,function(){})}),Og=at,Bg=Ge,Mg=ci,Vg=Bi,Fg=Ln,Ug=In,jg=td;Og({target:"Promise",stat:!0,forced:jg},{all:function(e){var t=this,i=Vg.f(t),r=i.resolve,n=i.reject,o=Fg(function(){var l=Mg(t.resolve),d=[],u=0,c=1;Ug(e,function(h){var f=u++,p=!1;c++,Bg(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),i.promise}});var Hg=at,Gg=gs.CONSTRUCTOR,ol=Oi;ol&&ol.prototype;Hg({target:"Promise",proto:!0,forced:Gg,real:!0},{catch:function(s){return this.then(void 0,s)}});var Yg=at,zg=Ge,qg=ci,Wg=Bi,Qg=Ln,Kg=In,Jg=td;Yg({target:"Promise",stat:!0,forced:Jg},{race:function(e){var t=this,i=Wg.f(t),r=i.reject,n=Qg(function(){var o=qg(t.resolve);Kg(e,function(l){zg(o,t,l).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}});var Xg=at,Zg=Ge,eb=Bi,tb=gs.CONSTRUCTOR;Xg({target:"Promise",stat:!0,forced:tb},{reject:function(e){var t=eb.f(this);return Zg(t.reject,void 0,e),t.promise}});var ib=Lt,sb=Ct,rb=Bi,id=function(s,e){if(ib(s),sb(e)&&e.constructor===s)return e;var t=rb.f(s),i=t.resolve;return i(e),t.promise},ab=at,nb=di,ob=Bc,lb=Oi,ub=gs.CONSTRUCTOR,db=id,cb=nb("Promise"),hb=!ub;ab({target:"Promise",stat:!0,forced:ob},{resolve:function(e){return db(hb&&this===cb?lb:this,e)}});var fb=at,ln=Oi,pb=Je,mb=di,vb=pe,gb=Lu,ll=id,bb=ln&&ln.prototype,Sb=!!ln&&pb(function(){bb.finally.call({then:function(){}},function(){})});fb({target:"Promise",proto:!0,real:!0,forced:Sb},{finally:function(s){var e=gb(this,mb("Promise")),t=vb(s);return this.then(t?function(i){return ll(e,s()).then(function(){return i})}:s,t?function(i){return ll(e,s()).then(function(){throw i})}:s)}});var yb=di,Mn=yb,Tb=Mn,Eb=Tb("Promise","finally"),$b=Eb,kb=$b,wb=kb,Ab=wb,Ss=hr(Ab),ae;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ae||(ae={}));var _e=(s,e=0,t=ae.OFFSET_P)=>{switch(t){case ae.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ae.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case ae.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:a.assertNever(t)}return s};const er=(s,e)=>{var t;switch(e){case ae.OFFSET_P:return NaN;case ae.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case ae.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var A=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ee{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||a.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Pb=s=>{switch(s){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(s)}};var H;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(H||(H={}));const _b=5,Db=5,Ib=500,ul=7e3;class Rb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new ee(H.STOPPED),this.syncPlayback=()=>{const i=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: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===Y.Requested&&i!==H.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case H.PLAYING:case H.PAUSED:case H.READY:break;case H.STOPPED:this.videoState.startTransitionTo(H.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case H.PLAYING:break;case H.PAUSED:this.videoState.startTransitionTo(H.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case H.READY:this.videoState.startTransitionTo(H.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case H.STOPPED:this.videoState.startTransitionTo(H.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case H.PLAYING:this.videoState.startTransitionTo(H.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case H.PAUSED:break;case H.READY:this.videoState.startTransitionTo(H.PAUSED),this.videoState.setState(H.PAUSED);break;case H.STOPPED:this.videoState.startTransitionTo(H.READY),this.prepare();break;default:a.assertNever(i)}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(Pb(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(Ib)).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===Y.Applying||Math.abs(l-n)>_b)&&r.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Db&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),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 i=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(i,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(H.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(H.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===H.PAUSED||e===H.PLAYING)&&(this.videoState.setState(H.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===H.PLAYING||e===H.PAUSED)&&(this.videoState.setState(H.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===H.READY&&this.videoState.setState(H.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==H.STOPPED&&this.videoState.setState(H.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i: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:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[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=i[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=i[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=i[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=i[e];a.assertNonNullable(c),r=_e(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 i=this.params.desiredState.seekState.getState();return i.state===Y.Applying||i.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(ul).subscribe(()=>n(`timeout(${ul})`)))});Ss(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.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 Cb=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Lb=s=>{const e=new a.ValueSubject(1/0),t=new a.Subject,i=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 S=ni(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),T=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=T!=null?T:v*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(b={1:!0,0:!1}[S["x-reused"]])!==null&&b!==void 0?b:void 0;i.next(g),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.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$:i}},Ut=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},xb=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Ut}),!0),Nb=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const rt=(s,e,t,{equal:i=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=s.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},Ht=(s,e,t)=>rt(e,()=>s.loop,i=>{a.isNonNullable(i)&&(s.loop=i)},{onError:t}),vt=(s,e,t,i)=>rt(e,()=>({muted:s.muted,volume:s.volume}),r=>{a.isNonNullable(r)&&(s.muted=r.muted,s.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:i}),xt=(s,e,t,i)=>rt(e,()=>s.playbackRate,r=>{a.isNonNullable(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ob=s=>["__",s.language,s.label].join("|"),Bb=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class nt{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,i){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(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(rt(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(rt(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(rt(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(rt(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 i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),a.filterChanged((i,r)=>i.length===r.length&&i.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:i})=>i==="showing")),a.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),a.filterChanged()).subscribe(this.current$));const t=i=>{var r,n;return this.applyCueSettings((n=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(i=>{var r,n;(r=i.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=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;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(nt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:n}=e,o=e.id?e.id:Ob(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(i=this.internalTracks.get(o))===null||i===void 0?void 0:i.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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!Bb(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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 Vn=s=>{s.removeAttribute("src"),s.load()},Mb=s=>{try{s.pause(),s.playbackRate=0,Vn(s),s.remove()}catch(e){console.error(e)}};class Vb{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 un=window.WeakMap?new WeakMap:new Vb,gt=s=>{let e=s.querySelector("video");const t=!!e;return e?Vn(e):(e=document.createElement("video"),s.appendChild(e)),un.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=s=>{const e=un.get(s);un.delete(s),e?Vn(s):Mb(s)};class ys{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 sd=s=>{var e;let t=s;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},dl=s=>{const e=sd(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Fb=s=>{const e=sd(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},dn=3;class Ub{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<dn&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||dn))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(r,e):r<e&&n>t?(i(t,n),i(r,e)):i(r,n))})}destroy(){this._buffer=[]}}var rd=(s,e,t=dn)=>{let i=0,r=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,r=l,!t)return{from:i,to:r};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=r&&(r=s.end(d))}}return{from:i,to:r}};const St=s=>{const e=v=>a.fromEvent(s,v).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=a.merge(...t.map(v=>a.fromEvent(s,v))).pipe(a.map(v=>v.type==="ended"?s.readyState<2:s.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(s,"progress"),a.fromEvent(s,"timeupdate")).pipe(a.map(()=>rd(s.buffered,s.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(s,"volumechange").pipe(a.map(()=>({muted:s.muted,volume:s.volume}))),d=a.fromEvent(s,"ratechange").pipe(a.map(()=>s.playbackRate)),u=a.fromEvent(s,"error").pipe(a.filter(()=>!!(s.error||s.played.length)),a.map(()=>{var v;const T=s.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),c=a.fromEvent(s,"timeupdate").pipe(a.map(()=>s.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(v=>{s.loop&&a.isNonNullable(p)&&a.isNonNullable(v)&&p>=s.duration-f&&v<=f&&h.next(p),p=v});const m=a.fromEvent(s,"enterpictureinpicture"),b=a.fromEvent(s,"leavepictureinpicture"),S=new a.ValueSubject(Fb(s));m.subscribe(()=>S.next(!0)),b.subscribe(()=>S.next(!1));const g=new a.ValueSubject(dl(s));return a.fromEvent(s,"fullscreenchange").pipe(a.map(()=>dl(s))).subscribe(g),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!s.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(s,"durationchange").pipe(a.map(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:S,inFullscreen$:g}},$r=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var jb=at,Hb=br,Gb=An,Yb=wn;jb({target:"Array",proto:!0},{at:function(e){var t=Hb(this),i=Gb(t),r=Yb(e),n=r>=0?r:i+r;return n<0||n>=i?void 0:t[n]}});var zb=Mn,qb=zb("Array","at"),Wb=qb,Qb=Wb,Kb=Qb,Jb=Kb,be=hr(Jb);let Fn=!1,_t={};const Xb=s=>{Fn=s},Zb=()=>{_t={}},eS=s=>{s(_t)},Os=(s,e)=>{var t;Fn&&(_t.meta=(t=_t.meta)!==null&&t!==void 0?t:{},_t.meta[s]=e)};class ct{constructor(e){this.name=e}next(e){var t,i;if(!Fn)return;_t.series=(t=_t.series)!==null&&t!==void 0?t:{};const r=(i=_t.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),_t.series[this.name]=r}}var si;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(si||(si={}));const tS=new ct("best_bitrate"),iS=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class ad{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const sS='Assertion "ABR Tracks is empty array" failed',hi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,b,S;a.assertNotEmptyArray(s,sS);const g=i.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*g*i.containerSizeFactor,height:e.height*g*i.containerSizeFactor},v=y&&a.videoSizeToQuality(y),T=i.considerPlaybackRate&&a.isNonNullable(l)?l:1,E=s.filter(R=>!a.isInvariantQuality(R.quality)).sort((R,_)=>a.isHigher(R.quality,_.quality)?-1:1),P=(p=be(E,-1))===null||p===void 0?void 0:p.quality,N=(m=be(E,0))===null||m===void 0?void 0:m.quality,V=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&a.isLower(r.max,r.min)||a.isNonNullable(r.min)&&N&&a.isHigher(r.min,N)||a.isNonNullable(r.max)&&P&&a.isLower(r.max,P),x=T*iS(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},D=E.filter(R=>(v?a.isLower(R.quality,v):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(R.bitrate)?t-n>=R.bitrate*x:!0)?i.lazyQualitySwitch&&a.isNonNullable(i.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&a.isHigher(R.quality,d.quality)?(B[R.quality]=si.Buffer,!1):!!c&&a.isHigherOrEqual(R.quality,c)?(B[R.quality]=si.DroppedFramesLimit,!1):V||(a.isNullable(r.max)||a.isLowerOrEqual(R.quality,r.max))&&(a.isNullable(r.min)||a.isHigherOrEqual(R.quality,r.min))?!0:(B[R.quality]=si.FitsQualityLimits,!1):(B[R.quality]=si.FitsThroughput,!1):(B[R.quality]=si.FitsContainer,!1))[0];D&&D.bitrate&&tS.next(D.bitrate);const I=(b=D!=null?D:E[Math.ceil((E.length-1)/2)])!==null&&b!==void 0?b:s[0];I.quality!==((S=u==null?void 0:u.last)===null||S===void 0?void 0:S.quality)&&h({message:`
|
|
6
|
+
"use strict";var Cd=Object.create;var zn=Object.defineProperty;var Ld=Object.getOwnPropertyDescriptor;var xd=Object.getOwnPropertyNames;var Nd=Object.getPrototypeOf,Od=Object.prototype.hasOwnProperty;var Bd=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xd(e))!Od.call(s,r)&&r!==t&&zn(s,r,{get:()=>e[r],enumerable:!(i=Ld(e,r))||i.enumerable});return s};var qn=(s,e,t)=>(t=s!=null?Cd(Nd(s)):{},Bd(e||!s||!s.__esModule?zn(t,"default",{value:s,enumerable:!0}):t,s));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js");const Fl="2.0.98-dev.a3af0042.0";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var Ae;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var Y;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(Y||(Y={}));exports.Surface=void 0;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(exports.Surface||(exports.Surface={}));function F(s,e,t,i){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(i.next(c))}catch(h){o(h)}}function d(c){try{u(i.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(l,d)}u((i=i.apply(s,e||[])).next())})}function w(s){return this instanceof w?(this.v=s,this):new w(s)}function Z(s,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var i=t.apply(s,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){i[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(i[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof w?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 Md=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Vd{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 i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)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||Md("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 i,r,n;(n=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.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),i=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(i,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=i.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(i,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([i.getCastState()])).pipe(a.filterChanged(),a.map(Fd),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=i.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,i,r;try{t=cast.framework.CastContext.getInstance(),i=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:i,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Fd=s=>{switch(s){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(s)}};var Fr=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function hr(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Je=function(s){try{return!!s()}catch(e){return!0}},Ud=Je,fr=!Ud(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Ul=fr,jl=Function.prototype,ja=jl.call,jd=Ul&&jl.bind.bind(ja,ja),Xe=Ul?jd:function(s){return function(){return ja.apply(s,arguments)}},Hl=Xe,Hd=Hl({}.toString),Gd=Hl("".slice),cs=function(s){return Gd(Hd(s),8,-1)},Yd=Xe,zd=Je,qd=cs,Ur=Object,Wd=Yd("".split),Qd=zd(function(){return!Ur("z").propertyIsEnumerable(0)})?function(s){return qd(s)=="String"?Wd(s,""):Ur(s)}:Ur,hs=function(s){return s==null},Kd=hs,Jd=TypeError,vn=function(s){if(Kd(s))throw Jd("Can't call method on "+s);return s},Xd=Qd,Zd=vn,fs=function(s){return Xd(Zd(s))},Ni={},$s=function(s){return s&&s.Math==Math&&s},Ee=$s(typeof globalThis=="object"&&globalThis)||$s(typeof window=="object"&&window)||$s(typeof self=="object"&&self)||$s(typeof Fr=="object"&&Fr)||function(){return this}()||Fr||Function("return this")(),Ha=typeof document=="object"&&document.all,ec=typeof Ha=="undefined"&&Ha!==void 0,Gl={all:Ha,IS_HTMLDDA:ec},Yl=Gl,tc=Yl.all,pe=Yl.IS_HTMLDDA?function(s){return typeof s=="function"||s===tc}:function(s){return typeof s=="function"},ic=Ee,sc=pe,Wn=ic.WeakMap,rc=sc(Wn)&&/native code/.test(String(Wn)),Qn=pe,zl=Gl,ac=zl.all,Ct=zl.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Qn(s)||s===ac}:function(s){return typeof s=="object"?s!==null:Qn(s)},nc=Je,jt=!nc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ui={},oc=Ee,Kn=Ct,Ga=oc.document,lc=Kn(Ga)&&Kn(Ga.createElement),gn=function(s){return lc?Ga.createElement(s):{}},uc=jt,dc=Je,cc=gn,ql=!uc&&!dc(function(){return Object.defineProperty(cc("div"),"a",{get:function(){return 7}}).a!=7}),hc=jt,fc=Je,Wl=hc&&fc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),pc=Ct,mc=String,vc=TypeError,Lt=function(s){if(pc(s))return s;throw vc(mc(s)+" is not an object")},gc=fr,ks=Function.prototype.call,Ge=gc?ks.bind(ks):function(){return ks.apply(ks,arguments)},bn={},jr=bn,Hr=Ee,bc=pe,Jn=function(s){return bc(s)?s:void 0},di=function(s,e){return arguments.length<2?Jn(jr[s])||Jn(Hr[s]):jr[s]&&jr[s][e]||Hr[s]&&Hr[s][e]},Sc=Xe,pr=Sc({}.isPrototypeOf),mr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Ql=Ee,Gr=mr,Xn=Ql.process,Zn=Ql.Deno,eo=Xn&&Xn.versions||Zn&&Zn.version,to=eo&&eo.v8,st,Ks;to&&(st=to.split("."),Ks=st[0]>0&&st[0]<4?1:+(st[0]+st[1]));!Ks&&Gr&&(st=Gr.match(/Edge\/(\d+)/),(!st||st[1]>=74)&&(st=Gr.match(/Chrome\/(\d+)/),st&&(Ks=+st[1])));var Kl=Ks,io=Kl,yc=Je,Tc=Ee,Ec=Tc.String,Jl=!!Object.getOwnPropertySymbols&&!yc(function(){var s=Symbol();return!Ec(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&io&&io<41}),$c=Jl,Xl=$c&&!Symbol.sham&&typeof Symbol.iterator=="symbol",kc=di,wc=pe,Ac=pr,Pc=Xl,_c=Object,Zl=Pc?function(s){return typeof s=="symbol"}:function(s){var e=kc("Symbol");return wc(e)&&Ac(e.prototype,_c(s))},Dc=String,vr=function(s){try{return Dc(s)}catch(e){return"Object"}},Ic=pe,Rc=vr,Cc=TypeError,ci=function(s){if(Ic(s))return s;throw Cc(Rc(s)+" is not a function")},Lc=ci,xc=hs,gr=function(s,e){var t=s[e];return xc(t)?void 0:Lc(t)},Yr=Ge,zr=pe,qr=Ct,Nc=TypeError,Oc=function(s,e){var t,i;if(e==="string"&&zr(t=s.toString)&&!qr(i=Yr(t,s))||zr(t=s.valueOf)&&!qr(i=Yr(t,s))||e!=="string"&&zr(t=s.toString)&&!qr(i=Yr(t,s)))return i;throw Nc("Can't convert object to primitive value")},eu={exports:{}},Bc=!0,so=Ee,Mc=Object.defineProperty,Vc=function(s,e){try{Mc(so,s,{value:e,configurable:!0,writable:!0})}catch(t){so[s]=e}return e},Fc=Ee,Uc=Vc,ro="__core-js_shared__",jc=Fc[ro]||Uc(ro,{}),Sn=jc,ao=Sn;(eu.exports=function(s,e){return ao[s]||(ao[s]=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 tu=eu.exports,Hc=vn,Gc=Object,br=function(s){return Gc(Hc(s))},Yc=Xe,zc=br,qc=Yc({}.hasOwnProperty),mt=Object.hasOwn||function(e,t){return qc(zc(e),t)},Wc=Xe,Qc=0,Kc=Math.random(),Jc=Wc(1 .toString),iu=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Jc(++Qc+Kc,36)},Xc=Ee,Zc=tu,no=mt,eh=iu,th=Jl,ih=Xl,ki=Xc.Symbol,Wr=Zc("wks"),sh=ih?ki.for||ki:ki&&ki.withoutSetter||eh,Ie=function(s){return no(Wr,s)||(Wr[s]=th&&no(ki,s)?ki[s]:sh("Symbol."+s)),Wr[s]},rh=Ge,oo=Ct,lo=Zl,ah=gr,nh=Oc,oh=Ie,lh=TypeError,uh=oh("toPrimitive"),dh=function(s,e){if(!oo(s)||lo(s))return s;var t=ah(s,uh),i;if(t){if(e===void 0&&(e="default"),i=rh(t,s,e),!oo(i)||lo(i))return i;throw lh("Can't convert object to primitive value")}return e===void 0&&(e="number"),nh(s,e)},ch=dh,hh=Zl,yn=function(s){var e=ch(s,"string");return hh(e)?e:e+""},fh=jt,ph=ql,mh=Wl,ws=Lt,uo=yn,vh=TypeError,Qr=Object.defineProperty,gh=Object.getOwnPropertyDescriptor,Kr="enumerable",Jr="configurable",Xr="writable";ui.f=fh?mh?function(e,t,i){if(ws(e),t=uo(t),ws(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xr in i&&!i[Xr]){var r=gh(e,t);r&&r[Xr]&&(e[t]=i.value,i={configurable:Jr in i?i[Jr]:r[Jr],enumerable:Kr in i?i[Kr]:r[Kr],writable:!1})}return Qr(e,t,i)}:Qr:function(e,t,i){if(ws(e),t=uo(t),ws(i),ph)try{return Qr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw vh("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Sr=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},bh=jt,Sh=ui,yh=Sr,ps=bh?function(s,e,t){return Sh.f(s,e,yh(1,t))}:function(s,e,t){return s[e]=t,s},Th=tu,Eh=iu,co=Th("keys"),Tn=function(s){return co[s]||(co[s]=Eh(s))},En={},$h=rc,su=Ee,kh=Ct,wh=ps,Zr=mt,ea=Sn,Ah=Tn,Ph=En,ho="Object already initialized",Ya=su.TypeError,_h=su.WeakMap,Js,os,Xs,Dh=function(s){return Xs(s)?os(s):Js(s,{})},Ih=function(s){return function(e){var t;if(!kh(e)||(t=os(e)).type!==s)throw Ya("Incompatible receiver, "+s+" required");return t}};if($h||ea.state){var lt=ea.state||(ea.state=new _h);lt.get=lt.get,lt.has=lt.has,lt.set=lt.set,Js=function(s,e){if(lt.has(s))throw Ya(ho);return e.facade=s,lt.set(s,e),e},os=function(s){return lt.get(s)||{}},Xs=function(s){return lt.has(s)}}else{var vi=Ah("state");Ph[vi]=!0,Js=function(s,e){if(Zr(s,vi))throw Ya(ho);return e.facade=s,wh(s,vi,e),e},os=function(s){return Zr(s,vi)?s[vi]:{}},Xs=function(s){return Zr(s,vi)}}var ru={set:Js,get:os,has:Xs,enforce:Dh,getterFor:Ih},Rh=fr,au=Function.prototype,fo=au.apply,po=au.call,nu=typeof Reflect=="object"&&Reflect.apply||(Rh?po.bind(fo):function(){return po.apply(fo,arguments)}),Ch=cs,Lh=Xe,ou=function(s){if(Ch(s)==="Function")return Lh(s)},$n={},lu={},uu={}.propertyIsEnumerable,du=Object.getOwnPropertyDescriptor,xh=du&&!uu.call({1:2},1);lu.f=xh?function(e){var t=du(this,e);return!!t&&t.enumerable}:uu;var Nh=jt,Oh=Ge,Bh=lu,Mh=Sr,Vh=fs,Fh=yn,Uh=mt,jh=ql,mo=Object.getOwnPropertyDescriptor;$n.f=Nh?mo:function(e,t){if(e=Vh(e),t=Fh(t),jh)try{return mo(e,t)}catch(i){}if(Uh(e,t))return Mh(!Oh(Bh.f,e,t),e[t])};var Hh=Je,Gh=pe,Yh=/#|\.prototype\./,ms=function(s,e){var t=qh[zh(s)];return t==Qh?!0:t==Wh?!1:Gh(e)?Hh(e):!!e},zh=ms.normalize=function(s){return String(s).replace(Yh,".").toLowerCase()},qh=ms.data={},Wh=ms.NATIVE="N",Qh=ms.POLYFILL="P",cu=ms,vo=ou,Kh=ci,Jh=fr,Xh=vo(vo.bind),yr=function(s,e){return Kh(s),e===void 0?s:Jh?Xh(s,e):function(){return s.apply(e,arguments)}},As=Ee,Zh=nu,ef=ou,tf=pe,sf=$n.f,rf=cu,gi=bn,af=yr,bi=ps,go=mt,nf=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Zh(s,this,arguments)};return e.prototype=s.prototype,e},at=function(s,e){var t=s.target,i=s.global,r=s.stat,n=s.proto,o=i?As:r?As[t]:(As[t]||{}).prototype,l=i?gi:gi[t]||bi(gi,t,{})[t],d=l.prototype,u,c,h,f,p,m,b,S,g;for(f in e)u=rf(i?f:t+(r?".":"#")+f,s.forced),c=!u&&o&&go(o,f),m=l[f],c&&(s.dontCallGetSet?(g=sf(o,f),b=g&&g.value):b=o[f]),p=c&&b?b:e[f],!(c&&typeof m==typeof p)&&(s.bind&&c?S=af(p,As):s.wrap&&c?S=nf(p):n&&tf(p)?S=ef(p):S=p,(s.sham||p&&p.sham||m&&m.sham)&&bi(S,"sham",!0),bi(l,f,S),n&&(h=t+"Prototype",go(gi,h)||bi(gi,h,{}),bi(gi[h],f,p),s.real&&d&&(u||!d[f])&&bi(d,f,p)))},za=jt,of=mt,hu=Function.prototype,lf=za&&Object.getOwnPropertyDescriptor,kn=of(hu,"name"),uf=kn&&function(){}.name==="something",df=kn&&(!za||za&&lf(hu,"name").configurable),cf={EXISTS:kn,PROPER:uf,CONFIGURABLE:df},fu={},hf=Math.ceil,ff=Math.floor,pf=Math.trunc||function(e){var t=+e;return(t>0?ff:hf)(t)},mf=pf,wn=function(s){var e=+s;return e!==e||e===0?0:mf(e)},vf=wn,gf=Math.max,bf=Math.min,Sf=function(s,e){var t=vf(s);return t<0?gf(t+e,0):bf(t,e)},yf=wn,Tf=Math.min,Ef=function(s){return s>0?Tf(yf(s),9007199254740991):0},$f=Ef,An=function(s){return $f(s.length)},kf=fs,wf=Sf,Af=An,bo=function(s){return function(e,t,i){var r=kf(e),n=Af(r),o=wf(i,n),l;if(s&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in r)&&r[o]===t)return s||o||0;return!s&&-1}},Pf={includes:bo(!0),indexOf:bo(!1)},_f=Xe,ta=mt,Df=fs,If=Pf.indexOf,Rf=En,So=_f([].push),Cf=function(s,e){var t=Df(s),i=0,r=[],n;for(n in t)!ta(Rf,n)&&ta(t,n)&&So(r,n);for(;e.length>i;)ta(t,n=e[i++])&&(~If(r,n)||So(r,n));return r},pu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Lf=Cf,xf=pu,Nf=Object.keys||function(e){return Lf(e,xf)},Of=jt,Bf=Wl,Mf=ui,Vf=Lt,Ff=fs,Uf=Nf;fu.f=Of&&!Bf?Object.defineProperties:function(e,t){Vf(e);for(var i=Ff(t),r=Uf(t),n=r.length,o=0,l;n>o;)Mf.f(e,l=r[o++],i[l]);return e};var jf=di,mu=jf("document","documentElement"),Hf=Lt,Gf=fu,yo=pu,Yf=En,zf=mu,qf=gn,Wf=Tn,To=">",Eo="<",qa="prototype",Wa="script",vu=Wf("IE_PROTO"),ia=function(){},gu=function(s){return Eo+Wa+To+s+Eo+"/"+Wa+To},$o=function(s){s.write(gu("")),s.close();var e=s.parentWindow.Object;return s=null,e},Qf=function(){var s=qf("iframe"),e="java"+Wa+":",t;return s.style.display="none",zf.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(gu("document.F=Object")),t.close(),t.F},Ps,zs=function(){try{Ps=new ActiveXObject("htmlfile")}catch(e){}zs=typeof document!="undefined"?document.domain&&Ps?$o(Ps):Qf():$o(Ps);for(var s=yo.length;s--;)delete zs[qa][yo[s]];return zs()};Yf[vu]=!0;var bu=Object.create||function(e,t){var i;return e!==null?(ia[qa]=Hf(e),i=new ia,ia[qa]=null,i[vu]=e):i=zs(),t===void 0?i:Gf.f(i,t)},Kf=Je,Jf=!Kf(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Xf=mt,Zf=pe,ep=br,tp=Tn,ip=Jf,ko=tp("IE_PROTO"),Qa=Object,sp=Qa.prototype,Su=ip?Qa.getPrototypeOf:function(s){var e=ep(s);if(Xf(e,ko))return e[ko];var t=e.constructor;return Zf(t)&&e instanceof t?t.prototype:e instanceof Qa?sp:null},rp=ps,Pn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:rp(s,e,t),s},ap=Je,np=pe,op=Ct,lp=bu,wo=Su,up=Pn,dp=Ie,Ka=dp("iterator"),yu=!1,Dt,sa,ra;[].keys&&(ra=[].keys(),"next"in ra?(sa=wo(wo(ra)),sa!==Object.prototype&&(Dt=sa)):yu=!0);var cp=!op(Dt)||ap(function(){var s={};return Dt[Ka].call(s)!==s});cp?Dt={}:Dt=lp(Dt);np(Dt[Ka])||up(Dt,Ka,function(){return this});var Tu={IteratorPrototype:Dt,BUGGY_SAFARI_ITERATORS:yu},hp=Ie,fp=hp("toStringTag"),Eu={};Eu[fp]="z";var _n=String(Eu)==="[object z]",pp=_n,mp=pe,qs=cs,vp=Ie,gp=vp("toStringTag"),bp=Object,Sp=qs(function(){return arguments}())=="Arguments",yp=function(s,e){try{return s[e]}catch(t){}},vs=pp?qs:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=yp(e=bp(s),gp))=="string"?t:Sp?qs(e):(i=qs(e))=="Object"&&mp(e.callee)?"Arguments":i},Tp=_n,Ep=vs,$p=Tp?{}.toString:function(){return"[object "+Ep(this)+"]"},kp=_n,wp=ui.f,Ap=ps,Pp=mt,_p=$p,Dp=Ie,Ao=Dp("toStringTag"),Dn=function(s,e,t,i){if(s){var r=t?s:s.prototype;Pp(r,Ao)||wp(r,Ao,{configurable:!0,value:e}),i&&!kp&&Ap(r,"toString",_p)}},Ip=Tu.IteratorPrototype,Rp=bu,Cp=Sr,Lp=Dn,xp=Ni,Np=function(){return this},Op=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Rp(Ip,{next:Cp(+!i,t)}),Lp(s,r,!1,!0),xp[r]=Np,s},Bp=at,Mp=Ge,$u=cf,Vp=Op,Fp=Su,Up=Dn,Po=Pn,jp=Ie,_o=Ni,ku=Tu,Hp=$u.PROPER;$u.CONFIGURABLE;ku.IteratorPrototype;var _s=ku.BUGGY_SAFARI_ITERATORS,aa=jp("iterator"),Do="keys",Ds="values",Io="entries",Gp=function(){return this},Yp=function(s,e,t,i,r,n,o){Vp(t,e,i);var l=function(g){if(g===r&&f)return f;if(!_s&&g in c)return c[g];switch(g){case Do:return function(){return new t(this,g)};case Ds:return function(){return new t(this,g)};case Io:return function(){return new t(this,g)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[aa]||c["@@iterator"]||r&&c[r],f=!_s&&h||l(r),p=e=="Array"&&c.entries||h,m,b,S;if(p&&(m=Fp(p.call(new s)),m!==Object.prototype&&m.next&&(Up(m,d,!0,!0),_o[d]=Gp)),Hp&&r==Ds&&h&&h.name!==Ds&&(u=!0,f=function(){return Mp(h,this)}),r)if(b={values:l(Ds),keys:n?f:l(Do),entries:l(Io)},o)for(S in b)(_s||u||!(S in c))&&Po(c,S,b[S]);else Bp({target:e,proto:!0,forced:_s||u},b);return o&&c[aa]!==f&&Po(c,aa,f,{name:r}),_o[e]=f,b},zp=function(s,e){return{value:s,done:e}},qp=fs,Ro=Ni,wu=ru;ui.f;var Wp=Yp,Is=zp,Au="Array Iterator",Qp=wu.set,Kp=wu.getterFor(Au);Wp(Array,"Array",function(s,e){Qp(this,{type:Au,target:qp(s),index:0,kind:e})},function(){var s=Kp(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,Is(void 0,!0)):t=="keys"?Is(i,!1):t=="values"?Is(e[i],!1):Is([i,e[i]],!1)},"values");Ro.Arguments=Ro.Array;var Jp=Ie,Xp=Ni,Zp=Jp("iterator"),em=Array.prototype,tm=function(s){return s!==void 0&&(Xp.Array===s||em[Zp]===s)},im=vs,Co=gr,sm=hs,rm=Ni,am=Ie,nm=am("iterator"),Pu=function(s){if(!sm(s))return Co(s,nm)||Co(s,"@@iterator")||rm[im(s)]},om=Ge,lm=ci,um=Lt,dm=vr,cm=Pu,hm=TypeError,fm=function(s,e){var t=arguments.length<2?cm(s):e;if(lm(t))return um(om(t,s));throw hm(dm(s)+" is not iterable")},pm=Ge,Lo=Lt,mm=gr,vm=function(s,e,t){var i,r;Lo(s);try{if(i=mm(s,"return"),!i){if(e==="throw")throw t;return t}i=pm(i,s)}catch(n){r=!0,i=n}if(e==="throw")throw t;if(r)throw i;return Lo(i),t},gm=yr,bm=Ge,Sm=Lt,ym=vr,Tm=tm,Em=An,xo=pr,$m=fm,km=Pu,No=vm,wm=TypeError,Ws=function(s,e){this.stopped=s,this.result=e},Oo=Ws.prototype,In=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=gm(e,i),u,c,h,f,p,m,b,S=function(y){return u&&No(u,"normal",y),new Ws(!0,y)},g=function(y){return r?(Sm(y),l?d(y[0],y[1],S):d(y[0],y[1])):l?d(y,S):d(y)};if(n)u=s.iterator;else if(o)u=s;else{if(c=km(s),!c)throw wm(ym(s)+" is not iterable");if(Tm(c)){for(h=0,f=Em(s);f>h;h++)if(p=g(s[h]),p&&xo(Oo,p))return p;return new Ws(!1)}u=$m(s,c)}for(m=n?s.next:u.next;!(b=bm(m,u)).done;){try{p=g(b.value)}catch(y){No(u,"throw",y)}if(typeof p=="object"&&p&&xo(Oo,p))return p}return new Ws(!1)},Am=yn,Pm=ui,_m=Sr,Dm=function(s,e,t){var i=Am(e);i in s?Pm.f(s,i,_m(0,t)):s[i]=t},Im=at,Rm=In,Cm=Dm;Im({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Rm(e,function(i,r){Cm(t,i,r)},{AS_ENTRIES:!0}),t}});var Lm=bn,xm=Lm.Object.fromEntries,Nm={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},Om=Nm,Bm=Ee,Mm=vs,Vm=ps,Bo=Ni,Fm=Ie,Mo=Fm("toStringTag");for(var na in Om){var Vo=Bm[na],oa=Vo&&Vo.prototype;oa&&Mm(oa)!==Mo&&Vm(oa,Mo,na),Bo[na]=Bo.Array}var Um=xm,jm=Um,Hm=jm,Gm=Hm,ni=hr(Gm),Ym=cs,Tr=typeof process!="undefined"&&Ym(process)=="process",zm=ui,qm=function(s,e,t){return zm.f(s,e,t)},Wm=di,Qm=qm,Km=Ie,Jm=jt,Fo=Km("species"),Xm=function(s){var e=Wm(s);Jm&&e&&!e[Fo]&&Qm(e,Fo,{configurable:!0,get:function(){return this}})},Zm=pr,ev=TypeError,tv=function(s,e){if(Zm(e,s))return s;throw ev("Incorrect invocation")},iv=Xe,sv=pe,Ja=Sn,rv=iv(Function.toString);sv(Ja.inspectSource)||(Ja.inspectSource=function(s){return rv(s)});var _u=Ja.inspectSource,av=Xe,nv=Je,Du=pe,ov=vs,lv=di,uv=_u,Iu=function(){},dv=[],Ru=lv("Reflect","construct"),Rn=/^\s*(?:class|function)\b/,cv=av(Rn.exec),hv=!Rn.exec(Iu),Ki=function(e){if(!Du(e))return!1;try{return Ru(Iu,dv,e),!0}catch(t){return!1}},Cu=function(e){if(!Du(e))return!1;switch(ov(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return hv||!!cv(Rn,uv(e))}catch(t){return!0}};Cu.sham=!0;var fv=!Ru||nv(function(){var s;return Ki(Ki.call)||!Ki(Object)||!Ki(function(){s=!0})||s})?Cu:Ki,pv=fv,mv=vr,vv=TypeError,gv=function(s){if(pv(s))return s;throw vv(mv(s)+" is not a constructor")},Uo=Lt,bv=gv,Sv=hs,yv=Ie,Tv=yv("species"),Lu=function(s,e){var t=Uo(s).constructor,i;return t===void 0||Sv(i=Uo(t)[Tv])?e:bv(i)},Ev=Xe,$v=Ev([].slice),kv=TypeError,wv=function(s,e){if(s<e)throw kv("Not enough arguments");return s},Av=mr,xu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Av),He=Ee,Pv=nu,_v=yr,jo=pe,Dv=mt,Nu=Je,Ho=mu,Iv=$v,Go=gn,Rv=wv,Cv=xu,Lv=Tr,Xa=He.setImmediate,Za=He.clearImmediate,xv=He.process,la=He.Dispatch,Nv=He.Function,Yo=He.MessageChannel,Ov=He.String,ua=0,rs={},zo="onreadystatechange",ls,ti,da,ca;Nu(function(){ls=He.location});var Cn=function(s){if(Dv(rs,s)){var e=rs[s];delete rs[s],e()}},ha=function(s){return function(){Cn(s)}},qo=function(s){Cn(s.data)},Wo=function(s){He.postMessage(Ov(s),ls.protocol+"//"+ls.host)};(!Xa||!Za)&&(Xa=function(e){Rv(arguments.length,1);var t=jo(e)?e:Nv(e),i=Iv(arguments,1);return rs[++ua]=function(){Pv(t,void 0,i)},ti(ua),ua},Za=function(e){delete rs[e]},Lv?ti=function(s){xv.nextTick(ha(s))}:la&&la.now?ti=function(s){la.now(ha(s))}:Yo&&!Cv?(da=new Yo,ca=da.port2,da.port1.onmessage=qo,ti=_v(ca.postMessage,ca)):He.addEventListener&&jo(He.postMessage)&&!He.importScripts&&ls&&ls.protocol!=="file:"&&!Nu(Wo)?(ti=Wo,He.addEventListener("message",qo,!1)):zo in Go("script")?ti=function(s){Ho.appendChild(Go("script"))[zo]=function(){Ho.removeChild(this),Cn(s)}}:ti=function(s){setTimeout(ha(s),0)});var Ou={set:Xa,clear:Za},Bu=function(){this.head=null,this.tail=null};Bu.prototype={add:function(s){var e={item:s,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var s=this.head;if(s){var e=this.head=s.next;return e===null&&(this.tail=null),s.item}}};var Mu=Bu,Bv=mr,Mv=/ipad|iphone|ipod/i.test(Bv)&&typeof Pebble!="undefined",Vv=mr,Fv=/web0s(?!.*chrome)/i.test(Vv),oi=Ee,Qo=yr,Uv=$n.f,fa=Ou.set,jv=Mu,Hv=xu,Gv=Mv,Yv=Fv,pa=Tr,Ko=oi.MutationObserver||oi.WebKitMutationObserver,Jo=oi.document,Xo=oi.process,Rs=oi.Promise,Zo=Uv(oi,"queueMicrotask"),en=Zo&&Zo.value,Si,ma,va,Cs,el;if(!en){var Ls=new jv,xs=function(){var s,e;for(pa&&(s=Xo.domain)&&s.exit();e=Ls.get();)try{e()}catch(t){throw Ls.head&&Si(),t}s&&s.enter()};!Hv&&!pa&&!Yv&&Ko&&Jo?(ma=!0,va=Jo.createTextNode(""),new Ko(xs).observe(va,{characterData:!0}),Si=function(){va.data=ma=!ma}):!Gv&&Rs&&Rs.resolve?(Cs=Rs.resolve(void 0),Cs.constructor=Rs,el=Qo(Cs.then,Cs),Si=function(){el(xs)}):pa?Si=function(){Xo.nextTick(xs)}:(fa=Qo(fa,oi),Si=function(){fa(xs)}),en=function(s){Ls.head||Si(),Ls.add(s)}}var zv=en,qv=function(s,e){try{arguments.length==1?console.error(s):console.error(s,e)}catch(t){}},Ln=function(s){try{return{error:!1,value:s()}}catch(e){return{error:!0,value:e}}},Wv=Ee,Oi=Wv.Promise,Vu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Qv=Vu,Kv=Tr,Jv=!Qv&&!Kv&&typeof window=="object"&&typeof document=="object",Xv=Ee,as=Oi,Zv=pe,eg=cu,tg=_u,ig=Ie,sg=Jv,rg=Vu,ga=Kl,tl=as&&as.prototype,ag=ig("species"),tn=!1,Fu=Zv(Xv.PromiseRejectionEvent),ng=eg("Promise",function(){var s=tg(as),e=s!==String(as);if(!e&&ga===66||!(tl.catch&&tl.finally))return!0;if(!ga||ga<51||!/native code/.test(s)){var t=new as(function(n){n(1)}),i=function(n){n(function(){},function(){})},r=t.constructor={};if(r[ag]=i,tn=t.then(function(){})instanceof i,!tn)return!0}return!e&&(sg||rg)&&!Fu}),gs={CONSTRUCTOR:ng,REJECTION_EVENT:Fu,SUBCLASSING:tn},Bi={},il=ci,og=TypeError,lg=function(s){var e,t;this.promise=new s(function(i,r){if(e!==void 0||t!==void 0)throw og("Bad Promise constructor");e=i,t=r}),this.resolve=il(e),this.reject=il(t)};Bi.f=function(s){return new lg(s)};var ug=at,Zs=Tr,Ft=Ee,bs=Ge,dg=Pn,cg=Dn,hg=Xm,fg=ci,sn=pe,pg=Ct,mg=tv,vg=Lu,Uu=Ou.set,xn=zv,gg=qv,bg=Ln,Sg=Mu,ju=ru,rn=Oi,Nn=gs,Hu=Bi,Er="Promise",Gu=Nn.CONSTRUCTOR,yg=Nn.REJECTION_EVENT;Nn.SUBCLASSING;var ba=ju.getterFor(Er),Tg=ju.set,Eg=rn&&rn.prototype,wi=rn,Sa=Eg,Yu=Ft.TypeError,an=Ft.document,On=Ft.process,nn=Hu.f,$g=nn,kg=!!(an&&an.createEvent&&Ft.dispatchEvent),zu="unhandledrejection",wg="rejectionhandled",sl=0,qu=1,Ag=2,Bn=1,Wu=2,Ns,rl,Pg,Qu=function(s){var e;return pg(s)&&sn(e=s.then)?e:!1},Ku=function(s,e){var t=e.value,i=e.state==qu,r=i?s.ok:s.fail,n=s.resolve,o=s.reject,l=s.domain,d,u,c;try{r?(i||(e.rejection===Wu&&Dg(e),e.rejection=Bn),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===s.promise?o(Yu("Promise-chain cycle")):(u=Qu(d))?bs(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Ju=function(s,e){s.notified||(s.notified=!0,xn(function(){for(var t=s.reactions,i;i=t.get();)Ku(i,s);s.notified=!1,e&&!s.rejection&&_g(s)}))},Xu=function(s,e,t){var i,r;kg?(i=an.createEvent("Event"),i.promise=e,i.reason=t,i.initEvent(s,!1,!0),Ft.dispatchEvent(i)):i={promise:e,reason:t},!yg&&(r=Ft["on"+s])?r(i):s===zu&&gg("Unhandled promise rejection",t)},_g=function(s){bs(Uu,Ft,function(){var e=s.facade,t=s.value,i=al(s),r;if(i&&(r=bg(function(){Zs?On.emit("unhandledRejection",t,e):Xu(zu,e,t)}),s.rejection=Zs||al(s)?Wu:Bn,r.error))throw r.value})},al=function(s){return s.rejection!==Bn&&!s.parent},Dg=function(s){bs(Uu,Ft,function(){var e=s.facade;Zs?On.emit("rejectionHandled",e):Xu(wg,e,s.value)})},Ai=function(s,e,t){return function(i){s(e,i,t)}},Di=function(s,e,t){s.done||(s.done=!0,t&&(s=t),s.value=e,s.state=Ag,Ju(s,!0))},on=function(s,e,t){if(!s.done){s.done=!0,t&&(s=t);try{if(s.facade===e)throw Yu("Promise can't be resolved itself");var i=Qu(e);i?xn(function(){var r={done:!1};try{bs(i,e,Ai(on,r,s),Ai(Di,r,s))}catch(n){Di(r,n,s)}}):(s.value=e,s.state=qu,Ju(s,!1))}catch(r){Di({done:!1},r,s)}}};Gu&&(wi=function(e){mg(this,Sa),fg(e),bs(Ns,this);var t=ba(this);try{e(Ai(on,t),Ai(Di,t))}catch(i){Di(t,i)}},Sa=wi.prototype,Ns=function(e){Tg(this,{type:Er,done:!1,notified:!1,parent:!1,reactions:new Sg,rejection:!1,state:sl,value:void 0})},Ns.prototype=dg(Sa,"then",function(e,t){var i=ba(this),r=nn(vg(this,wi));return i.parent=!0,r.ok=sn(e)?e:!0,r.fail=sn(t)&&t,r.domain=Zs?On.domain:void 0,i.state==sl?i.reactions.add(r):xn(function(){Ku(r,i)}),r.promise}),rl=function(){var s=new Ns,e=ba(s);this.promise=s,this.resolve=Ai(on,e),this.reject=Ai(Di,e)},Hu.f=nn=function(s){return s===wi||s===Pg?new rl(s):$g(s)});ug({global:!0,constructor:!0,wrap:!0,forced:Gu},{Promise:wi});cg(wi,Er,!1,!0);hg(Er);var Ig=Ie,Zu=Ig("iterator"),ed=!1;try{var Rg=0,nl={next:function(){return{done:!!Rg++}},return:function(){ed=!0}};nl[Zu]=function(){return this},Array.from(nl,function(){throw 2})}catch(s){}var Cg=function(s,e){if(!e&&!ed)return!1;var t=!1;try{var i={};i[Zu]=function(){return{next:function(){return{done:t=!0}}}},s(i)}catch(r){}return t},Lg=Oi,xg=Cg,Ng=gs.CONSTRUCTOR,td=Ng||!xg(function(s){Lg.all(s).then(void 0,function(){})}),Og=at,Bg=Ge,Mg=ci,Vg=Bi,Fg=Ln,Ug=In,jg=td;Og({target:"Promise",stat:!0,forced:jg},{all:function(e){var t=this,i=Vg.f(t),r=i.resolve,n=i.reject,o=Fg(function(){var l=Mg(t.resolve),d=[],u=0,c=1;Ug(e,function(h){var f=u++,p=!1;c++,Bg(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),i.promise}});var Hg=at,Gg=gs.CONSTRUCTOR,ol=Oi;ol&&ol.prototype;Hg({target:"Promise",proto:!0,forced:Gg,real:!0},{catch:function(s){return this.then(void 0,s)}});var Yg=at,zg=Ge,qg=ci,Wg=Bi,Qg=Ln,Kg=In,Jg=td;Yg({target:"Promise",stat:!0,forced:Jg},{race:function(e){var t=this,i=Wg.f(t),r=i.reject,n=Qg(function(){var o=qg(t.resolve);Kg(e,function(l){zg(o,t,l).then(i.resolve,r)})});return n.error&&r(n.value),i.promise}});var Xg=at,Zg=Ge,eb=Bi,tb=gs.CONSTRUCTOR;Xg({target:"Promise",stat:!0,forced:tb},{reject:function(e){var t=eb.f(this);return Zg(t.reject,void 0,e),t.promise}});var ib=Lt,sb=Ct,rb=Bi,id=function(s,e){if(ib(s),sb(e)&&e.constructor===s)return e;var t=rb.f(s),i=t.resolve;return i(e),t.promise},ab=at,nb=di,ob=Bc,lb=Oi,ub=gs.CONSTRUCTOR,db=id,cb=nb("Promise"),hb=!ub;ab({target:"Promise",stat:!0,forced:ob},{resolve:function(e){return db(hb&&this===cb?lb:this,e)}});var fb=at,ln=Oi,pb=Je,mb=di,vb=pe,gb=Lu,ll=id,bb=ln&&ln.prototype,Sb=!!ln&&pb(function(){bb.finally.call({then:function(){}},function(){})});fb({target:"Promise",proto:!0,real:!0,forced:Sb},{finally:function(s){var e=gb(this,mb("Promise")),t=vb(s);return this.then(t?function(i){return ll(e,s()).then(function(){return i})}:s,t?function(i){return ll(e,s()).then(function(){throw i})}:s)}});var yb=di,Mn=yb,Tb=Mn,Eb=Tb("Promise","finally"),$b=Eb,kb=$b,wb=kb,Ab=wb,Ss=hr(Ab),ae;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ae||(ae={}));var _e=(s,e=0,t=ae.OFFSET_P)=>{switch(t){case ae.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ae.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case ae.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:a.assertNever(t)}return s};const er=(s,e)=>{var t;switch(e){case ae.OFFSET_P:return NaN;case ae.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case ae.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var A=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class ee{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,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:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||a.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Pb=s=>{switch(s){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(s)}};var H;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(H||(H={}));const _b=5,Db=5,Ib=500,ul=7e3;class Rb{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new ee(H.STOPPED),this.syncPlayback=()=>{const i=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: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==H.STOPPED&&(this.videoState.startTransitionTo(H.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===Y.Requested&&i!==H.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case H.PLAYING:case H.PAUSED:case H.READY:break;case H.STOPPED:this.videoState.startTransitionTo(H.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case H.PLAYING:break;case H.PAUSED:this.videoState.startTransitionTo(H.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case H.READY:this.videoState.startTransitionTo(H.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case H.STOPPED:this.videoState.startTransitionTo(H.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case H.PLAYING:this.videoState.startTransitionTo(H.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case H.PAUSED:break;case H.READY:this.videoState.startTransitionTo(H.PAUSED),this.videoState.setState(H.PAUSED);break;case H.STOPPED:this.videoState.startTransitionTo(H.READY),this.prepare();break;default:a.assertNever(i)}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(Pb(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(Ib)).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===Y.Applying||Math.abs(l-n)>_b)&&r.next(l),n=l})),e.add(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),r=>{this.logRemoteEvent(r),r.value?this.handleRemotePause():this.handleRemotePlay()}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),r=>{this.logRemoteEvent(r);const{remotePlayer:n}=this.params.connection,o=r.value,l=this.params.output.isBuffering$.getValue(),d=o===chrome.cast.media.PlayerState.BUFFERING;switch(l!==d&&this.params.output.isBuffering$.next(d),o){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&n.duration-n.currentTime<Db&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),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 i=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(i,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(H.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(H.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===H.PAUSED||e===H.PLAYING)&&(this.videoState.setState(H.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===H.PLAYING||e===H.PAUSED)&&(this.videoState.setState(H.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===H.READY&&this.videoState.setState(H.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==H.STOPPED&&this.videoState.setState(H.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i: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:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[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=i[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=i[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=i[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=i[e];a.assertNonNullable(c),r=_e(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 i=this.params.desiredState.seekState.getState();return i.state===Y.Applying||i.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(ul).subscribe(()=>n(`timeout(${ul})`)))});Ss(Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===Y.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 Cb=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Lb=s=>{const e=new a.ValueSubject(1/0),t=new a.Subject,i=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 S=ni(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),T=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),E=(p=T!=null?T:v*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(b={1:!0,0:!1}[S["x-reused"]])!==null&&b!==void 0?b:void 0;i.next(g),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.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$:i}},Ut=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},xb=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Ut}),!0),Nb=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const rt=(s,e,t,{equal:i=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=s.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},Ht=(s,e,t)=>rt(e,()=>s.loop,i=>{a.isNonNullable(i)&&(s.loop=i)},{onError:t}),vt=(s,e,t,i)=>rt(e,()=>({muted:s.muted,volume:s.volume}),r=>{a.isNonNullable(r)&&(s.muted=r.muted,s.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:i}),xt=(s,e,t,i)=>rt(e,()=>s.playbackRate,r=>{a.isNonNullable(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Ob=s=>["__",s.language,s.label].join("|"),Bb=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class nt{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,i){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(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(rt(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(rt(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(rt(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(rt(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 i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),a.filterChanged((i,r)=>i.length===r.length&&i.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:i})=>i==="showing")),a.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),a.filterChanged()).subscribe(this.current$));const t=i=>{var r,n;return this.applyCueSettings((n=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(i=>{var r,n;(r=i.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=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;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(nt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:n}=e,o=e.id?e.id:Ob(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(i=this.internalTracks.get(o))===null||i===void 0?void 0:i.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(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!Bb(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.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 Vn=s=>{s.removeAttribute("src"),s.load()},Mb=s=>{try{s.pause(),s.playbackRate=0,Vn(s),s.remove()}catch(e){console.error(e)}};class Vb{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 un=window.WeakMap?new WeakMap:new Vb,gt=s=>{let e=s.querySelector("video");const t=!!e;return e?Vn(e):(e=document.createElement("video"),s.appendChild(e)),un.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},bt=s=>{const e=un.get(s);un.delete(s),e?Vn(s):Mb(s)};class ys{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 sd=s=>{var e;let t=s;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},dl=s=>{const e=sd(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},Fb=s=>{const e=sd(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},dn=3;class Ub{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<dn&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||dn))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(r,e):r<e&&n>t?(i(t,n),i(r,e)):i(r,n))})}destroy(){this._buffer=[]}}var rd=(s,e,t=dn)=>{let i=0,r=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,r=l,!t)return{from:i,to:r};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=r&&(r=s.end(d))}}return{from:i,to:r}};const St=s=>{const e=v=>a.fromEvent(s,v).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=a.merge(...t.map(v=>a.fromEvent(s,v))).pipe(a.map(v=>v.type==="ended"?s.readyState<2:s.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(s,"progress"),a.fromEvent(s,"timeupdate")).pipe(a.map(()=>rd(s.buffered,s.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(s,"volumechange").pipe(a.map(()=>({muted:s.muted,volume:s.volume}))),d=a.fromEvent(s,"ratechange").pipe(a.map(()=>s.playbackRate)),u=a.fromEvent(s,"error").pipe(a.filter(()=>!!(s.error||s.played.length)),a.map(()=>{var v;const T=s.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),c=a.fromEvent(s,"timeupdate").pipe(a.map(()=>s.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(v=>{s.loop&&a.isNonNullable(p)&&a.isNonNullable(v)&&p>=s.duration-f&&v<=f&&h.next(p),p=v});const m=a.fromEvent(s,"enterpictureinpicture"),b=a.fromEvent(s,"leavepictureinpicture"),S=new a.ValueSubject(Fb(s));m.subscribe(()=>S.next(!0)),b.subscribe(()=>S.next(!1));const g=new a.ValueSubject(dl(s));return a.fromEvent(s,"fullscreenchange").pipe(a.map(()=>dl(s))).subscribe(g),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!s.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(s,"durationchange").pipe(a.map(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:S,inFullscreen$:g}},$r=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var jb=at,Hb=br,Gb=An,Yb=wn;jb({target:"Array",proto:!0},{at:function(e){var t=Hb(this),i=Gb(t),r=Yb(e),n=r>=0?r:i+r;return n<0||n>=i?void 0:t[n]}});var zb=Mn,qb=zb("Array","at"),Wb=qb,Qb=Wb,Kb=Qb,Jb=Kb,be=hr(Jb);let Fn=!1,_t={};const Xb=s=>{Fn=s},Zb=()=>{_t={}},eS=s=>{s(_t)},Os=(s,e)=>{var t;Fn&&(_t.meta=(t=_t.meta)!==null&&t!==void 0?t:{},_t.meta[s]=e)};class ct{constructor(e){this.name=e}next(e){var t,i;if(!Fn)return;_t.series=(t=_t.series)!==null&&t!==void 0?t:{};const r=(i=_t.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),_t.series[this.name]=r}}var si;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(si||(si={}));const tS=new ct("best_bitrate"),iS=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class ad{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const sS='Assertion "ABR Tracks is empty array" failed',hi=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,b,S;a.assertNotEmptyArray(s,sS);const g=i.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*g*i.containerSizeFactor,height:e.height*g*i.containerSizeFactor},v=y&&a.videoSizeToQuality(y),T=i.considerPlaybackRate&&a.isNonNullable(l)?l:1,E=s.filter(R=>!a.isInvariantQuality(R.quality)).sort((R,_)=>a.isHigher(R.quality,_.quality)?-1:1),P=(p=be(E,-1))===null||p===void 0?void 0:p.quality,N=(m=be(E,0))===null||m===void 0?void 0:m.quality,V=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&a.isLower(r.max,r.min)||a.isNonNullable(r.min)&&N&&a.isHigher(r.min,N)||a.isNonNullable(r.max)&&P&&a.isLower(r.max,P),x=T*iS(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},D=E.filter(R=>(v?a.isLower(R.quality,v):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(R.bitrate)?t-n>=R.bitrate*x:!0)?i.lazyQualitySwitch&&a.isNonNullable(i.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&a.isHigher(R.quality,d.quality)?(B[R.quality]=si.Buffer,!1):!!c&&a.isHigherOrEqual(R.quality,c)?(B[R.quality]=si.DroppedFramesLimit,!1):V||(a.isNullable(r.max)||a.isLowerOrEqual(R.quality,r.max))&&(a.isNullable(r.min)||a.isHigherOrEqual(R.quality,r.min))?!0:(B[R.quality]=si.FitsQualityLimits,!1):(B[R.quality]=si.FitsThroughput,!1):(B[R.quality]=si.FitsContainer,!1))[0];D&&D.bitrate&&tS.next(D.bitrate);const I=(b=D!=null?D:E[Math.ceil((E.length-1)/2)])!==null&&b!==void 0?b:s[0];I.quality!==((S=u==null?void 0:u.last)===null||S===void 0?void 0:S.quality)&&h({message:`
|
|
7
7
|
[available tracks]
|
|
8
8
|
${s.map(R=>`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -42,5 +42,5 @@ precision highp float;
|
|
|
42
42
|
#define GLSLIFY 1
|
|
43
43
|
#endif
|
|
44
44
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class bd{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,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 i0(this.params.fov,this.params.orientation),this.cameraRotationManager=new s0(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"),i=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(i),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(i,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(r0,this.gl.VERTEX_SHADER),i=this.createShader(a0,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,n=e-i,o=t-r,l=e+i,d=t-r,u=e+i,c=t+r,h=e-i,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}}let Sd=class{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(le.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ad,this.textTracks=[],this.syncPlayback=()=>{var t,i,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===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==le.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==le.STOPPED&&(this.videoState.startTransitionTo(le.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(le.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(le.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case le.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case le.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var i,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.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=gt(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(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new t0({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=St(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:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,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$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.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(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(xt(this.video,t.playbackRate,i.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ze.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((g,y)=>y.bitrate-g.bitrate),m=Array.from(f.video).sort((g,y)=>y.bitrate-g.bitrate),b=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const y=dy(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=uy(g);if(y){h.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&cy(p,m,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(h);for(const g of b){const y=hy(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===ze.REPRESENTATIOS_READY&&(this.videoState.setState(le.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!==ze.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(ye.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(ye.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,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=Ne(this.video.buffered,this.video.currentTime*1e3),p=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=hi(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=d?S!=null?S:c:c!=null?c:S;return g&&((l=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||l===void 0?void 0:l.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(le.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}},n0=class extends Sd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Te;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Te||(Te={}));var dt;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(dt||(dt={}));var lr;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(lr||(lr={}));var Qe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Qe||(Qe={}));var G;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(G||(G={}));var Li;(function(s){s.MP4="mp4",s.WEBM="webm"})(Li||(Li={}));var ur;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ur||(ur={}));var ue;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ue||(ue={}));var wa,Aa;let yd=!1;try{yd=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Aa=(wa=navigator.userAgent.match(/Version\/(\d+)/))===null||wa===void 0?void 0:wa[1])!==null&&Aa!==void 0?Aa:"",10)<16}catch(s){console.error(s)}class o0{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 i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return F(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return F(this,void 0,void 0,function*(){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return F(this,void 0,void 0,function*(){return new Promise(t=>{let i;yd&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),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:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,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)}}}class Ze{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 Td extends Ze{}class l0 extends Ze{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class u0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class d0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class c0 extends Ze{constructor(e){super(e),this.data=this.content}}class Ot extends Ze{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class h0 extends Ot{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 i=this.readUint32();const r=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class f0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class p0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}var ai;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(ai||(ai={}));class m0 extends Ot{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=ai.MONOSCOPIC;break;case 1:this.stereoMode=ai.TOP_BOTTOM;break;case 2:this.stereoMode=ai.LEFT_RIGHT;break;case 3:this.stereoMode=ai.STEREO_CUSTOM;break;case 4:this.stereoMode=ai.RIGHT_LEFT;break}this.cursor+=1}}class v0 extends Ot{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class g0 extends Ot{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class b0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class S0 extends Ot{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 y0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class T0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class E0 extends Ot{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class $0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class k0 extends Ot{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 w0 extends Ot{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 A0 extends Ot{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 P0={ftyp:l0,moov:u0,moof:d0,mdat:c0,sidx:h0,trak:f0,mdia:b0,mfhd:E0,tkhd:S0,traf:$0,tfhd:k0,tfdt:w0,trun:A0,minf:y0,sv3d:p0,st3d:m0,prhd:v0,proj:T0,equi:g0,unknown:Td};class _0{createBox(e,t){const i=P0[e];return i?new i(t):new Td(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ar.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Ar=new _0;function ss(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(o=>o.charCodeAt(0));let r=s.byteOffset,n=[];for(;r<t.byteLength;){if(t[r]===i[n.length]?n.push(t[r]):n=[],n.length===4){const l=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+l>s.buffer.byteLength?null:Ar.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function hn(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=ss(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function Gt(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Ar.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const D0=new TextDecoder("ascii"),I0=s=>D0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",R0=s=>{const e=Ar.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.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:G.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},C0=s=>{const e=hn(s,"mdat"),t=hn(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],n=i.source.byteOffset,l=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,n,l)},L0=(s,e)=>{const t=hn(s,"traf"),i=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=i.defaultSampleDuration*n.sampleCount,(Number(r.baseMediaDecodeTime)+o)/e*1e3},x0=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ss(s,"sv3d")){e.is3dVideo=!0;const i=ss(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=ss(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=ss(s,"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},N0={validateData:I0,parseInit:x0,getIndexRange:()=>{},parseSegments:R0,parseFeedableSegmentChunk:C0,getSegmentEndTime:L0};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var L;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(L||(L={}));const $l={[k.EBML]:{type:L.Master},[k.EBMLVersion]:{type:L.UnsignedInteger},[k.EBMLReadVersion]:{type:L.UnsignedInteger},[k.EBMLMaxIDLength]:{type:L.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:L.UnsignedInteger},[k.DocType]:{type:L.String},[k.DocTypeVersion]:{type:L.UnsignedInteger},[k.DocTypeReadVersion]:{type:L.UnsignedInteger},[k.Void]:{type:L.Binary},[k.Segment]:{type:L.Master},[k.SeekHead]:{type:L.Master},[k.Seek]:{type:L.Master},[k.SeekID]:{type:L.Binary},[k.SeekPosition]:{type:L.UnsignedInteger},[k.Info]:{type:L.Master},[k.TimestampScale]:{type:L.UnsignedInteger},[k.Duration]:{type:L.Float},[k.Tracks]:{type:L.Master},[k.TrackEntry]:{type:L.Master},[k.Video]:{type:L.Master},[k.Projection]:{type:L.Master},[k.ProjectionType]:{type:L.UnsignedInteger},[k.ProjectionPrivate]:{type:L.Master},[k.Chapters]:{type:L.Master},[k.Cluster]:{type:L.Master},[k.Timestamp]:{type:L.UnsignedInteger},[k.SilentTracks]:{type:L.Master},[k.SilentTrackNumber]:{type:L.UnsignedInteger},[k.Position]:{type:L.UnsignedInteger},[k.PrevSize]:{type:L.UnsignedInteger},[k.SimpleBlock]:{type:L.Binary},[k.BlockGroup]:{type:L.Master},[k.EncryptedBlock]:{type:L.Binary},[k.Attachments]:{type:L.Master},[k.Tags]:{type:L.Master},[k.Cues]:{type:L.Master},[k.CuePoint]:{type:L.Master},[k.CueTime]:{type:L.UnsignedInteger},[k.CueTrackPositions]:{type:L.Master},[k.CueTrack]:{type:L.UnsignedInteger},[k.CueClusterPosition]:{type:L.UnsignedInteger},[k.CueRelativePosition]:{type:L.UnsignedInteger},[k.CueDuration]:{type:L.UnsignedInteger},[k.CueBlockNumber]:{type:L.UnsignedInteger},[k.CueCodecState]:{type:L.UnsignedInteger},[k.CueReference]:{type:L.Master},[k.CueRefTime]:{type:L.UnsignedInteger}},Ed=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=dr(s,t),r=i in $l,n=r?$l[i].type:L.Binary,o=s.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(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=dr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},dr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ft=(s,e)=>{switch(e){case L.SignedInteger:return s.getInt8(0);case L.UnsignedInteger:return dr(s);case L.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case L.String:return new TextDecoder("ascii").decode(s);case L.UTF8:return new TextDecoder("utf-8").decode(s);case L.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case L.Master:return s;case L.Binary:return s;default:a.assertNever(e)}},xi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Ed(i);if(!e(r))return;r.type===L.Master&&xi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},O0=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Ed(s);return xi(r.value,({tag:n,type:o,value:l})=>(n===k.EBMLReadVersion?e=ft(l,o):n===k.DocType?t=ft(l,o):n===k.DocTypeReadVersion&&(i=ft(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},$d=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],B0=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],M0=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return xi(s,({tag:f,type:p,value:m,valueSize:b})=>{if(f===k.SeekID){const S=ft(m,p);u=dr(S)}else f!==k.SeekPosition&&(u=void 0);return f===k.Segment?(e=m.byteOffset,t=m.byteOffset+b):f===k.Info?n=!0:f===k.SeekHead?o=!0:f===k.TimestampScale?i=ft(m,p):f===k.Duration?r=ft(m,p):f===k.SeekPosition&&u===k.Cues?d=ft(m,p):f===k.Tracks?xi(m,({tag:S,type:g,value:y})=>S===k.ProjectionType?(c=ft(y,g)===1,!1):!0):n&&o&&$d.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"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},V0=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},F0=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return xi(s,({tag:l,type:d,value:u})=>{switch(l){case k.Cues:t=!0;break;case k.CuePoint:o&&r(o)&&n.push(o),o={};break;case k.CueTime:o&&(o.time=ft(u,d));break;case k.CueTrackPositions:break;case k.CueClusterPosition:o&&(o.position=ft(u,d));break;default:t&&$d.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:G.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},U0=s=>{let e=0,t=!1;try{xi(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):B0.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},j0={validateData:O0,parseInit:M0,getIndexRange:V0,parseSegments:F0,parseFeedableSegmentChunk:U0},kl=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},$i=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},H0=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,m,b,S,g,y,v,T,E,P,N,V,x,B,M,D,I,U,R,_,O,z,te,ne,me,Re,Ye,q;const Ce=new DOMParser().parseFromString(s,"application/xml"),ve={video:[],audio:[],text:[]},ce=Ce.children[0],Tt=ce.getElementsByTagName("Period")[0],Et=Tt.children,Bt=ce.getAttribute("type")==="dynamic",$t=ce.getAttribute("availabilityStartTime"),fi=$t?new Date($t).getTime():void 0;let ke;const Fi=ce.getAttribute("mediaPresentationDuration"),Ui=Tt.getAttribute("duration"),Yt=ce.getElementsByTagName("vk:Attrs")[0],ji=Yt==null?void 0:Yt.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Fi)ke=kl(Fi);else if(Ui){const oe=kl(Ui);a.isNonNullable(oe)&&(ke=oe)}else ji&&(ke=parseInt(ji,10));let Pr=0;const zt=(i=(t=ce.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=zt.includes(lr.WEBM_AS_IN_FFMPEG)||zt.includes(lr.WEBM_AS_IN_SPEC)?Li.WEBM:Li.MP4;for(const oe of Et){const kt=oe.getAttribute("mimeType"),Dr=oe.getAttribute("codecs"),Hi=(r=oe.getAttribute("contentType"))!==null&&r!==void 0?r:kt==null?void 0:kt.split("/")[0],Ir=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gi=oe.querySelectorAll("Representation"),Rr=oe.querySelector("SegmentTemplate");if(Hi===Te.TEXT){for(const j of Gi){const ge=j.getAttribute("id")||"",wt=oe.getAttribute("lang"),Oe=(u=(d=(l=j.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",qt=new URL(Oe,e).toString(),Wt=ge.includes("_auto");ve[Te.TEXT].push({id:ge,lang:wt,isAuto:Wt,kind:Te.TEXT,url:qt})}continue}for(const j of Gi){const ge=(c=j.getAttribute("mimeType"))!==null&&c!==void 0?c:kt,wt=(f=(h=j.getAttribute("codecs"))!==null&&h!==void 0?h:Dr)!==null&&f!==void 0?f:"",Oe=(m=(p=j.getAttribute("contentType"))!==null&&p!==void 0?p:ge==null?void 0:ge.split("/")[0])!==null&&m!==void 0?m:Hi,qt=(S=(b=oe.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&S!==void 0?S:[],Wt=parseInt((g=j.getAttribute("width"))!==null&&g!==void 0?g:"",10),Yi=parseInt((y=j.getAttribute("height"))!==null&&y!==void 0?y:"",10),zi=parseInt((v=j.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,qi=(T=j.getAttribute("frameRate"))!==null&&T!==void 0?T:"",Cr=(E=j.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Lr=qi?$r(qi):void 0,xr=(P=j.getAttribute("id"))!==null&&P!==void 0?P:(Pr++).toString(10),Nr=Oe==="video"?`${Yi}p`:Oe==="audio"?`${zi}Kbps`:wt,Or=`${xr}@${Nr}`,Br=(x=(V=(N=j.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||V===void 0?void 0:V.trim())!==null&&x!==void 0?x:"",Wi=new URL(Br,e).toString(),Mr=[...zt,...Ir,...qt];let Qt;const Vr=j.querySelector("SegmentBase"),we=(B=j.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Rr;if(Vr){const Be=(D=(M=j.querySelector("SegmentBase Initialization"))===null||M===void 0?void 0:M.getAttribute("range"))!==null&&D!==void 0?D:"",[Me,Jt]=Be.split("-").map(Ve=>parseInt(Ve,10)),Le={from:Me,to:Jt},et=(I=j.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Xt,At]=et?et.split("-").map(Ve=>parseInt(Ve,10)):[],tt=et?{from:Xt,to:At}:void 0;Qt={type:Qe.BYTE_RANGE,url:Wi,initRange:Le,indexRange:tt}}else if(we){const Be={representationId:(U=j.getAttribute("id"))!==null&&U!==void 0?U:void 0,bandwidth:(R=j.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Me=parseInt((_=we.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Jt=(O=we.getAttribute("initialization"))!==null&&O!==void 0?O:"",Le=we.getAttribute("media"),et=(te=parseInt((z=we.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&te!==void 0?te:1,Xt=$i(Jt,Be);if(!Le)throw new ReferenceError("No media attribute in SegmentTemplate");const At=(ne=we.querySelectorAll("SegmentTimeline S"))!==null&&ne!==void 0?ne:[],tt=[];let Ve=0,Zt="",Fe=0;if(At.length){let Ue=et,he=0;for(const it of At){const xe=parseInt((me=it.getAttribute("d"))!==null&&me!==void 0?me:"",10),ot=parseInt((Re=it.getAttribute("r"))!==null&&Re!==void 0?Re:"",10)||0,Pt=parseInt((Ye=it.getAttribute("t"))!==null&&Ye!==void 0?Ye:"",10);he=Number.isFinite(Pt)?Pt:he;const Qi=xe/Me*1e3,pi=he/Me*1e3;for(let mi=0;mi<ot+1;mi++){const Id=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:Ue.toString(10),segmentTime:(he+mi*xe).toString(10)})),Yn=(pi!=null?pi:0)+mi*Qi,Rd=Yn+Qi;Ue++,tt.push({time:{from:Yn,to:Rd},url:Id})}he+=(ot+1)*xe,Ve+=(ot+1)*Qi}Fe=he/Me*1e3,Zt=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:Ue.toString(10),segmentTime:he.toString(10)}))}else if(a.isNonNullable(ke)){const he=parseInt((q=we.getAttribute("duration"))!==null&&q!==void 0?q:"",10)/Me*1e3,it=Math.ceil(ke/he);let xe=0;for(let ot=1;ot<it;ot++){const Pt=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:ot.toString(10),segmentTime:xe.toString(10)}));tt.push({time:{from:xe,to:xe+he},url:Pt}),xe+=he}Fe=xe,Zt=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:it.toString(10),segmentTime:xe.toString(10)}))}const ei={time:{from:Fe,to:1/0},url:Zt};Qt={type:Qe.TEMPLATE,baseUrl:Wi,segmentTemplateUrl:Le,initUrl:Xt,totalSegmentsDurationMs:Ve,segments:tt,nextSegmentBeyondManifest:ei,timescale:Me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!ge)continue;const Kt={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Oe];Kt&&ve[Kt].push({id:Or,kind:Kt,segmentReference:Qt,profiles:Mr,duration:ke,bitrate:zi,mime:ge,codecs:wt,width:Wt,height:Yi,fps:Lr,quality:Cr})}}return{dynamic:Bt,liveAvailabilityStartTime:fi,duration:ke,container:_r,representations:ve}},G0=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Mi(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},Y0=({id:s,bitrate:e})=>({id:s,bitrate:e}),z0=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=be(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:be(s,-1)},q0=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),wl=s=>"size"in s,Ti=s=>s.type===Qe.TEMPLATE,fn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class Al{constructor(e,t,i,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 Ke,this.destroyAbortController=new Ke,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 Z(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 o0(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),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(S=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield yield w(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 w(void 0);this.searchGaps(m,f),yield yield w(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 Z(this,arguments,function*(){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return yield w(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 w(this.loadInit(f,"high",!1)):m instanceof Promise&&(yield yield w(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 w(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield yield w(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const b=this.getCurrentPosition();a.isNonNullable(b)&&(this.isLive||(p.forEach(S=>S.status=G.NONE),this.pruneBuffer(b,1/0,!0)),this.maintain(b))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(h){var f;return Z(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return yield w(void 0);for(const y of this.representations.keys()){const v=h.find(P=>P.id===y);v&&this.representations.set(y,v);const T=this.representations.get(y);if(!T||!Ti(T.segmentReference))return yield w(void 0);const E=this.getActualLiveStartingSegments(T.segmentReference);this.segments.set(T.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 S=this.initData.get(p);if(a.assertNonNullable(S,"No init buffer for starting representation"),!(S instanceof ArrayBuffer))return yield w(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield w(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(b,m),yield yield w(this.sourceBufferTaskQueue.append(S,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=i,i){case Li.MP4:this.containerParser=N0;break;case Li.WEBM:this.containerParser=j0;break;default:a.assertNever(i)}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 Ke,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),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Ne(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ne(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(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=be(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===G.FED&&!l.length&&Ne(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=be(i,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+r}),i=n.time.to;a.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=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<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,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 i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Ti(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:G.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(r=be(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 i of this.representations.values()){const r=i.segmentReference;if(!Ti(r))return;const n=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),o=$i(r.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(i.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:G.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i: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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const b=f<=i&&p>=i,S=f>i||b||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=i+g||p<=i+g;return(h===G.NONE||h===G.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!Ri(this.sourceBuffer.buffered,i))&&S&&y});if(r===-1)return[];if(t!==Qe.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===G.NONE||f.status===G.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,i="auto"){return F(this,void 0,void 0,function*(){t.segmentReference.type===Qe.TEMPLATE?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return F(this,void 0,void 0,function*(){e.status=G.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,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(yield a.abortable(l,function(){return Z(this,arguments,function*(){const c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield w(new Promise(h=>setTimeout(h,c)))})}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const c=yield this.fetcher.fetch(o,{range:n,signal:l,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;const h=new DataView(c);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}d&&r.feedingBytes&&u?yield Promise.all(u):yield this.sourceBufferTaskQueue.append(h,l),r.segment.status=G.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){if(!fn(c))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(c)}})}loadByteRangeSegments(e,t,i="auto"){return F(this,void 0,void 0,function*(){if(!e.length)return;for(const d of e)d.status=G.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 Z(this,arguments,function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield w(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:i}),this.failedDownloads=0}catch(d){if(!fn(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}})}prepareByteRangeFetchSegmentParams(e,t){if(Ti(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:be(e,0).byte.from,to:be(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,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(!Ti(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},l=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});l.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:r,signal:n,onProgress:u,onProgressTasks:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=Ne((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:n}){return F(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:d}=l;if(l.representationId===t){if(n.aborted){r();continue}if(l.loadedBytes=i,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=G.PARTIALLY_FED,l.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),l.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,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===Qe.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const b=f?h.byte.from-i:0,S=f?h.byte.to-i:e.byteLength,g=b<r,y=S<=r;if(h.status===G.DOWNLOADING&&g&&y){h.status=G.DOWNLOADED;const v=new DataView(e.buffer,e.byteOffset+b,p);this.sourceBufferTaskQueue.append(v,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(c,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(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),T=c.loadedBytes===p?v:this.containerParser.parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(h.status=G.PARTIALLY_FED,c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(E=>{if(n.aborted)o();else if(E)c.fedBytes+=T.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=G.FED,wl(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const n of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])n.status===G.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=G.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>Ss(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return F(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Z(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield w(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>F(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&&Ti(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),i&&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,i=!1){return F(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=wl(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===G.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===G.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===G.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){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===G.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.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=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==G.FED&&n!==G.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=G.PARTIALLY_EJECTED:r.status=G.NONE)}}}var _i;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(_i||(_i={}));class W0{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!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 Ke,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(r){return Z(this,arguments,function*(){let n=r;this.requestQuic&&(n=Ut(n));const o=yield yield w(li(n,{signal:this.abortAllController.signal}).catch(Zi));return o?(this.onHeadersReceived(o.headers),yield w(o.text())):yield w(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(r,{rangeMethod:n=this.compatibilityMode?_i.HEADER:_i.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0,isLowLatency:h=!1}={}){var f,p;return Z(this,arguments,function*(){let m=r;const b=new Headers;if(o)switch(n){case _i.HEADER:{b.append("Range",`bytes=${o.from}-${o.to}`);break}case _i.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=Ut(m));let S=this.abortAllController.signal,g;if(u){const I=new Ke;if(g=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{I.abort()}catch(U){Zi(U)}}),this.abortAllController.signal.aborted||u.aborted)try{I.abort()}catch(U){Zi(U)}S=I.signal}const y=a.now(),v=yield yield w(li(m,{priority:d,headers:b,signal:S}).catch(Zi)),T=a.now();if(!v)return g==null||g.unsubscribe(),yield w(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!v.ok||!v.body)return g==null||g.unsubscribe(),yield w(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));if(this.onHeadersReceived(v.headers),!l&&!c)return g==null||g.unsubscribe(),yield w(v.arrayBuffer());const[E,P]=v.body.tee(),N=E.getReader();c&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(P,h));let V=0,x=new Uint8Array(0),B=!1;const M=I=>{g==null||g.unsubscribe(),B=!0,Zi(I)},D=a.abortable(S,function({done:I,value:U}){return Z(this,arguments,function*(){if(V===0&&this.lastRequestFirstBytes$.next(a.now()-y),S.aborted)return g==null||g.unsubscribe(),yield w(void 0);if(!I&&U){const R=new Uint8Array(x.length+U.length);R.set(x),R.set(U,x.length),x=R,V+=U.byteLength,l==null||l(new DataView(x.buffer),V),yield yield w(N==null?void 0:N.read().then(D,M))}})}.bind(this));return yield yield w(N==null?void 0:N.read().then(D,M)),g==null||g.unsubscribe(),yield w(B?null:x.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return Z(this,arguments,function*(){if(r.type!==Qe.BYTE_RANGE)return yield w(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 w(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!b)return yield w(null);const S=new DataView(b,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const g=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let v;if(f)v=new DataView(b,y.from-c,y.to-y.from+1);else{const E=yield yield w(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!E)return yield w(null);v=new DataView(E)}const T=n.parseSegments(v,g,y);return yield w({init:g,dataView:new DataView(b),segments:T})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return Z(this,arguments,function*(){if(r.type!==Qe.TEMPLATE)return yield w(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield w(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield w(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:G.NONE,size:void 0}));return yield w({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,n;return F(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case Qe.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Qe.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Zi=s=>{if(!fn(s))throw s},pn=1e3,cr=(s,e,t)=>t*e+(1-t)*s,kd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Q0=(s,e,t,i)=>{let r=0,n=t;const o=kd(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?r++:r--,n=(s.length+n-1)%s.length;return Math.abs(r)===l};class Gn{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 i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ct(`raw_${i}`),this.smoothedSeries$=new ct(`smoothed_${i}`),this.reportedSeries$=new ct(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;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 K0 extends Gn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class J0 extends Gn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=kd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const i=Q0(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class X0 extends Gn{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?cr(this.smoothed,e,this.params.emaAlpha):e}}class mn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new K0({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new J0({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new X0(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const Z0=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},Pl=["timeupdate","progress","play","seeked","stalled","waiting"];var qe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(qe||(qe={}));let eT=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 ee(qe.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.livePositionFromPlayer$=new a.ValueSubject(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ke,this.initManifest=a.abortable(this.destroyController.signal,function(t,i,r){var n;return Z(this,arguments,function*(){this.element=t,this.manifestUrlString=_e(i,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(qe.MANIFEST_READY),this.manifest=yield yield w(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(qe.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 Z(this,arguments,function*(){const i=yield yield w(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(!i)return yield w(null);let r;try{r=H0(i!=null?i:"",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 w(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===Te.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield w(Object.assign(Object.assign({},r),{representations:ni(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,i){return Z(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(qe.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;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 Al(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new Al(Te.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(pn).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=er(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P);this.manifestUrlString=_e(this.manifestUrlString,u+pn,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Pl.map(l=>a.fromEvent(this.element,l))).pipe(a.map(l=>this.element?Ne(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(l=>!!l),a.tap(l=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).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),Z0(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,S;return(S=(b=m.getLiveSegmentsToLoadState(this.manifest))===null||b===void 0?void 0:b.to)!==null&&S!==void 0?S:0}))-f}h&&this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(a.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:d,bufferLength:u})=>F(this,void 0,void 0,function*(){if(a.assertNonNullable(this.element),this.isUpdatingLive)return;const c=this.element.playbackRate,h=er(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P),f=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,p=Math.min(f,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*c),m=this.tuning.dashCmafLive.normalizedActualBufferOffset*c,b=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,S=this.isActiveLowLatency?u:d;let g=dt.None;if(this.isActiveLowLatency?g=dt.ActiveLowLatency:S<p+b&&S>=p?g=dt.LiveWithTargetOffset:h!==0&&S<p&&(g=dt.LiveForwardBuffering),isFinite(d)&&(l=d>l?d:l),g===dt.LiveForwardBuffering||g===dt.LiveWithTargetOffset){const y=l-(p+m),v=this.normolizeLiveOffset(Math.trunc(h+y/c)),T=Math.abs(v-h);let E;!d||T<=this.tuning.dashCmafLive.offsetCalculationError?E=h:v>0&&T>this.tuning.dashCmafLive.offsetCalculationError?E=v:E=0,this.manifestUrlString=_e(this.manifestUrlString,E,ae.DASH_CMAF_OFFSET_P)}g!==dt.None&&g!==dt.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 w(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(i)?yield yield w(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield w(this.videoBufferManager.startWith(t)),this.state$.setState(qe.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,i;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||!((i=this.audioBufferManager)===null||i===void 0)&&i.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 W0({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=mn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,i,r,n;return F(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const o=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&o===0,this.liveLastSeekOffset=o,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=_e(this.manifestUrlString,o,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.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(qe.RUNNING),this.subscription.add(a.merge(...Pl.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&&Ri(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}switchRepresentation(e,t){return F(this,void 0,void 0,function*(){const i={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,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((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Ri(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(qe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}waitingEventCallback(){return F(this,void 0,void 0,function*(){try{if(!this.element)return;this.isLive$.getValue()?yield this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:a.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return F(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];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?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class wd{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(ue.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ad,this.textTracks=[],this.syncPlayback=()=>{var t,i,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===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ue.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.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(ue.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case ue.STOPPED:this.videoState.startTransitionTo(ue.READY),this.prepare();return;case ue.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(ue.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ue.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ue.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var i,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.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=gt(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(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new eT({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=St(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:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,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$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.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(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(xt(this.video,t.playbackRate,i.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ue.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===qe.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((g,y)=>y.bitrate-g.bitrate),m=Array.from(f.video).sort((g,y)=>y.bitrate-g.bitrate),b=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const y=Y0(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=G0(g);if(y){h.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&z0(p,m,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(h);for(const g of b){const y=q0(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===qe.REPRESENTATIOS_READY&&(this.videoState.setState(ue.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!==qe.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(Te.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(Te.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,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=Ne(this.video.buffered,this.video.currentTime*1e3),p=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=hi(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=d?S!=null?S:c:c!=null?c:S;return g&&((l=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||l===void 0?void 0:l.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(ue.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}}class tT extends wd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let iT=class extends Sd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(cn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===le.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(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===le.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)})}};class sT extends wd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(pn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===ue.PLAYING&&!this.player.isActiveLowLatency){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(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===ue.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 ut={};var X;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));const es=(s,e)=>new a.Observable(t=>{const i=(r,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class rT{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(X.INITIALIZING),this.textTracksManager=new nt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==X.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===Y.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case X.STOPPED:break;case X.READY:case X.PLAYING:case X.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case X.STOPPED:this.prepare();break;case X.READY:case X.PLAYING:case X.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case X.PLAYING:break;case X.STOPPED:this.prepare();break;case X.READY:case X.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case X.PAUSED:break;case X.STOPPED:this.prepare();break;case X.READY:this.videoState.setState(X.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case X.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(i)}},this.video=gt(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(De(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),bt(this.video)}loadHlsJs(){let e=!1;const t=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},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ss(import("hls.js").then(r=>{e||(ut.Hls=r.default,ut.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(ut.Hls,"hls.js not loaded"),this.hls=new ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){a.assertNonNullable(ut.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=St(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));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(Ht(this.video,e.isLooped,i)),this.subscription.add(vt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(xt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(es(this.hls,ut.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(X.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===X.READY&&this.videoState.setState(X.READY),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},i)),n(es(this.hls,ut.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:S}=h,g=(p=Mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:b,height:S});if(!g)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:g,bitrate:h.bitrate/1e3,size:{width:b,height:S},fps:y};return this.trackLevels.set(m,{track:v,level:h}),c.push(v),c},[]))),t.availableVideoTracks$),n(es(this.hls,ut.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(es(this.hls,ut.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>De(u))),t.hostname$),this.subscription.add(rt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));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=es(this.hls,ut.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(rt(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u.id))===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,onError:i})),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,i))}prepare(){this.videoState.startTransitionTo(X.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return F(this,void 0,void 0,function*(){this.videoState.startTransitionTo(X.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(X.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(X.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(X.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const _l="X-Playback-Duration";var Dl=s=>F(void 0,void 0,void 0,function*(){var e;const t=yield li(s),i=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(_l)?parseInt(t.headers.get(_l),10):void 0});const aT=s=>{let e=null;if(s.QUALITY&&(e=Mi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=a.videoSizeToQuality({width:t,height:i})}return e!=null?e:null},Ad=(s,e=s)=>F(void 0,void 0,void 0,function*(){var t,i;const o=(yield(yield li(s)).text()).split(`
|
|
46
|
-
`),l=[],d=[];for(let u=0;u<o.length;u++){const c=o[u],h=c.match(/^#EXT-X-STREAM-INF:(.+)/),f=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!h&&!f)){if(h){const p=ni(h[1].split(",").map(T=>T.split("="))),m=(t=p.QUALITY)!==null&&t!==void 0?t:`stream-${p.BANDWIDTH}`,b=aT(p);let S;p.BANDWIDTH&&(S=parseInt(p.BANDWIDTH,10)/1e3||void 0),!S&&p["AVERAGE-BANDWIDTH"]&&(S=parseInt(p["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const g=p["FRAME-RATE"]?parseFloat(p["FRAME-RATE"]):void 0;let y;if(p.RESOLUTION){const[T,E]=p.RESOLUTION.split("x").map(P=>parseInt(P,10));T&&E&&(y={width:T,height:E})}const v=new URL(o[++u],e).toString();b&&l.push({id:m,quality:b,url:v,bandwidth:S,size:y,fps:g})}if(f){const p=ni(f[1].split(",").map(g=>g.split("=")).map(([g,y])=>[g,y.replace(/^"|"$/g,"")])),m=(i=p.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),b=p.LANGUAGE,S=p.NAME;m&&b&&d.push({type:"internal",id:b,label:S,language:b,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}});var ie;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ie||(ie={}));class nT{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new ee(ie.STOPPED),this.textTracksManager=new nt,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ys,this.manifestStartTime$=new a.ValueSubject(void 0),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(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.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(ie.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(l||d||u){const f=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:n===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ie.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},Ad(_e(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:a.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(De(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,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));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),i)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),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.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(De(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===ie.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===Y.Requested&&this.seek(l.position)},i)),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)},i)),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),i)),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$,i));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:u,min:c}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[h,f]of[[u,"mq"],[c,"lq"]]){const p=String(parseFloat(h||""));f&&h&&o.searchParams.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?ae.DASH_CMAF_OFFSET_P:ae.OFFSET_P,d=_e(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",d),this.video.load(),Dl(d).then(u=>{var c;if(!a.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(c=this.params.source.maxSeekBackTime)!==null&&c!==void 0?c:this.maxSeekBackTime$.getValue();if(a.isNullable(h)||!isFinite(h))try{li(d).then(f=>f.text()).then(f=>{var p;const m=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(m){const b=new URL(m,d).toString();Dl(b).then(S=>{a.isNullable(S)||this.maxSeekBackTime$.next(S)})}})}catch(f){}}})}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var re;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(re||(re={}));class oT{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(re.STOPPED),this.textTracksManager=new nt,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===exports.PlaybackState.STOPPED){i!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(i===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||l||d){const h=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&c.state===Y.Requested&&this.seek(c.position),i){case re.READY:r===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(re.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case re.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return a.assertNever(i)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ad(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));if(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(Ht(this.video,t.isLooped,i)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},i).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.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(De(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===re.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===Y.Requested&&this.seek(l.position)},i))),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$,i)),!a.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(a.merge(a.fromEvent(l,"addtrack"),a.fromEvent(l,"removetrack"),a.fromEvent(l,"change"),a.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<l.length;d++)l[d].mode="hidden"},i))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,c]of[[l,"mq"],[d,"lq"]]){const h=String(parseFloat(u||""));c&&u&&o.searchParams.set(c,h)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var de;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));class lT{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(de.STOPPED),this.trackUrls={},this.textTracksManager=new nt,this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),A(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!==de.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(c){const{currentTime:f}=this.video;this.prepare(),h.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:f*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[c.to.id])===null||i===void 0?void 0:i.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===Y.Requested&&this.seek(h.position),n){case de.READY:o===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(de.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case de.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),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,i=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));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(Ht(this.video,t.isLooped,i)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===de.READY&&this.videoState.setState(de.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.id].track)),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i)),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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;a.assertNonNullable(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];a.assertNonNullable(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=Ut(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(De(i))}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const d=(i=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||i===void 0?void 0:i.track,u=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,c=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(d&&c&&a.isHigherOrEqual(c.quality,d.quality)&&(o=d),!o){const h=Object.values(this.trackUrls).filter(p=>!a.isInvariantQuality(p.track.quality)&&a.isHigher(p.track.quality,e)),f=h.length;f&&(o=h[f-1].track)}o&&(l=o.quality)}else if(!e){const d=Object.values(this.trackUrls).map(u=>u.track);o=hi(d,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}o&&(this.params.output.currentVideoTrack$.next(o),this.params.desiredState.videoTrack.startTransitionTo(o)),this.params.output.autoVideoTrackLimits$.next({max:l})}}const Il=["stun:videostun.mycdn.me:80"],uT=1e3,dT=3,Pa=()=>null;class cT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Pa,this.externalStopCallback=Pa,this.externalErrorCallback=Pa,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.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 F(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 F(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Il}]};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 F(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 F(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 F(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 F(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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),uT)}normalizeOptions(e={}){const t={stunServerList:Il,maxRetryNumber:dT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));class hT{constructor(e){this.videoState=new ee(se.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.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(se.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case se.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(se.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case se.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=gt(e.container),this.liveStreamClient=new cT(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=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=St(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));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)===se.READY&&this.videoState.setState(se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(vt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case se.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},i)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:a.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.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(se.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Rl{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 _a,Da,Ia,Ra,Ca,La,xa,Na,Fs,Oa,Us,Ba,js,Ma,Hs,Va,Gs,Fa,Ys,Ua;const Pd=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Vt=document.createElement("video"),fT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',pT='video/mp4; codecs="hev1.1.6.L93.B0"',_d='video/webm; codecs="vp09.00.10.08"',Dd='video/webm; codecs="av01.0.00M.08"',mT='audio/mp4; codecs="mp4a.40.2"',vT='audio/webm; codecs="opus"',Se={mms:!!(window.ManagedMediaSource&&(!((Da=(_a=window.ManagedSourceBuffer)===null||_a===void 0?void 0:_a.prototype)===null||Da===void 0)&&Da.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Ra=(Ia=window.SourceBuffer)===null||Ia===void 0?void 0:Ia.prototype)===null||Ra===void 0)&&Ra.appendBuffer)),hls:!!(!((Ca=Vt.canPlayType)===null||Ca===void 0)&&Ca.call(Vt,"application/x-mpegurl")||!((La=Vt.canPlayType)===null||La===void 0)&&La.call(Vt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},je={mp4:!!(!((xa=Vt.canPlayType)===null||xa===void 0)&&xa.call(Vt,"video/mp4")),webm:!!(!((Na=Vt.canPlayType)===null||Na===void 0)&&Na.call(Vt,"video/webm")),cmaf:!0},pt={h264:!!(!((Oa=(Fs=window.MediaSource||window.ManagedMediaSource)===null||Fs===void 0?void 0:Fs.isTypeSupported)===null||Oa===void 0)&&Oa.call(Fs,fT)),h265:!!(!((Ba=(Us=window.MediaSource||window.ManagedMediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||Ba===void 0)&&Ba.call(Us,pT)),vp9:!!(!((Ma=(js=window.MediaSource||window.ManagedMediaSource)===null||js===void 0?void 0:js.isTypeSupported)===null||Ma===void 0)&&Ma.call(js,_d)),av1:!!(!((Va=(Hs=window.MediaSource||window.ManagedMediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||Va===void 0)&&Va.call(Hs,Dd)),aac:!!(!((Fa=(Gs=window.MediaSource||window.ManagedMediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||Fa===void 0)&&Fa.call(Gs,mT)),opus:!!(!((Ua=(Ys=window.MediaSource||window.ManagedMediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||Ua===void 0)&&Ua.call(Ys,vT))},Ei=(pt.h264||pt.h265)&&pt.aac;var Mt;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(Mt||(Mt={}));var It;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(It||(It={}));let ii;const gT=()=>F(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={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({},s),{video:Object.assign(Object.assign({},s.video),{contentType:Dd})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:_d})}))]);ii={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{gT()}catch(s){console.error(s)}const ds=Se.hls&&je.mp4,bT=()=>Object.keys(pt).filter(s=>pt[s]),ST=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case exports.VideoFormat.DASH:return Se.mse&&je.mp4&&Ei;case exports.VideoFormat.DASH_SEP:return(Se.mse||Se.mms&&t)&&je.mp4&&Ei;case exports.VideoFormat.DASH_WEBM:return(Se.mse||Se.mms&&t)&&je.webm&&pt.vp9&&pt.opus;case exports.VideoFormat.DASH_WEBM_AV1:return(Se.mse||Se.mms&&t)&&je.webm&&pt.av1&&pt.opus;case exports.VideoFormat.DASH_LIVE:return Se.mse&&je.mp4&&Ei;case exports.VideoFormat.DASH_LIVE_CMAF:return(Se.mse||Se.mms&&t)&&je.mp4&&Ei&&je.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return(Se.mse||Se.mms&&t)&&je.mp4&&Ei;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ds||e&&Se.mse&&je.mp4&&Ei;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ds;case exports.VideoFormat.MPEG:return je.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Se.webrtc&&Se.ws&&pt.h264&&(je.mp4||je.webm);default:return a.assertNever(i)}}),ts=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case Mt.VP9:return[e,t];case Mt.AV1:return[t,e];case Mt.NONE:return[];case Mt.SMOOTH:return ii?ii[t].smooth?[t,e]:ii[e].smooth?[e,t]:[t,e]:[e,t];case Mt.POWER_EFFICIENT:return ii?ii[t].powerEfficient?[t,e]:ii[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(s)}return[e,t]},yT=({webmCodec:s,androidPreferredFormat:e})=>{if(Pd)switch(e){case It.MPEG:return[exports.VideoFormat.MPEG,...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case It.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case It.DASH:return[...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return ds?[...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},TT=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],r=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...r],o=[...r,...i];let l;if(Pd)switch(s){case It.DASH:{l=n;break}case It.HLS:case It.MPEG:{l=o;break}}else ds?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},Cl=s=>s?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var ET=s=>new a.Observable(e=>{const t=new a.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.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),s.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const $T={cacheDuration:12e4},kT={chunkDuration:5e3,maxParallelRequests:5};class wT{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=ST([...TT(this.params.tuning),...yT(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>a.isNonNullable(e.sources[l]));console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(t);const{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let n=[];i?n=[i]:r.length?n=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Rl(n);const o=[...Cl(!0),...Cl(!1)];this.chromecastFormatsIterator=new Rl(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 i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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,i=this.params.desiredState.seekState.getState(),r=i.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?i.position:t,forcePrecise:r?i.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 Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,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 wS(Object.assign(Object.assign({},o),{source:l,config:$T}))}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 cl(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new tT(Object.assign(Object.assign({},o),{source:l})):new n0(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 cl(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new sT(Object.assign(Object.assign({},o),{source:l})):new iT(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),ds||!this.params.tuning.useHlsJs?new oT(Object.assign(Object.assign({},o),{source:l})):new rT(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 nT(Object.assign(Object.assign({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new lT(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new yS(Object.assign(Object.assign({},o),{source:l,config:Object.assign(Object.assign({},kT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new hT({container:i,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:i,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Rb({connection:l,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ae.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 i=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:i(e.url)})}return ni(Object.entries(e).map(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,i=0;const r=a.now();return e.add(a.merge(this.providerOutput.error$,ET({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(n=>({id:`ProviderHangup:${n}`,category:a.ErrorCategory.WTF,message:`A ${n} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const n=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(n)})),e.add(this.providerError$.subscribe(n=>{const o=this.current$.getValue().destination;if(o===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const l=n.category===a.ErrorCategory.NETWORK,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit,c=d&&(l&&t||!u),h=n.id.includes("partial_metadata"),f=a.now()-r;c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):h&&f<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():u?(i++,this.reinitProvider()):this.switchToNextProvider(o!=null?o:Ae.SCREEN)}})),e}}const AT=5e3,Ll="one_video_throughput",xl="one_video_rtt",Rt=window.navigator.connection,Nl=()=>{const s=Rt==null?void 0:Rt.downlink;if(a.isNonNullable(s)&&s!==10)return s*1e3},Ol=()=>{const s=Rt==null?void 0:Rt.rtt;if(a.isNonNullable(s)&&s!==3e3)return s},Bl=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class ns{constructor(e){var t,i;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ns.load(Ll)||(e.useBrowserEstimation?Nl():void 0)||AT,n=(i=(t=ns.load(xl))!==null&&t!==void 0?t:e.useBrowserEstimation?Ol():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Bl(r,n,e.rttPenaltyRequestSize)),this.throughput=mn.getSmoothedValue(r,-1,e),this.rtt=mn.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Nl();d&&this.throughput.next(d);const u=Ol();a.isNonNullable(u)&&this.rtt.next(u)};Rt&&"onchange"in Rt&&this.subscription.add(a.fromEvent(Rt,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(Ll,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(xl,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})=>Bl(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,i=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,i=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=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-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){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),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=({done:c,value:h})=>F(this,void 0,void 0,function*(){if(c)!t&&this.addRawSpeed(r,a.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(a.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=h.byteLength;else{const p=l-n;p&&this.addRawSpeed(o,p,1,t),o=h.byteLength,n=a.now()}l=a.now()}else 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 i==null?void 0:i.read().then(u,d)}});this.concurrentDownloads.add(e),i==null||i.read().then(u,d)}addRawSpeed(e,t,i=1,r=!1){if(ns.sanityCheck(e,t,r)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=a.safeStorage.get(e);if(a.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Ml={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:a.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Mt.VP9,androidPreferredFormat:It.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},PT=s=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(s,Ml)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Ml.configName]})};var Vl=({seekState:s,position$:e})=>a.merge(s.stateChangeEnded$.pipe(a.map(({to:t})=>{var i;return t.state===Y.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>s.getState().state===Y.None))),_T=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return a.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const DT=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class IT{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ee(exports.PlaybackState.STOPPED),seekState:new ee({state:Y.None}),volume:new ee({volume:1,muted:!1}),videoTrack:new ee(void 0),autoVideoTrackSwitching:new ee(!0),autoVideoTrackLimits:new ee({}),isLooped:new ee(!1),playbackRate:new ee(1),externalTextTracks:new ee([]),internalTextTracks:new ee([]),currentTextTrack:new ee(void 0),textTrackCuesSettings:new ee({}),cameraOrientation:new ee({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:eS},this.initLogs(),this.tuning=PT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Vd({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ns(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,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(i)}`,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,i,r;return this.config=e,this.domContainer=_T(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new wT({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},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,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?a.fromEvent(document,"visibilitychange").pipe(a.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return DT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),n=i.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(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===Y.None?void 0:t.position;return a.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||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===Y.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:Y.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===Y.Applying&&(this.desiredState.seekState.setState({state:Y.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:Vl({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))*1e3<this.tuning.live.activeLiveDelay),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Vl({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 i=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>i.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,i).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.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((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:n})=>n===r),i||this.setAutoQuality(!0)),i||(i=hi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.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),Zb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Xb(i)),this.providerContainer.current$.subscribe(({type:i})=>Os("provider",i)),t.duration$.subscribe(i=>Os("duration",i)),t.availableVideoTracks$.pipe(a.filter(i=>!!i.length),a.once()).subscribe(i=>Os("tracks",i)),this.events.fatalError$.subscribe(new ct("fatalError")),this.events.managedError$.subscribe(new ct("managedError")),t.position$.subscribe(new ct("position")),t.currentVideoTrack$.pipe(a.map(i=>i==null?void 0:i.quality)).subscribe(new ct("quality")),this.info.currentBuffer$.subscribe(new ct("buffer")),t.isBuffering$.subscribe(new ct("isBuffering"))].forEach(i=>this.subscription.add(i)),Os("codecs",bT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>F(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||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const RT=`@vkontakte/videoplayer-core@${Fl}`;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=IT;exports.SDK_VERSION=RT;exports.VERSION=Fl;
|
|
45
|
+
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class bd{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,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 i0(this.params.fov,this.params.orientation),this.cameraRotationManager=new s0(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"),i=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(i),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(i,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(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(r0,this.gl.VERTEX_SHADER),i=this.createShader(a0,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),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,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),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,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,n=e-i,o=t-r,l=e+i,d=t-r,u=e+i,c=t+r,h=e-i,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}}let Sd=class{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(le.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ad,this.textTracks=[],this.syncPlayback=()=>{var t,i,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===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==le.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==le.STOPPED&&(this.videoState.startTransitionTo(le.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(le.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case le.STOPPED:this.videoState.startTransitionTo(le.READY),this.prepare();return;case le.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(le.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case le.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(le.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case le.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(le.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var i,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.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=gt(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(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new t0({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=St(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:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,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$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.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(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(xt(this.video,t.playbackRate,i.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===ze.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((g,y)=>y.bitrate-g.bitrate),m=Array.from(f.video).sort((g,y)=>y.bitrate-g.bitrate),b=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const y=dy(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=uy(g);if(y){h.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&cy(p,m,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(h);for(const g of b){const y=hy(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===ze.REPRESENTATIOS_READY&&(this.videoState.setState(le.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!==ze.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(ye.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(ye.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,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=Ne(this.video.buffered,this.video.currentTime*1e3),p=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=hi(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=d?S!=null?S:c:c!=null?c:S;return g&&((l=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||l===void 0?void 0:l.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(le.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}},n0=class extends Sd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var Te;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(Te||(Te={}));var dt;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(dt||(dt={}));var lr;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(lr||(lr={}));var Qe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Qe||(Qe={}));var G;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(G||(G={}));var Li;(function(s){s.MP4="mp4",s.WEBM="webm"})(Li||(Li={}));var ur;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ur||(ur={}));var ue;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ue||(ue={}));var wa,Aa;let yd=!1;try{yd=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Aa=(wa=navigator.userAgent.match(/Version\/(\d+)/))===null||wa===void 0?void 0:wa[1])!==null&&Aa!==void 0?Aa:"",10)<16}catch(s){console.error(s)}class o0{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 i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return F(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})})}remove(e,t,i){return F(this,void 0,void 0,function*(){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return F(this,void 0,void 0,function*(){return new Promise(t=>{let i;yd&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),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:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,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)}}}class Ze{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 Td extends Ze{}class l0 extends Ze{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class u0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class d0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class c0 extends Ze{constructor(e){super(e),this.data=this.content}}class Ot extends Ze{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class h0 extends Ot{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 i=this.readUint32();const r=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class f0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class p0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}var ai;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(ai||(ai={}));class m0 extends Ot{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=ai.MONOSCOPIC;break;case 1:this.stereoMode=ai.TOP_BOTTOM;break;case 2:this.stereoMode=ai.LEFT_RIGHT;break;case 3:this.stereoMode=ai.STEREO_CUSTOM;break;case 4:this.stereoMode=ai.RIGHT_LEFT;break}this.cursor+=1}}class v0 extends Ot{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class g0 extends Ot{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class b0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class S0 extends Ot{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 y0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class T0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class E0 extends Ot{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class $0 extends Ze{parseChildrenBoxes(){return Gt(this.content)}}class k0 extends Ot{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 w0 extends Ot{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 A0 extends Ot{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 P0={ftyp:l0,moov:u0,moof:d0,mdat:c0,sidx:h0,trak:f0,mdia:b0,mfhd:E0,tkhd:S0,traf:$0,tfhd:k0,tfdt:w0,trun:A0,minf:y0,sv3d:p0,st3d:m0,prhd:v0,proj:T0,equi:g0,unknown:Td};class _0{createBox(e,t){const i=P0[e];return i?new i(t):new Td(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ar.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Ar=new _0;function ss(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(o=>o.charCodeAt(0));let r=s.byteOffset,n=[];for(;r<t.byteLength;){if(t[r]===i[n.length]?n.push(t[r]):n=[],n.length===4){const l=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+l>s.buffer.byteLength?null:Ar.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function hn(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=ss(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function Gt(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Ar.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const D0=new TextDecoder("ascii"),I0=s=>D0.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",R0=s=>{const e=Ar.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.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:G.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},C0=s=>{const e=hn(s,"mdat"),t=hn(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],n=i.source.byteOffset,l=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,n,l)},L0=(s,e)=>{const t=hn(s,"traf"),i=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=i.defaultSampleDuration*n.sampleCount,(Number(r.baseMediaDecodeTime)+o)/e*1e3},x0=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(ss(s,"sv3d")){e.is3dVideo=!0;const i=ss(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=ss(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=ss(s,"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},N0={validateData:I0,parseInit:x0,getIndexRange:()=>{},parseSegments:R0,parseFeedableSegmentChunk:C0,getSegmentEndTime:L0};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var L;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(L||(L={}));const $l={[k.EBML]:{type:L.Master},[k.EBMLVersion]:{type:L.UnsignedInteger},[k.EBMLReadVersion]:{type:L.UnsignedInteger},[k.EBMLMaxIDLength]:{type:L.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:L.UnsignedInteger},[k.DocType]:{type:L.String},[k.DocTypeVersion]:{type:L.UnsignedInteger},[k.DocTypeReadVersion]:{type:L.UnsignedInteger},[k.Void]:{type:L.Binary},[k.Segment]:{type:L.Master},[k.SeekHead]:{type:L.Master},[k.Seek]:{type:L.Master},[k.SeekID]:{type:L.Binary},[k.SeekPosition]:{type:L.UnsignedInteger},[k.Info]:{type:L.Master},[k.TimestampScale]:{type:L.UnsignedInteger},[k.Duration]:{type:L.Float},[k.Tracks]:{type:L.Master},[k.TrackEntry]:{type:L.Master},[k.Video]:{type:L.Master},[k.Projection]:{type:L.Master},[k.ProjectionType]:{type:L.UnsignedInteger},[k.ProjectionPrivate]:{type:L.Master},[k.Chapters]:{type:L.Master},[k.Cluster]:{type:L.Master},[k.Timestamp]:{type:L.UnsignedInteger},[k.SilentTracks]:{type:L.Master},[k.SilentTrackNumber]:{type:L.UnsignedInteger},[k.Position]:{type:L.UnsignedInteger},[k.PrevSize]:{type:L.UnsignedInteger},[k.SimpleBlock]:{type:L.Binary},[k.BlockGroup]:{type:L.Master},[k.EncryptedBlock]:{type:L.Binary},[k.Attachments]:{type:L.Master},[k.Tags]:{type:L.Master},[k.Cues]:{type:L.Master},[k.CuePoint]:{type:L.Master},[k.CueTime]:{type:L.UnsignedInteger},[k.CueTrackPositions]:{type:L.Master},[k.CueTrack]:{type:L.UnsignedInteger},[k.CueClusterPosition]:{type:L.UnsignedInteger},[k.CueRelativePosition]:{type:L.UnsignedInteger},[k.CueDuration]:{type:L.UnsignedInteger},[k.CueBlockNumber]:{type:L.UnsignedInteger},[k.CueCodecState]:{type:L.UnsignedInteger},[k.CueReference]:{type:L.Master},[k.CueRefTime]:{type:L.UnsignedInteger}},Ed=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=dr(s,t),r=i in $l,n=r?$l[i].type:L.Binary,o=s.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(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=dr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},dr=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*Math.pow(2,16)+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*Math.pow(2,32)+s.getUint32(1);case 6:return s.getUint16(0)*Math.pow(2,32)+s.getUint32(2);case 7:{const t=s.getUint8(0)*Math.pow(2,48)+s.getUint16(1)*Math.pow(2,32)+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ft=(s,e)=>{switch(e){case L.SignedInteger:return s.getInt8(0);case L.UnsignedInteger:return dr(s);case L.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case L.String:return new TextDecoder("ascii").decode(s);case L.UTF8:return new TextDecoder("utf-8").decode(s);case L.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case L.Master:return s;case L.Binary:return s;default:a.assertNever(e)}},xi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=Ed(i);if(!e(r))return;r.type===L.Master&&xi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},O0=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=Ed(s);return xi(r.value,({tag:n,type:o,value:l})=>(n===k.EBMLReadVersion?e=ft(l,o):n===k.DocType?t=ft(l,o):n===k.DocTypeReadVersion&&(i=ft(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},$d=[k.Info,k.SeekHead,k.Tracks,k.TrackEntry,k.Video,k.Projection,k.ProjectionType,k.ProjectionPrivate,k.Chapters,k.Cluster,k.Cues,k.Attachments,k.Tags],B0=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],M0=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return xi(s,({tag:f,type:p,value:m,valueSize:b})=>{if(f===k.SeekID){const S=ft(m,p);u=dr(S)}else f!==k.SeekPosition&&(u=void 0);return f===k.Segment?(e=m.byteOffset,t=m.byteOffset+b):f===k.Info?n=!0:f===k.SeekHead?o=!0:f===k.TimestampScale?i=ft(m,p):f===k.Duration?r=ft(m,p):f===k.SeekPosition&&u===k.Cues?d=ft(m,p):f===k.Tracks?xi(m,({tag:S,type:g,value:y})=>S===k.ProjectionType?(c=ft(y,g)===1,!1):!0):n&&o&&$d.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"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},V0=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},F0=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return xi(s,({tag:l,type:d,value:u})=>{switch(l){case k.Cues:t=!0;break;case k.CuePoint:o&&r(o)&&n.push(o),o={};break;case k.CueTime:o&&(o.time=ft(u,d));break;case k.CueTrackPositions:break;case k.CueClusterPosition:o&&(o.position=ft(u,d));break;default:t&&$d.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:G.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},U0=s=>{let e=0,t=!1;try{xi(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):B0.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},j0={validateData:O0,parseInit:M0,getIndexRange:V0,parseSegments:F0,parseFeedableSegmentChunk:U0},kl=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},$i=(s,e)=>{let t=s;t=or(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},H0=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,m,b,S,g,y,v,T,E,P,N,V,x,B,M,D,I,U,R,_,O,z,te,ne,me,Re,Ye,q;const Ce=new DOMParser().parseFromString(s,"application/xml"),ve={video:[],audio:[],text:[]},ce=Ce.children[0],Tt=ce.getElementsByTagName("Period")[0],Et=Tt.children,Bt=ce.getAttribute("type")==="dynamic",$t=ce.getAttribute("availabilityStartTime"),fi=$t?new Date($t).getTime():void 0;let ke;const Fi=ce.getAttribute("mediaPresentationDuration"),Ui=Tt.getAttribute("duration"),Yt=ce.getElementsByTagName("vk:Attrs")[0],ji=Yt==null?void 0:Yt.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Fi)ke=kl(Fi);else if(Ui){const oe=kl(Ui);a.isNonNullable(oe)&&(ke=oe)}else ji&&(ke=parseInt(ji,10));let Pr=0;const zt=(i=(t=ce.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],_r=zt.includes(lr.WEBM_AS_IN_FFMPEG)||zt.includes(lr.WEBM_AS_IN_SPEC)?Li.WEBM:Li.MP4;for(const oe of Et){const kt=oe.getAttribute("mimeType"),Dr=oe.getAttribute("codecs"),Hi=(r=oe.getAttribute("contentType"))!==null&&r!==void 0?r:kt==null?void 0:kt.split("/")[0],Ir=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gi=oe.querySelectorAll("Representation"),Rr=oe.querySelector("SegmentTemplate");if(Hi===Te.TEXT){for(const j of Gi){const ge=j.getAttribute("id")||"",wt=oe.getAttribute("lang"),Oe=(u=(d=(l=j.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",qt=new URL(Oe,e).toString(),Wt=ge.includes("_auto");ve[Te.TEXT].push({id:ge,lang:wt,isAuto:Wt,kind:Te.TEXT,url:qt})}continue}for(const j of Gi){const ge=(c=j.getAttribute("mimeType"))!==null&&c!==void 0?c:kt,wt=(f=(h=j.getAttribute("codecs"))!==null&&h!==void 0?h:Dr)!==null&&f!==void 0?f:"",Oe=(m=(p=j.getAttribute("contentType"))!==null&&p!==void 0?p:ge==null?void 0:ge.split("/")[0])!==null&&m!==void 0?m:Hi,qt=(S=(b=oe.getAttribute("profiles"))===null||b===void 0?void 0:b.split(","))!==null&&S!==void 0?S:[],Wt=parseInt((g=j.getAttribute("width"))!==null&&g!==void 0?g:"",10),Yi=parseInt((y=j.getAttribute("height"))!==null&&y!==void 0?y:"",10),zi=parseInt((v=j.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,qi=(T=j.getAttribute("frameRate"))!==null&&T!==void 0?T:"",Cr=(E=j.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Lr=qi?$r(qi):void 0,xr=(P=j.getAttribute("id"))!==null&&P!==void 0?P:(Pr++).toString(10),Nr=Oe==="video"?`${Yi}p`:Oe==="audio"?`${zi}Kbps`:wt,Or=`${xr}@${Nr}`,Br=(x=(V=(N=j.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||V===void 0?void 0:V.trim())!==null&&x!==void 0?x:"",Wi=new URL(Br,e).toString(),Mr=[...zt,...Ir,...qt];let Qt;const Vr=j.querySelector("SegmentBase"),we=(B=j.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Rr;if(Vr){const Be=(D=(M=j.querySelector("SegmentBase Initialization"))===null||M===void 0?void 0:M.getAttribute("range"))!==null&&D!==void 0?D:"",[Me,Jt]=Be.split("-").map(Ve=>parseInt(Ve,10)),Le={from:Me,to:Jt},et=(I=j.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Xt,At]=et?et.split("-").map(Ve=>parseInt(Ve,10)):[],tt=et?{from:Xt,to:At}:void 0;Qt={type:Qe.BYTE_RANGE,url:Wi,initRange:Le,indexRange:tt}}else if(we){const Be={representationId:(U=j.getAttribute("id"))!==null&&U!==void 0?U:void 0,bandwidth:(R=j.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Me=parseInt((_=we.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Jt=(O=we.getAttribute("initialization"))!==null&&O!==void 0?O:"",Le=we.getAttribute("media"),et=(te=parseInt((z=we.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&te!==void 0?te:1,Xt=$i(Jt,Be);if(!Le)throw new ReferenceError("No media attribute in SegmentTemplate");const At=(ne=we.querySelectorAll("SegmentTimeline S"))!==null&&ne!==void 0?ne:[],tt=[];let Ve=0,Zt="",Fe=0;if(At.length){let Ue=et,he=0;for(const it of At){const xe=parseInt((me=it.getAttribute("d"))!==null&&me!==void 0?me:"",10),ot=parseInt((Re=it.getAttribute("r"))!==null&&Re!==void 0?Re:"",10)||0,Pt=parseInt((Ye=it.getAttribute("t"))!==null&&Ye!==void 0?Ye:"",10);he=Number.isFinite(Pt)?Pt:he;const Qi=xe/Me*1e3,pi=he/Me*1e3;for(let mi=0;mi<ot+1;mi++){const Id=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:Ue.toString(10),segmentTime:(he+mi*xe).toString(10)})),Yn=(pi!=null?pi:0)+mi*Qi,Rd=Yn+Qi;Ue++,tt.push({time:{from:Yn,to:Rd},url:Id})}he+=(ot+1)*xe,Ve+=(ot+1)*Qi}Fe=he/Me*1e3,Zt=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:Ue.toString(10),segmentTime:he.toString(10)}))}else if(a.isNonNullable(ke)){const he=parseInt((q=we.getAttribute("duration"))!==null&&q!==void 0?q:"",10)/Me*1e3,it=Math.ceil(ke/he);let xe=0;for(let ot=1;ot<it;ot++){const Pt=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:ot.toString(10),segmentTime:xe.toString(10)}));tt.push({time:{from:xe,to:xe+he},url:Pt}),xe+=he}Fe=xe,Zt=$i(Le,Object.assign(Object.assign({},Be),{segmentNumber:it.toString(10),segmentTime:xe.toString(10)}))}const ei={time:{from:Fe,to:1/0},url:Zt};Qt={type:Qe.TEMPLATE,baseUrl:Wi,segmentTemplateUrl:Le,initUrl:Xt,totalSegmentsDurationMs:Ve,segments:tt,nextSegmentBeyondManifest:ei,timescale:Me}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Oe||!ge)continue;const Kt={video:Te.VIDEO,audio:Te.AUDIO,text:Te.TEXT}[Oe];Kt&&ve[Kt].push({id:Or,kind:Kt,segmentReference:Qt,profiles:Mr,duration:ke,bitrate:zi,mime:ge,codecs:wt,width:Wt,height:Yi,fps:Lr,quality:Cr})}}return{dynamic:Bt,liveAvailabilityStartTime:fi,duration:ke,container:_r,representations:ve}},G0=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Mi(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},Y0=({id:s,bitrate:e})=>({id:s,bitrate:e}),z0=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=be(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:be(s,-1)},q0=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),wl=s=>"size"in s,Ti=s=>s.type===Qe.TEMPLATE,fn=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class Al{constructor(e,t,i,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 Ke,this.destroyAbortController=new Ke,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 Z(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 o0(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),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(S=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield yield w(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 w(void 0);this.searchGaps(m,f),yield yield w(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 Z(this,arguments,function*(){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return yield w(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 w(this.loadInit(f,"high",!1)):m instanceof Promise&&(yield yield w(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 w(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield yield w(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const b=this.getCurrentPosition();a.isNonNullable(b)&&(this.isLive||(p.forEach(S=>S.status=G.NONE),this.pruneBuffer(b,1/0,!0)),this.maintain(b))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(h){var f;return Z(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return yield w(void 0);for(const y of this.representations.keys()){const v=h.find(P=>P.id===y);v&&this.representations.set(y,v);const T=this.representations.get(y);if(!T||!Ti(T.segmentReference))return yield w(void 0);const E=this.getActualLiveStartingSegments(T.segmentReference);this.segments.set(T.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 S=this.initData.get(p);if(a.assertNonNullable(S,"No init buffer for starting representation"),!(S instanceof ArrayBuffer))return yield w(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield w(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(b,m),yield yield w(this.sourceBufferTaskQueue.append(S,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=i,i){case Li.MP4:this.containerParser=N0;break;case Li.WEBM:this.containerParser=j0;break;default:a.assertNever(i)}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 Ke,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),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Ne(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&r.time.to-e<this.tuning.dash.maxSegmentDurationLeftToSelectNextSegment&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ne(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(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=be(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===G.FED&&!l.length&&Ne(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=be(i,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+r}),i=n.time.to;a.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=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<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,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 i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Ti(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:G.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(r=be(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 i of this.representations.values()){const r=i.segmentReference;if(!Ti(r))return;const n=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),o=$i(r.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(i.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:G.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i: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,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const b=f<=i&&p>=i,S=f>i||b||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=i+g||p<=i+g;return(h===G.NONE||h===G.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!Ri(this.sourceBuffer.buffered,i))&&S&&y});if(r===-1)return[];if(t!==Qe.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===G.NONE||f.status===G.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,i="auto"){return F(this,void 0,void 0,function*(){t.segmentReference.type===Qe.TEMPLATE?yield this.loadTemplateSegment(e[0],t,i):yield this.loadByteRangeSegments(e,t,i)})}loadTemplateSegment(e,t,i="auto"){return F(this,void 0,void 0,function*(){e.status=G.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,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(yield a.abortable(l,function(){return Z(this,arguments,function*(){const c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield w(new Promise(h=>setTimeout(h,c)))})}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const c=yield this.fetcher.fetch(o,{range:n,signal:l,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;const h=new DataView(c);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}d&&r.feedingBytes&&u?yield Promise.all(u):yield this.sourceBufferTaskQueue.append(h,l),r.segment.status=G.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){if(!fn(c))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(c)}})}loadByteRangeSegments(e,t,i="auto"){return F(this,void 0,void 0,function*(){if(!e.length)return;for(const d of e)d.status=G.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 Z(this,arguments,function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield w(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:i}),this.failedDownloads=0}catch(d){if(!fn(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}})}prepareByteRangeFetchSegmentParams(e,t){if(Ti(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:be(e,0).byte.from,to:be(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,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(!Ti(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},l=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});l.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:r,signal:n,onProgress:u,onProgressTasks:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=Ne((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:n}){return F(this,void 0,void 0,function*(){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:d}=l;if(l.representationId===t){if(n.aborted){r();continue}if(l.loadedBytes=i,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=G.PARTIALLY_FED,l.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),l.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,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===Qe.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const b=f?h.byte.from-i:0,S=f?h.byte.to-i:e.byteLength,g=b<r,y=S<=r;if(h.status===G.DOWNLOADING&&g&&y){h.status=G.DOWNLOADED;const v=new DataView(e.buffer,e.byteOffset+b,p);this.sourceBufferTaskQueue.append(v,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(c,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(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),T=c.loadedBytes===p?v:this.containerParser.parseFeedableSegmentChunk(v);T!=null&&T.byteLength&&(h.status=G.PARTIALLY_FED,c.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(E=>{if(n.aborted)o();else if(E)c.fedBytes+=T.byteLength,c.fedBytes===p&&this.onSegmentFullyAppended(c,t);else{if(c.feedingBytes<p)return;o()}}))}}}onSegmentFullyAppended(e,t){var i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=G.FED,wl(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const n of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])n.status===G.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=G.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);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 i=this.representations.get(e);i&&(this.initLoadIdleCallback=rr(()=>Ss(this.loadInit(i,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",i=!1){return F(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Z(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield w(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>F(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&&Ti(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),i&&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,i=!1){return F(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=wl(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===G.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===G.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===G.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){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===G.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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 i of t){let r={representation:e,from:i.time.from,to:i.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<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.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=rr(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==G.FED&&n!==G.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=G.PARTIALLY_EJECTED:r.status=G.NONE)}}}var _i;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(_i||(_i={}));class W0{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!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 Ke,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,function(r){return Z(this,arguments,function*(){let n=r;this.requestQuic&&(n=Ut(n));const o=yield yield w(li(n,{signal:this.abortAllController.signal}).catch(Zi));return o?(this.onHeadersReceived(o.headers),yield w(o.text())):yield w(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(r,{rangeMethod:n=this.compatibilityMode?_i.HEADER:_i.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0,isLowLatency:h=!1}={}){var f,p;return Z(this,arguments,function*(){let m=r;const b=new Headers;if(o)switch(n){case _i.HEADER:{b.append("Range",`bytes=${o.from}-${o.to}`);break}case _i.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=Ut(m));let S=this.abortAllController.signal,g;if(u){const I=new Ke;if(g=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{I.abort()}catch(U){Zi(U)}}),this.abortAllController.signal.aborted||u.aborted)try{I.abort()}catch(U){Zi(U)}S=I.signal}const y=a.now(),v=yield yield w(li(m,{priority:d,headers:b,signal:S}).catch(Zi)),T=a.now();if(!v)return g==null||g.unsubscribe(),yield w(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!v.ok||!v.body)return g==null||g.unsubscribe(),yield w(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));if(this.onHeadersReceived(v.headers),!l&&!c)return g==null||g.unsubscribe(),yield w(v.arrayBuffer());const[E,P]=v.body.tee(),N=E.getReader();c&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(P,h));let V=0,x=new Uint8Array(0),B=!1;const M=I=>{g==null||g.unsubscribe(),B=!0,Zi(I)},D=a.abortable(S,function({done:I,value:U}){return Z(this,arguments,function*(){if(V===0&&this.lastRequestFirstBytes$.next(a.now()-y),S.aborted)return g==null||g.unsubscribe(),yield w(void 0);if(!I&&U){const R=new Uint8Array(x.length+U.length);R.set(x),R.set(U,x.length),x=R,V+=U.byteLength,l==null||l(new DataView(x.buffer),V),yield yield w(N==null?void 0:N.read().then(D,M))}})}.bind(this));return yield yield w(N==null?void 0:N.read().then(D,M)),g==null||g.unsubscribe(),yield w(B?null:x.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return Z(this,arguments,function*(){if(r.type!==Qe.BYTE_RANGE)return yield w(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 w(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!b)return yield w(null);const S=new DataView(b,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const g=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let v;if(f)v=new DataView(b,y.from-c,y.to-y.from+1);else{const E=yield yield w(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!E)return yield w(null);v=new DataView(E)}const T=n.parseSegments(v,g,y);return yield w({init:g,dataView:new DataView(b),segments:T})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return Z(this,arguments,function*(){if(r.type!==Qe.TEMPLATE)return yield w(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield w(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield w(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:G.NONE,size:void 0}));return yield w({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Un(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}fetchRepresentation(e,t,i="auto"){var r,n;return F(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case Qe.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Qe.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Zi=s=>{if(!fn(s))throw s},pn=1e3,cr=(s,e,t)=>t*e+(1-t)*s,kd=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Q0=(s,e,t,i)=>{let r=0,n=t;const o=kd(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?r++:r--,n=(s.length+n-1)%s.length;return Math.abs(r)===l};class Gn{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 i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ct(`raw_${i}`),this.smoothedSeries$=new ct(`smoothed_${i}`),this.reportedSeries$=new ct(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),i++);this.takenMeasures=i,t/=i;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 K0 extends Gn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=cr(this.slow,e,this.params.emaAlphaSlow),this.fast=cr(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class J0 extends Gn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=kd(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const i=Q0(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class X0 extends Gn{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?cr(this.smoothed,e,this.params.emaAlpha):e}}class mn{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new K0({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new J0({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new X0(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const Z0=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},Pl=["timeupdate","progress","play","seeked","stalled","waiting"];var qe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(qe||(qe={}));let eT=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 ee(qe.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.livePositionFromPlayer$=new a.ValueSubject(0),this.isActiveLowLatency=!1,this.isUpdatingLive=!1,this.isJumpGapAfterSeekLive=!1,this.liveLastSeekOffset=0,this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ke,this.initManifest=a.abortable(this.destroyController.signal,function(t,i,r){var n;return Z(this,arguments,function*(){this.element=t,this.manifestUrlString=_e(i,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(qe.MANIFEST_READY),this.manifest=yield yield w(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(qe.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 Z(this,arguments,function*(){const i=yield yield w(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(!i)return yield w(null);let r;try{r=H0(i!=null?i:"",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 w(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===Te.TEXT)};return r.dynamic&&this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield w(Object.assign(Object.assign({},r),{representations:ni(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}))})}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,function(t,i){return Z(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(qe.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;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 Al(Te.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new Al(Te.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(pn).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=er(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P);this.manifestUrlString=_e(this.manifestUrlString,u+pn,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Pl.map(l=>a.fromEvent(this.element,l))).pipe(a.map(l=>this.element?Ne(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(l=>!!l),a.tap(l=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).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),Z0(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,S;return(S=(b=m.getLiveSegmentsToLoadState(this.manifest))===null||b===void 0?void 0:b.to)!==null&&S!==void 0?S:0}))-f}h&&this.liveLoadBufferLength$.getValue()!==h&&this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(a.combine({liveLoadBufferLength:this.liveLoadBufferLength$,bufferLength:this.bufferLength$}).subscribe(({liveLoadBufferLength:d,bufferLength:u})=>F(this,void 0,void 0,function*(){if(a.assertNonNullable(this.element),this.isUpdatingLive)return;const c=this.element.playbackRate,h=er(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P),f=Math.abs(this.livePositionFromPlayer$.getValue())*1e3,p=Math.min(f,this.tuning.dashCmafLive.normalizedTargetMinBufferSize*c),m=this.tuning.dashCmafLive.normalizedActualBufferOffset*c,b=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,S=this.isActiveLowLatency?u:d;let g=dt.None;if(this.isActiveLowLatency?g=dt.ActiveLowLatency:S<p+b&&S>=p?g=dt.LiveWithTargetOffset:h!==0&&S<p&&(g=dt.LiveForwardBuffering),isFinite(d)&&(l=d>l?d:l),g===dt.LiveForwardBuffering||g===dt.LiveWithTargetOffset){const y=l-(p+m),v=this.normolizeLiveOffset(Math.trunc(h+y/c)),T=Math.abs(v-h);let E;!d||T<=this.tuning.dashCmafLive.offsetCalculationError?E=h:v>0&&T>this.tuning.dashCmafLive.offsetCalculationError?E=v:E=0,this.manifestUrlString=_e(this.manifestUrlString,E,ae.DASH_CMAF_OFFSET_P)}g!==dt.None&&g!==dt.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 w(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(i)?yield yield w(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)])):yield yield w(this.videoBufferManager.startWith(t)),this.state$.setState(qe.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,i;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||!((i=this.audioBufferManager)===null||i===void 0)&&i.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 W0({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=mn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,i,r,n;return F(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const o=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&o===0,this.liveLastSeekOffset=o,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=_e(this.manifestUrlString,o,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),this.manifest&&(yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.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(qe.RUNNING),this.subscription.add(a.merge(...Pl.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&&Ri(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}switchRepresentation(e,t){return F(this,void 0,void 0,function*(){const i={[Te.VIDEO]:this.videoBufferManager,[Te.AUDIO]:this.audioBufferManager,[Te.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)})}seek(e,t){var i,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((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Ri(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(qe.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}waitingEventCallback(){return F(this,void 0,void 0,function*(){try{if(!this.element)return;this.isLive$.getValue()?yield this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:a.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}})}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}updateLive(){var e;return F(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];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?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class wd{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(ue.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new ad,this.textTracks=[],this.syncPlayback=()=>{var t,i,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===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ue.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==ue.STOPPED&&(this.videoState.startTransitionTo(ue.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(ue.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case ue.STOPPED:this.videoState.startTransitionTo(ue.READY),this.prepare();return;case ue.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(ue.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ue.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ue.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ue.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ue.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var i,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.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=gt(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(De(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new eT({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=St(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:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,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$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.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(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(xt(this.video,t.playbackRate,i.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ue.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===qe.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((g,y)=>y.bitrate-g.bitrate),m=Array.from(f.video).sort((g,y)=>y.bitrate-g.bitrate),b=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const y=Y0(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=G0(g);if(y){h.push({track:y,representation:g});const v=!this.params.tuning.isAudioDisabled&&z0(p,m,g);v&&this.audioRepresentations.set(g.id,v)}}this.videoTracks$.next(h);for(const g of b){const y=q0(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===qe.REPRESENTATIOS_READY&&(this.videoState.setState(ue.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!==qe.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(Te.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(Te.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,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=Ne(this.video.buffered,this.video.currentTime*1e3),p=d?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(f/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=hi(this.videoTracks$.getValue().map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=d?S!=null?S:c:c!=null?c:S;return g&&((l=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||l===void 0?void 0:l.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(ue.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){console.log("destroy DASH provider"),this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),bt(this.video)}}class tT extends wd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let iT=class extends Sd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(cn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===le.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(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===le.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)})}};class sT extends wd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(pn),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===ue.PLAYING&&!this.player.isActiveLowLatency){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(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===ue.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 ut={};var X;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));const es=(s,e)=>new a.Observable(t=>{const i=(r,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class rT{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(X.INITIALIZING),this.textTracksManager=new nt,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==X.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===Y.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case X.STOPPED:break;case X.READY:case X.PLAYING:case X.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case X.STOPPED:this.prepare();break;case X.READY:case X.PLAYING:case X.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case X.PLAYING:break;case X.STOPPED:this.prepare();break;case X.READY:case X.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case X.PAUSED:break;case X.STOPPED:this.prepare();break;case X.READY:this.videoState.setState(X.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case X.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(i)}},this.video=gt(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(De(this.params.source.url)),this.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),bt(this.video)}loadHlsJs(){let e=!1;const t=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},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ss(import("hls.js").then(r=>{e||(ut.Hls=r.default,ut.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(ut.Hls,"hls.js not loaded"),this.hls=new ut.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(X.STOPPED)}subscribe(){a.assertNonNullable(ut.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=St(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));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(Ht(this.video,e.isLooped,i)),this.subscription.add(vt(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(xt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(es(this.hls,ut.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(X.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===X.READY&&this.videoState.setState(X.READY),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},i)),n(es(this.hls,ut.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:S}=h,g=(p=Mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:b,height:S});if(!g)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:g,bitrate:h.bitrate/1e3,size:{width:b,height:S},fps:y};return this.trackLevels.set(m,{track:v,level:h}),c.push(v),c},[]))),t.availableVideoTracks$),n(es(this.hls,ut.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(es(this.hls,ut.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>De(u))),t.hostname$),this.subscription.add(rt(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));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=es(this.hls,ut.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(rt(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u.id))===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,onError:i})),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,i))}prepare(){this.videoState.startTransitionTo(X.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return F(this,void 0,void 0,function*(){this.videoState.startTransitionTo(X.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(X.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}pause(){this.videoState.startTransitionTo(X.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(X.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const _l="X-Playback-Duration";var Dl=s=>F(void 0,void 0,void 0,function*(){var e;const t=yield li(s),i=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(_l)?parseInt(t.headers.get(_l),10):void 0});const aT=s=>{let e=null;if(s.QUALITY&&(e=Mi(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=a.videoSizeToQuality({width:t,height:i})}return e!=null?e:null},Ad=(s,e=s)=>F(void 0,void 0,void 0,function*(){var t,i;const o=(yield(yield li(s)).text()).split(`
|
|
46
|
+
`),l=[],d=[];for(let u=0;u<o.length;u++){const c=o[u],h=c.match(/^#EXT-X-STREAM-INF:(.+)/),f=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!h&&!f)){if(h){const p=ni(h[1].split(",").map(T=>T.split("="))),m=(t=p.QUALITY)!==null&&t!==void 0?t:`stream-${p.BANDWIDTH}`,b=aT(p);let S;p.BANDWIDTH&&(S=parseInt(p.BANDWIDTH,10)/1e3||void 0),!S&&p["AVERAGE-BANDWIDTH"]&&(S=parseInt(p["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const g=p["FRAME-RATE"]?parseFloat(p["FRAME-RATE"]):void 0;let y;if(p.RESOLUTION){const[T,E]=p.RESOLUTION.split("x").map(P=>parseInt(P,10));T&&E&&(y={width:T,height:E})}const v=new URL(o[++u],e).toString();b&&l.push({id:m,quality:b,url:v,bandwidth:S,size:y,fps:g})}if(f){const p=ni(f[1].split(",").map(g=>g.split("=")).map(([g,y])=>[g,y.replace(/^"|"$/g,"")])),m=(i=p.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),b=p.LANGUAGE,S=p.NAME;m&&b&&d.push({type:"internal",id:b,label:S,language:b,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}});var ie;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(ie||(ie={}));class nT{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new ee(ie.STOPPED),this.textTracksManager=new nt,this.manifests$=new a.ValueSubject([]),this.liveOffset=new ys,this.manifestStartTime$=new a.ValueSubject(void 0),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(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){r!==ie.STOPPED&&(this.videoState.startTransitionTo(ie.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(ie.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(l||d||u){const f=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:n===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ie.PLAYING),this.playIfAllowed());return;case ie.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ie.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ie.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(ie.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case ie.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},Ad(_e(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:a.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),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(De(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,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));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),i)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===ie.READY&&this.videoState.setState(ie.READY),this.videoState.getState()===ie.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),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.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(De(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===ie.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===Y.Requested&&this.seek(l.position)},i)),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)},i)),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),i)),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$,i));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:u,min:c}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[h,f]of[[u,"mq"],[c,"lq"]]){const p=String(parseFloat(h||""));f&&h&&o.searchParams.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?ae.DASH_CMAF_OFFSET_P:ae.OFFSET_P,d=_e(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",d),this.video.load(),Dl(d).then(u=>{var c;if(!a.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(c=this.params.source.maxSeekBackTime)!==null&&c!==void 0?c:this.maxSeekBackTime$.getValue();if(a.isNullable(h)||!isFinite(h))try{li(d).then(f=>f.text()).then(f=>{var p;const m=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(m){const b=new URL(m,d).toString();Dl(b).then(S=>{a.isNullable(S)||this.maxSeekBackTime$.next(S)})}})}catch(f){}}})}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var re;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(re||(re={}));class oT{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(re.STOPPED),this.textTracksManager=new nt,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===exports.PlaybackState.STOPPED){i!==re.STOPPED&&(this.videoState.startTransitionTo(re.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(re.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(i===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||l||d){const h=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&c.state===Y.Requested&&this.seek(c.position),i){case re.READY:r===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(re.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed());return;case re.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(re.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case re.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(re.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return a.assertNever(i)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ad(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));if(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(Ht(this.video,t.isLooped,i)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===re.READY&&this.videoState.setState(re.READY),this.videoState.getState()===re.PLAYING&&this.playIfAllowed()},i).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.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(De(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===re.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===Y.Requested&&this.seek(l.position)},i))),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$,i)),!a.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(a.merge(a.fromEvent(l,"addtrack"),a.fromEvent(l,"removetrack"),a.fromEvent(l,"change"),a.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<l.length;d++)l[d].mode="hidden"},i))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,c]of[[l,"mq"],[d,"lq"]]){const h=String(parseFloat(u||""));c&&u&&o.searchParams.set(c,h)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var de;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(de||(de={}));class lT{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(de.STOPPED),this.trackUrls={},this.textTracksManager=new nt,this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==de.STOPPED&&(this.videoState.startTransitionTo(de.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(de.STOPPED),A(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!==de.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===de.STOPPED){this.videoState.startTransitionTo(de.READY),this.prepare();return}if(c){const{currentTime:f}=this.video;this.prepare(),h.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:f*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[c.to.id])===null||i===void 0?void 0:i.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===Y.Requested&&this.seek(h.position),n){case de.READY:o===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(de.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed());return;case de.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(de.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case de.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(de.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=gt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),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,i=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));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(Ht(this.video,t.isLooped,i)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(xt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===de.READY&&this.videoState.setState(de.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.id].track)),this.videoState.getState()===de.PLAYING&&this.playIfAllowed()},i)),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,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),bt(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;a.assertNonNullable(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];a.assertNonNullable(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=Ut(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(De(i))}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const d=(i=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||i===void 0?void 0:i.track,u=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,c=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(d&&c&&a.isHigherOrEqual(c.quality,d.quality)&&(o=d),!o){const h=Object.values(this.trackUrls).filter(p=>!a.isInvariantQuality(p.track.quality)&&a.isHigher(p.track.quality,e)),f=h.length;f&&(o=h[f-1].track)}o&&(l=o.quality)}else if(!e){const d=Object.values(this.trackUrls).map(u=>u.track);o=hi(d,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}o&&(this.params.output.currentVideoTrack$.next(o),this.params.desiredState.videoTrack.startTransitionTo(o)),this.params.output.autoVideoTrackLimits$.next({max:l})}}const Il=["stun:videostun.mycdn.me:80"],uT=1e3,dT=3,Pa=()=>null;class cT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Pa,this.externalStopCallback=Pa,this.externalErrorCallback=Pa,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.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 F(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 F(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Il}]};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 F(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 F(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 F(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 F(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),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))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),uT)}normalizeOptions(e={}){const t={stunServerList:Il,maxRetryNumber:dT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(se||(se={}));class hT{constructor(e){this.videoState=new ee(se.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==se.STOPPED&&(this.videoState.startTransitionTo(se.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(se.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===se.STOPPED){this.videoState.startTransitionTo(se.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case se.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(se.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case se.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=gt(e.container),this.liveStreamClient=new cT(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),bt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=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=St(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));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)===se.READY&&this.videoState.setState(se.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(vt(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case se.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case se.READY:break;case se.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case se.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},i)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}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(De(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:a.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(se.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(se.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class Rl{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 _a,Da,Ia,Ra,Ca,La,xa,Na,Fs,Oa,Us,Ba,js,Ma,Hs,Va,Gs,Fa,Ys,Ua;const Pd=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Vt=document.createElement("video"),fT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',pT='video/mp4; codecs="hev1.1.6.L93.B0"',_d='video/webm; codecs="vp09.00.10.08"',Dd='video/webm; codecs="av01.0.00M.08"',mT='audio/mp4; codecs="mp4a.40.2"',vT='audio/webm; codecs="opus"',Se={mms:!!(window.ManagedMediaSource&&(!((Da=(_a=window.ManagedSourceBuffer)===null||_a===void 0?void 0:_a.prototype)===null||Da===void 0)&&Da.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Ra=(Ia=window.SourceBuffer)===null||Ia===void 0?void 0:Ia.prototype)===null||Ra===void 0)&&Ra.appendBuffer)),hls:!!(!((Ca=Vt.canPlayType)===null||Ca===void 0)&&Ca.call(Vt,"application/x-mpegurl")||!((La=Vt.canPlayType)===null||La===void 0)&&La.call(Vt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},je={mp4:!!(!((xa=Vt.canPlayType)===null||xa===void 0)&&xa.call(Vt,"video/mp4")),webm:!!(!((Na=Vt.canPlayType)===null||Na===void 0)&&Na.call(Vt,"video/webm")),cmaf:!0},pt={h264:!!(!((Oa=(Fs=window.MediaSource||window.ManagedMediaSource)===null||Fs===void 0?void 0:Fs.isTypeSupported)===null||Oa===void 0)&&Oa.call(Fs,fT)),h265:!!(!((Ba=(Us=window.MediaSource||window.ManagedMediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||Ba===void 0)&&Ba.call(Us,pT)),vp9:!!(!((Ma=(js=window.MediaSource||window.ManagedMediaSource)===null||js===void 0?void 0:js.isTypeSupported)===null||Ma===void 0)&&Ma.call(js,_d)),av1:!!(!((Va=(Hs=window.MediaSource||window.ManagedMediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||Va===void 0)&&Va.call(Hs,Dd)),aac:!!(!((Fa=(Gs=window.MediaSource||window.ManagedMediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||Fa===void 0)&&Fa.call(Gs,mT)),opus:!!(!((Ua=(Ys=window.MediaSource||window.ManagedMediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||Ua===void 0)&&Ua.call(Ys,vT))},Ei=(pt.h264||pt.h265)&&pt.aac;var Mt;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(Mt||(Mt={}));var It;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(It||(It={}));let ii;const gT=()=>F(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const s={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({},s),{video:Object.assign(Object.assign({},s.video),{contentType:Dd})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},s),{video:Object.assign(Object.assign({},s.video),{contentType:_d})}))]);ii={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{gT()}catch(s){console.error(s)}const ds=Se.hls&&je.mp4,bT=()=>Object.keys(pt).filter(s=>pt[s]),ST=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case exports.VideoFormat.DASH:return Se.mse&&je.mp4&&Ei;case exports.VideoFormat.DASH_SEP:return(Se.mse||Se.mms&&t)&&je.mp4&&Ei;case exports.VideoFormat.DASH_WEBM:return(Se.mse||Se.mms&&t)&&je.webm&&pt.vp9&&pt.opus;case exports.VideoFormat.DASH_WEBM_AV1:return(Se.mse||Se.mms&&t)&&je.webm&&pt.av1&&pt.opus;case exports.VideoFormat.DASH_LIVE:return Se.mse&&je.mp4&&Ei;case exports.VideoFormat.DASH_LIVE_CMAF:return(Se.mse||Se.mms&&t)&&je.mp4&&Ei&&je.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return(Se.mse||Se.mms&&t)&&je.mp4&&Ei;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ds||e&&Se.mse&&je.mp4&&Ei;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ds;case exports.VideoFormat.MPEG:return je.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return Se.webrtc&&Se.ws&&pt.h264&&(je.mp4||je.webm);default:return a.assertNever(i)}}),ts=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case Mt.VP9:return[e,t];case Mt.AV1:return[t,e];case Mt.NONE:return[];case Mt.SMOOTH:return ii?ii[t].smooth?[t,e]:ii[e].smooth?[e,t]:[t,e]:[e,t];case Mt.POWER_EFFICIENT:return ii?ii[t].powerEfficient?[t,e]:ii[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(s)}return[e,t]},yT=({webmCodec:s,androidPreferredFormat:e})=>{if(Pd)switch(e){case It.MPEG:return[exports.VideoFormat.MPEG,...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case It.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case It.DASH:return[...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return ds?[...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...ts(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},TT=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],r=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...r],o=[...r,...i];let l;if(Pd)switch(s){case It.DASH:{l=n;break}case It.HLS:case It.MPEG:{l=o;break}}else ds?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},Cl=s=>s?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var ET=s=>new a.Observable(e=>{const t=new a.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.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),s.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const $T={cacheDuration:12e4},kT={chunkDuration:5e3,maxParallelRequests:5};class wT{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=ST([...TT(this.params.tuning),...yT(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let n=[];i?n=[i]:r.length?n=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Rl(n),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(n);const o=[...Cl(!0),...Cl(!1)];this.chromecastFormatsIterator=new Rl(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(console.log("Choose provider "+t),a.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,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,i=this.params.desiredState.seekState.getState(),r=i.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?i.position:t,forcePrecise:r?i.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 Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new wS(Object.assign(Object.assign({},o),{source:l,config:$T}))}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new cl(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new tT(Object.assign(Object.assign({},o),{source:l}))):new n0(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 cl(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new sT(Object.assign(Object.assign({},o),{source:l})):new iT(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),ds||!this.params.tuning.useHlsJs?new oT(Object.assign(Object.assign({},o),{source:l})):new rT(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 nT(Object.assign(Object.assign({},o),{source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e}))}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new lT(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new yS(Object.assign(Object.assign({},o),{source:l,config:Object.assign(Object.assign({},kT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new hT({container:i,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:i,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Rb({connection:l,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Ae.CHROMECAST:Ae.SCREEN}chooseFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Ae.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case Ae.SCREEN:return this.screenFormatsIterator.next();case Ae.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case Ae.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Ae.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 i=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:i(e.url)})}return ni(Object.entries(e).map(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,i=0;const r=a.now();return e.add(a.merge(this.providerOutput.error$,ET({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(n=>({id:`ProviderHangup:${n}`,category:a.ErrorCategory.WTF,message:`A ${n} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const n=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(n)})),e.add(this.providerError$.subscribe(n=>{console.log(n);const o=this.current$.getValue().destination;if(o===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const l=n.category===a.ErrorCategory.NETWORK,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit,c=d&&(l&&t||!u),h=n.id.includes("partial_metadata"),f=a.now()-r;c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):h&&f<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():u?(i++,this.reinitProvider()):this.switchToNextProvider(o!=null?o:Ae.SCREEN)}})),e}}const AT=5e3,Ll="one_video_throughput",xl="one_video_rtt",Rt=window.navigator.connection,Nl=()=>{const s=Rt==null?void 0:Rt.downlink;if(a.isNonNullable(s)&&s!==10)return s*1e3},Ol=()=>{const s=Rt==null?void 0:Rt.rtt;if(a.isNonNullable(s)&&s!==3e3)return s},Bl=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class ns{constructor(e){var t,i;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ns.load(Ll)||(e.useBrowserEstimation?Nl():void 0)||AT,n=(i=(t=ns.load(xl))!==null&&t!==void 0?t:e.useBrowserEstimation?Ol():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Bl(r,n,e.rttPenaltyRequestSize)),this.throughput=mn.getSmoothedValue(r,-1,e),this.rtt=mn.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Nl();d&&this.throughput.next(d);const u=Ol();a.isNonNullable(u)&&this.rtt.next(u)};Rt&&"onchange"in Rt&&this.subscription.add(a.fromEvent(Rt,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(Ll,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(xl,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})=>Bl(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,i=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,i=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=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-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){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),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=({done:c,value:h})=>F(this,void 0,void 0,function*(){if(c)!t&&this.addRawSpeed(r,a.now()-n,1),this.concurrentDownloads.delete(e);else if(h){if(t){if(a.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval)o+=h.byteLength;else{const p=l-n;p&&this.addRawSpeed(o,p,1,t),o=h.byteLength,n=a.now()}l=a.now()}else 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 i==null?void 0:i.read().then(u,d)}});this.concurrentDownloads.add(e),i==null||i.read().then(u,d)}addRawSpeed(e,t,i=1,r=!1){if(ns.sanityCheck(e,t,r)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=a.safeStorage.get(e);if(a.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Ml={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:a.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Mt.VP9,androidPreferredFormat:It.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},PT=s=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(s,Ml)),{configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Ml.configName]})};var Vl=({seekState:s,position$:e})=>a.merge(s.stateChangeEnded$.pipe(a.map(({to:t})=>{var i;return t.state===Y.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>s.getState().state===Y.None))),_T=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return a.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const DT=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class IT{constructor(e={configName:[]}){if(this.subscription=new a.Subscription,this.logger=new a.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new ee(exports.PlaybackState.STOPPED),seekState:new ee({state:Y.None}),volume:new ee({volume:1,muted:!1}),videoTrack:new ee(void 0),autoVideoTrackSwitching:new ee(!0),autoVideoTrackLimits:new ee({}),isLooped:new ee(!1),playbackRate:new ee(1),externalTextTracks:new ee([]),internalTextTracks:new ee([]),currentTextTrack:new ee(void 0),textTrackCuesSettings:new ee({}),cameraOrientation:new ee({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:eS},this.initLogs(),this.tuning=PT(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Vd({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ns(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,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(i)}`,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,i,r;return this.config=e,this.domContainer=_T(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new wT({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},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,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?a.fromEvent(document,"visibilitychange").pipe(a.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:Y.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return DT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),n=i.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(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===Y.None?void 0:t.position;return a.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||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===Y.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},o),{state:Y.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===Y.Applying&&(this.desiredState.seekState.setState({state:Y.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:Vl({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))*1e3<this.tuning.live.activeLiveDelay),a.filterChanged(),a.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.muted),a.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(a.map(o=>o.volume),a.filterChanged()).subscribe(this.info.volume$)).add(Vl({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 i=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>i.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,i).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.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((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:n})=>n===r),i||this.setAutoQuality(!0)),i||(i=hi(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.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),Zb(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Xb(i)),this.providerContainer.current$.subscribe(({type:i})=>Os("provider",i)),t.duration$.subscribe(i=>Os("duration",i)),t.availableVideoTracks$.pipe(a.filter(i=>!!i.length),a.once()).subscribe(i=>Os("tracks",i)),this.events.fatalError$.subscribe(new ct("fatalError")),this.events.managedError$.subscribe(new ct("managedError")),t.position$.subscribe(new ct("position")),t.currentVideoTrack$.pipe(a.map(i=>i==null?void 0:i.quality)).subscribe(new ct("quality")),this.info.currentBuffer$.subscribe(new ct("buffer")),t.isBuffering$.subscribe(new ct("isBuffering"))].forEach(i=>this.subscription.add(i)),Os("codecs",bT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=()=>F(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||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const RT=`@vkontakte/videoplayer-core@${Fl}`;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=IT;exports.SDK_VERSION=RT;exports.VERSION=Fl;
|