@vkontakte/videoplayer-core 2.0.97 → 2.0.98-dev.5902fe89.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 +9 -9
- package/es2015.esm.js +9 -9
- package/es2018.cjs.js +8 -8
- package/es2018.esm.js +9 -9
- package/esnext.cjs.js +8 -8
- package/esnext.esm.js +9 -9
- package/evergreen.esm.js +10 -10
- package/index.d.ts +1 -1
- package/package.json +1 -1
package/es2015.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.5902fe89.0
|
|
3
|
+
* Thu, 21 Dec 2023 11:07:44 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Rd=Object.create;var Yn=Object.defineProperty;var Cd=Object.getOwnPropertyDescriptor;var xd=Object.getOwnPropertyNames;var Ld=Object.getPrototypeOf,Nd=Object.prototype.hasOwnProperty;var Od=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xd(e))!Nd.call(i,r)&&r!==t&&Yn(i,r,{get:()=>e[r],enumerable:!(s=Cd(e,r))||s.enumerable});return i};var zn=(i,e,t)=>(t=i!=null?Rd(Ld(i)):{},Od(e||!i||!i.__esModule?Yn(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Bd=require("lodash/debounce.js");const Vl="2.0.97";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var Ae;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(exports.Surface||(exports.Surface={}));function H(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(s.next(c))}catch(h){o(h)}}function d(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(l,d)}u((s=s.apply(i,e||[])).next())})}function A(i){return this instanceof A?(this.v=i,this):new A(i)}function Z(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){s[f]&&(r[f]=function(p){return new Promise(function(m,g){n.push([f,p,m,g])>1||l(f,p)})})}function l(f,p){try{d(s[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof A?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=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class 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 s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||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 s,r,n;(n=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([s.getCastState()])).pipe(a.filterChanged(),a.map(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=s.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Fd=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var Ur=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function fr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ke=function(i){try{return!!i()}catch(e){return!0}},Ud=Ke,pr=!Ud(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Fl=pr,Ul=Function.prototype,Ua=Ul.call,jd=Fl&&Ul.bind.bind(Ua,Ua),Je=Fl?jd:function(i){return function(){return Ua.apply(i,arguments)}},jl=Je,Hd=jl({}.toString),Gd=jl("".slice),cs=function(i){return Gd(Hd(i),8,-1)},Yd=Je,zd=Ke,qd=cs,jr=Object,Wd=Yd("".split),Qd=zd(function(){return!jr("z").propertyIsEnumerable(0)})?function(i){return qd(i)=="String"?Wd(i,""):jr(i)}:jr,hs=function(i){return i==null},Kd=hs,Jd=TypeError,mn=function(i){if(Kd(i))throw Jd("Can't call method on "+i);return i},Xd=Qd,Zd=mn,fs=function(i){return Xd(Zd(i))},Ni={},$s=function(i){return i&&i.Math==Math&&i},Te=$s(typeof globalThis=="object"&&globalThis)||$s(typeof window=="object"&&window)||$s(typeof self=="object"&&self)||$s(typeof Ur=="object"&&Ur)||function(){return this}()||Ur||Function("return this")(),ja=typeof document=="object"&&document.all,ec=typeof ja=="undefined"&&ja!==void 0,Hl={all:ja,IS_HTMLDDA:ec},Gl=Hl,tc=Gl.all,pe=Gl.IS_HTMLDDA?function(i){return typeof i=="function"||i===tc}:function(i){return typeof i=="function"},ic=Te,sc=pe,qn=ic.WeakMap,rc=sc(qn)&&/native code/.test(String(qn)),Wn=pe,Yl=Hl,ac=Yl.all,Ct=Yl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Wn(i)||i===ac}:function(i){return typeof i=="object"?i!==null:Wn(i)},nc=Ke,jt=!nc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ui={},oc=Te,Qn=Ct,Ha=oc.document,lc=Qn(Ha)&&Qn(Ha.createElement),vn=function(i){return lc?Ha.createElement(i):{}},uc=jt,dc=Ke,cc=vn,zl=!uc&&!dc(function(){return Object.defineProperty(cc("div"),"a",{get:function(){return 7}}).a!=7}),hc=jt,fc=Ke,ql=hc&&fc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),pc=Ct,mc=String,vc=TypeError,xt=function(i){if(pc(i))return i;throw vc(mc(i)+" is not an object")},bc=pr,ks=Function.prototype.call,He=bc?ks.bind(ks):function(){return ks.apply(ks,arguments)},bn={},Hr=bn,Gr=Te,gc=pe,Kn=function(i){return gc(i)?i:void 0},di=function(i,e){return arguments.length<2?Kn(Hr[i])||Kn(Gr[i]):Hr[i]&&Hr[i][e]||Gr[i]&&Gr[i][e]},Sc=Je,mr=Sc({}.isPrototypeOf),vr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Wl=Te,Yr=vr,Jn=Wl.process,Xn=Wl.Deno,Zn=Jn&&Jn.versions||Xn&&Xn.version,eo=Zn&&Zn.v8,st,Ks;eo&&(st=eo.split("."),Ks=st[0]>0&&st[0]<4?1:+(st[0]+st[1]));!Ks&&Yr&&(st=Yr.match(/Edge\/(\d+)/),(!st||st[1]>=74)&&(st=Yr.match(/Chrome\/(\d+)/),st&&(Ks=+st[1])));var Ql=Ks,to=Ql,yc=Ke,Tc=Te,Ec=Tc.String,Kl=!!Object.getOwnPropertySymbols&&!yc(function(){var i=Symbol();return!Ec(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&to&&to<41}),$c=Kl,Jl=$c&&!Symbol.sham&&typeof Symbol.iterator=="symbol",kc=di,Ac=pe,wc=mr,Pc=Jl,_c=Object,Xl=Pc?function(i){return typeof i=="symbol"}:function(i){var e=kc("Symbol");return Ac(e)&&wc(e.prototype,_c(i))},Dc=String,br=function(i){try{return Dc(i)}catch(e){return"Object"}},Ic=pe,Rc=br,Cc=TypeError,ci=function(i){if(Ic(i))return i;throw Cc(Rc(i)+" is not a function")},xc=ci,Lc=hs,gr=function(i,e){var t=i[e];return Lc(t)?void 0:xc(t)},zr=He,qr=pe,Wr=Ct,Nc=TypeError,Oc=function(i,e){var t,s;if(e==="string"&&qr(t=i.toString)&&!Wr(s=zr(t,i))||qr(t=i.valueOf)&&!Wr(s=zr(t,i))||e!=="string"&&qr(t=i.toString)&&!Wr(s=zr(t,i)))return s;throw Nc("Can't convert object to primitive value")},Zl={exports:{}},Bc=!0,io=Te,Mc=Object.defineProperty,Vc=function(i,e){try{Mc(io,i,{value:e,configurable:!0,writable:!0})}catch(t){io[i]=e}return e},Fc=Te,Uc=Vc,so="__core-js_shared__",jc=Fc[so]||Uc(so,{}),gn=jc,ro=gn;(Zl.exports=function(i,e){return ro[i]||(ro[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eu=Zl.exports,Hc=mn,Gc=Object,Sr=function(i){return Gc(Hc(i))},Yc=Je,zc=Sr,qc=Yc({}.hasOwnProperty),mt=Object.hasOwn||function(e,t){return qc(zc(e),t)},Wc=Je,Qc=0,Kc=Math.random(),Jc=Wc(1 .toString),tu=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Jc(++Qc+Kc,36)},Xc=Te,Zc=eu,ao=mt,eh=tu,th=Kl,ih=Jl,ki=Xc.Symbol,Qr=Zc("wks"),sh=ih?ki.for||ki:ki&&ki.withoutSetter||eh,De=function(i){return ao(Qr,i)||(Qr[i]=th&&ao(ki,i)?ki[i]:sh("Symbol."+i)),Qr[i]},rh=He,no=Ct,oo=Xl,ah=gr,nh=Oc,oh=De,lh=TypeError,uh=oh("toPrimitive"),dh=function(i,e){if(!no(i)||oo(i))return i;var t=ah(i,uh),s;if(t){if(e===void 0&&(e="default"),s=rh(t,i,e),!no(s)||oo(s))return s;throw lh("Can't convert object to primitive value")}return e===void 0&&(e="number"),nh(i,e)},ch=dh,hh=Xl,Sn=function(i){var e=ch(i,"string");return hh(e)?e:e+""},fh=jt,ph=zl,mh=ql,As=xt,lo=Sn,vh=TypeError,Kr=Object.defineProperty,bh=Object.getOwnPropertyDescriptor,Jr="enumerable",Xr="configurable",Zr="writable";ui.f=fh?mh?function(e,t,s){if(As(e),t=lo(t),As(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Zr in s&&!s[Zr]){var r=bh(e,t);r&&r[Zr]&&(e[t]=s.value,s={configurable:Xr in s?s[Xr]:r[Xr],enumerable:Jr in s?s[Jr]:r[Jr],writable:!1})}return Kr(e,t,s)}:Kr:function(e,t,s){if(As(e),t=lo(t),As(s),ph)try{return Kr(e,t,s)}catch(r){}if("get"in s||"set"in s)throw vh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var yr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},gh=jt,Sh=ui,yh=yr,ps=gh?function(i,e,t){return Sh.f(i,e,yh(1,t))}:function(i,e,t){return i[e]=t,i},Th=eu,Eh=tu,uo=Th("keys"),yn=function(i){return uo[i]||(uo[i]=Eh(i))},Tn={},$h=rc,iu=Te,kh=Ct,Ah=ps,ea=mt,ta=gn,wh=yn,Ph=Tn,co="Object already initialized",Ga=iu.TypeError,_h=iu.WeakMap,Js,os,Xs,Dh=function(i){return Xs(i)?os(i):Js(i,{})},Ih=function(i){return function(e){var t;if(!kh(e)||(t=os(e)).type!==i)throw Ga("Incompatible receiver, "+i+" required");return t}};if($h||ta.state){var lt=ta.state||(ta.state=new _h);lt.get=lt.get,lt.has=lt.has,lt.set=lt.set,Js=function(i,e){if(lt.has(i))throw Ga(co);return e.facade=i,lt.set(i,e),e},os=function(i){return lt.get(i)||{}},Xs=function(i){return lt.has(i)}}else{var vi=wh("state");Ph[vi]=!0,Js=function(i,e){if(ea(i,vi))throw Ga(co);return e.facade=i,Ah(i,vi,e),e},os=function(i){return ea(i,vi)?i[vi]:{}},Xs=function(i){return ea(i,vi)}}var su={set:Js,get:os,has:Xs,enforce:Dh,getterFor:Ih},Rh=pr,ru=Function.prototype,ho=ru.apply,fo=ru.call,au=typeof Reflect=="object"&&Reflect.apply||(Rh?fo.bind(ho):function(){return fo.apply(ho,arguments)}),Ch=cs,xh=Je,nu=function(i){if(Ch(i)==="Function")return xh(i)},En={},ou={},lu={}.propertyIsEnumerable,uu=Object.getOwnPropertyDescriptor,Lh=uu&&!lu.call({1:2},1);ou.f=Lh?function(e){var t=uu(this,e);return!!t&&t.enumerable}:lu;var Nh=jt,Oh=He,Bh=ou,Mh=yr,Vh=fs,Fh=Sn,Uh=mt,jh=zl,po=Object.getOwnPropertyDescriptor;En.f=Nh?po:function(e,t){if(e=Vh(e),t=Fh(t),jh)try{return po(e,t)}catch(s){}if(Uh(e,t))return Mh(!Oh(Bh.f,e,t),e[t])};var Hh=Ke,Gh=pe,Yh=/#|\.prototype\./,ms=function(i,e){var t=qh[zh(i)];return t==Qh?!0:t==Wh?!1:Gh(e)?Hh(e):!!e},zh=ms.normalize=function(i){return String(i).replace(Yh,".").toLowerCase()},qh=ms.data={},Wh=ms.NATIVE="N",Qh=ms.POLYFILL="P",du=ms,mo=nu,Kh=ci,Jh=pr,Xh=mo(mo.bind),Tr=function(i,e){return Kh(i),e===void 0?i:Jh?Xh(i,e):function(){return i.apply(e,arguments)}},ws=Te,Zh=au,ef=nu,tf=pe,sf=En.f,rf=du,bi=bn,af=Tr,gi=ps,vo=mt,nf=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return Zh(i,this,arguments)};return e.prototype=i.prototype,e},at=function(i,e){var t=i.target,s=i.global,r=i.stat,n=i.proto,o=s?ws:r?ws[t]:(ws[t]||{}).prototype,l=s?bi:bi[t]||gi(bi,t,{})[t],d=l.prototype,u,c,h,f,p,m,g,S,v;for(f in e)u=rf(s?f:t+(r?".":"#")+f,i.forced),c=!u&&o&&vo(o,f),m=l[f],c&&(i.dontCallGetSet?(v=sf(o,f),g=v&&v.value):g=o[f]),p=c&&g?g:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?S=af(p,ws):i.wrap&&c?S=nf(p):n&&tf(p)?S=ef(p):S=p,(i.sham||p&&p.sham||m&&m.sham)&&gi(S,"sham",!0),gi(l,f,S),n&&(h=t+"Prototype",vo(bi,h)||gi(bi,h,{}),gi(bi[h],f,p),i.real&&d&&(u||!d[f])&&gi(d,f,p)))},Ya=jt,of=mt,cu=Function.prototype,lf=Ya&&Object.getOwnPropertyDescriptor,$n=of(cu,"name"),uf=$n&&function(){}.name==="something",df=$n&&(!Ya||Ya&&lf(cu,"name").configurable),cf={EXISTS:$n,PROPER:uf,CONFIGURABLE:df},hu={},hf=Math.ceil,ff=Math.floor,pf=Math.trunc||function(e){var t=+e;return(t>0?ff:hf)(t)},mf=pf,kn=function(i){var e=+i;return e!==e||e===0?0:mf(e)},vf=kn,bf=Math.max,gf=Math.min,Sf=function(i,e){var t=vf(i);return t<0?bf(t+e,0):gf(t,e)},yf=kn,Tf=Math.min,Ef=function(i){return i>0?Tf(yf(i),9007199254740991):0},$f=Ef,An=function(i){return $f(i.length)},kf=fs,Af=Sf,wf=An,bo=function(i){return function(e,t,s){var r=kf(e),n=wf(r),o=Af(s,n),l;if(i&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in r)&&r[o]===t)return i||o||0;return!i&&-1}},Pf={includes:bo(!0),indexOf:bo(!1)},_f=Je,ia=mt,Df=fs,If=Pf.indexOf,Rf=Tn,go=_f([].push),Cf=function(i,e){var t=Df(i),s=0,r=[],n;for(n in t)!ia(Rf,n)&&ia(t,n)&&go(r,n);for(;e.length>s;)ia(t,n=e[s++])&&(~If(r,n)||go(r,n));return r},fu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],xf=Cf,Lf=fu,Nf=Object.keys||function(e){return xf(e,Lf)},Of=jt,Bf=ql,Mf=ui,Vf=xt,Ff=fs,Uf=Nf;hu.f=Of&&!Bf?Object.defineProperties:function(e,t){Vf(e);for(var s=Ff(t),r=Uf(t),n=r.length,o=0,l;n>o;)Mf.f(e,l=r[o++],s[l]);return e};var jf=di,pu=jf("document","documentElement"),Hf=xt,Gf=hu,So=fu,Yf=Tn,zf=pu,qf=vn,Wf=yn,yo=">",To="<",za="prototype",qa="script",mu=Wf("IE_PROTO"),sa=function(){},vu=function(i){return To+qa+yo+i+To+"/"+qa+yo},Eo=function(i){i.write(vu("")),i.close();var e=i.parentWindow.Object;return i=null,e},Qf=function(){var i=qf("iframe"),e="java"+qa+":",t;return i.style.display="none",zf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(vu("document.F=Object")),t.close(),t.F},Ps,zs=function(){try{Ps=new ActiveXObject("htmlfile")}catch(e){}zs=typeof document!="undefined"?document.domain&&Ps?Eo(Ps):Qf():Eo(Ps);for(var i=So.length;i--;)delete zs[za][So[i]];return zs()};Yf[mu]=!0;var bu=Object.create||function(e,t){var s;return e!==null?(sa[za]=Hf(e),s=new sa,sa[za]=null,s[mu]=e):s=zs(),t===void 0?s:Gf.f(s,t)},Kf=Ke,Jf=!Kf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Xf=mt,Zf=pe,ep=Sr,tp=yn,ip=Jf,$o=tp("IE_PROTO"),Wa=Object,sp=Wa.prototype,gu=ip?Wa.getPrototypeOf:function(i){var e=ep(i);if(Xf(e,$o))return e[$o];var t=e.constructor;return Zf(t)&&e instanceof t?t.prototype:e instanceof Wa?sp:null},rp=ps,wn=function(i,e,t,s){return s&&s.enumerable?i[e]=t:rp(i,e,t),i},ap=Ke,np=pe,op=Ct,lp=bu,ko=gu,up=wn,dp=De,Qa=dp("iterator"),Su=!1,Dt,ra,aa;[].keys&&(aa=[].keys(),"next"in aa?(ra=ko(ko(aa)),ra!==Object.prototype&&(Dt=ra)):Su=!0);var cp=!op(Dt)||ap(function(){var i={};return Dt[Qa].call(i)!==i});cp?Dt={}:Dt=lp(Dt);np(Dt[Qa])||up(Dt,Qa,function(){return this});var yu={IteratorPrototype:Dt,BUGGY_SAFARI_ITERATORS:Su},hp=De,fp=hp("toStringTag"),Tu={};Tu[fp]="z";var Pn=String(Tu)==="[object z]",pp=Pn,mp=pe,qs=cs,vp=De,bp=vp("toStringTag"),gp=Object,Sp=qs(function(){return arguments}())=="Arguments",yp=function(i,e){try{return i[e]}catch(t){}},vs=pp?qs:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=yp(e=gp(i),bp))=="string"?t:Sp?qs(e):(s=qs(e))=="Object"&&mp(e.callee)?"Arguments":s},Tp=Pn,Ep=vs,$p=Tp?{}.toString:function(){return"[object "+Ep(this)+"]"},kp=Pn,Ap=ui.f,wp=ps,Pp=mt,_p=$p,Dp=De,Ao=Dp("toStringTag"),_n=function(i,e,t,s){if(i){var r=t?i:i.prototype;Pp(r,Ao)||Ap(r,Ao,{configurable:!0,value:e}),s&&!kp&&wp(r,"toString",_p)}},Ip=yu.IteratorPrototype,Rp=bu,Cp=yr,xp=_n,Lp=Ni,Np=function(){return this},Op=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Rp(Ip,{next:Cp(+!s,t)}),xp(i,r,!1,!0),Lp[r]=Np,i},Bp=at,Mp=He,Eu=cf,Vp=Op,Fp=gu,Up=_n,wo=wn,jp=De,Po=Ni,$u=yu,Hp=Eu.PROPER;Eu.CONFIGURABLE;$u.IteratorPrototype;var _s=$u.BUGGY_SAFARI_ITERATORS,na=jp("iterator"),_o="keys",Ds="values",Do="entries",Gp=function(){return this},Yp=function(i,e,t,s,r,n,o){Vp(t,e,s);var l=function(v){if(v===r&&f)return f;if(!_s&&v in c)return c[v];switch(v){case _o:return function(){return new t(this,v)};case Ds:return function(){return new t(this,v)};case Do:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[na]||c["@@iterator"]||r&&c[r],f=!_s&&h||l(r),p=e=="Array"&&c.entries||h,m,g,S;if(p&&(m=Fp(p.call(new i)),m!==Object.prototype&&m.next&&(Up(m,d,!0,!0),Po[d]=Gp)),Hp&&r==Ds&&h&&h.name!==Ds&&(u=!0,f=function(){return Mp(h,this)}),r)if(g={values:l(Ds),keys:n?f:l(_o),entries:l(Do)},o)for(S in g)(_s||u||!(S in c))&&wo(c,S,g[S]);else Bp({target:e,proto:!0,forced:_s||u},g);return o&&c[na]!==f&&wo(c,na,f,{name:r}),Po[e]=f,g},zp=function(i,e){return{value:i,done:e}},qp=fs,Io=Ni,ku=su;ui.f;var Wp=Yp,Is=zp,Au="Array Iterator",Qp=ku.set,Kp=ku.getterFor(Au);Wp(Array,"Array",function(i,e){Qp(this,{type:Au,target:qp(i),index:0,kind:e})},function(){var i=Kp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Is(void 0,!0)):t=="keys"?Is(s,!1):t=="values"?Is(e[s],!1):Is([s,e[s]],!1)},"values");Io.Arguments=Io.Array;var Jp=De,Xp=Ni,Zp=Jp("iterator"),em=Array.prototype,tm=function(i){return i!==void 0&&(Xp.Array===i||em[Zp]===i)},im=vs,Ro=gr,sm=hs,rm=Ni,am=De,nm=am("iterator"),wu=function(i){if(!sm(i))return Ro(i,nm)||Ro(i,"@@iterator")||rm[im(i)]},om=He,lm=ci,um=xt,dm=br,cm=wu,hm=TypeError,fm=function(i,e){var t=arguments.length<2?cm(i):e;if(lm(t))return um(om(t,i));throw hm(dm(i)+" is not iterable")},pm=He,Co=xt,mm=gr,vm=function(i,e,t){var s,r;Co(i);try{if(s=mm(i,"return"),!s){if(e==="throw")throw t;return t}s=pm(s,i)}catch(n){r=!0,s=n}if(e==="throw")throw t;if(r)throw s;return Co(s),t},bm=Tr,gm=He,Sm=xt,ym=br,Tm=tm,Em=An,xo=mr,$m=fm,km=wu,Lo=vm,Am=TypeError,Ws=function(i,e){this.stopped=i,this.result=e},No=Ws.prototype,Dn=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=bm(e,s),u,c,h,f,p,m,g,S=function(y){return u&&Lo(u,"normal",y),new Ws(!0,y)},v=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=i.iterator;else if(o)u=i;else{if(c=km(i),!c)throw Am(ym(i)+" is not iterable");if(Tm(c)){for(h=0,f=Em(i);f>h;h++)if(p=v(i[h]),p&&xo(No,p))return p;return new Ws(!1)}u=$m(i,c)}for(m=n?i.next:u.next;!(g=gm(m,u)).done;){try{p=v(g.value)}catch(y){Lo(u,"throw",y)}if(typeof p=="object"&&p&&xo(No,p))return p}return new Ws(!1)},wm=Sn,Pm=ui,_m=yr,Dm=function(i,e,t){var s=wm(e);s in i?Pm.f(i,s,_m(0,t)):i[s]=t},Im=at,Rm=Dn,Cm=Dm;Im({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Rm(e,function(s,r){Cm(t,s,r)},{AS_ENTRIES:!0}),t}});var xm=bn,Lm=xm.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=Te,Mm=vs,Vm=ps,Oo=Ni,Fm=De,Bo=Fm("toStringTag");for(var oa in Om){var Mo=Bm[oa],la=Mo&&Mo.prototype;la&&Mm(la)!==Bo&&Vm(la,Bo,oa),Oo[oa]=Oo.Array}var Um=Lm,jm=Um,Hm=jm,Gm=Hm,ni=fr(Gm),Ym=cs,Er=typeof process!="undefined"&&Ym(process)=="process",zm=ui,qm=function(i,e,t){return zm.f(i,e,t)},Wm=di,Qm=qm,Km=De,Jm=jt,Vo=Km("species"),Xm=function(i){var e=Wm(i);Jm&&e&&!e[Vo]&&Qm(e,Vo,{configurable:!0,get:function(){return this}})},Zm=mr,ev=TypeError,tv=function(i,e){if(Zm(e,i))return i;throw ev("Incorrect invocation")},iv=Je,sv=pe,Ka=gn,rv=iv(Function.toString);sv(Ka.inspectSource)||(Ka.inspectSource=function(i){return rv(i)});var Pu=Ka.inspectSource,av=Je,nv=Ke,_u=pe,ov=vs,lv=di,uv=Pu,Du=function(){},dv=[],Iu=lv("Reflect","construct"),In=/^\s*(?:class|function)\b/,cv=av(In.exec),hv=!In.exec(Du),Ki=function(e){if(!_u(e))return!1;try{return Iu(Du,dv,e),!0}catch(t){return!1}},Ru=function(e){if(!_u(e))return!1;switch(ov(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return hv||!!cv(In,uv(e))}catch(t){return!0}};Ru.sham=!0;var fv=!Iu||nv(function(){var i;return Ki(Ki.call)||!Ki(Object)||!Ki(function(){i=!0})||i})?Ru:Ki,pv=fv,mv=br,vv=TypeError,bv=function(i){if(pv(i))return i;throw vv(mv(i)+" is not a constructor")},Fo=xt,gv=bv,Sv=hs,yv=De,Tv=yv("species"),Cu=function(i,e){var t=Fo(i).constructor,s;return t===void 0||Sv(s=Fo(t)[Tv])?e:gv(s)},Ev=Je,$v=Ev([].slice),kv=TypeError,Av=function(i,e){if(i<e)throw kv("Not enough arguments");return i},wv=vr,xu=/(?:ipad|iphone|ipod).*applewebkit/i.test(wv),je=Te,Pv=au,_v=Tr,Uo=pe,Dv=mt,Lu=Ke,jo=pu,Iv=$v,Ho=vn,Rv=Av,Cv=xu,xv=Er,Ja=je.setImmediate,Xa=je.clearImmediate,Lv=je.process,ua=je.Dispatch,Nv=je.Function,Go=je.MessageChannel,Ov=je.String,da=0,rs={},Yo="onreadystatechange",ls,ti,ca,ha;Lu(function(){ls=je.location});var Rn=function(i){if(Dv(rs,i)){var e=rs[i];delete rs[i],e()}},fa=function(i){return function(){Rn(i)}},zo=function(i){Rn(i.data)},qo=function(i){je.postMessage(Ov(i),ls.protocol+"//"+ls.host)};(!Ja||!Xa)&&(Ja=function(e){Rv(arguments.length,1);var t=Uo(e)?e:Nv(e),s=Iv(arguments,1);return rs[++da]=function(){Pv(t,void 0,s)},ti(da),da},Xa=function(e){delete rs[e]},xv?ti=function(i){Lv.nextTick(fa(i))}:ua&&ua.now?ti=function(i){ua.now(fa(i))}:Go&&!Cv?(ca=new Go,ha=ca.port2,ca.port1.onmessage=zo,ti=_v(ha.postMessage,ha)):je.addEventListener&&Uo(je.postMessage)&&!je.importScripts&&ls&&ls.protocol!=="file:"&&!Lu(qo)?(ti=qo,je.addEventListener("message",zo,!1)):Yo in Ho("script")?ti=function(i){jo.appendChild(Ho("script"))[Yo]=function(){jo.removeChild(this),Rn(i)}}:ti=function(i){setTimeout(fa(i),0)});var Nu={set:Ja,clear:Xa},Ou=function(){this.head=null,this.tail=null};Ou.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Bu=Ou,Bv=vr,Mv=/ipad|iphone|ipod/i.test(Bv)&&typeof Pebble!="undefined",Vv=vr,Fv=/web0s(?!.*chrome)/i.test(Vv),oi=Te,Wo=Tr,Uv=En.f,pa=Nu.set,jv=Bu,Hv=xu,Gv=Mv,Yv=Fv,ma=Er,Qo=oi.MutationObserver||oi.WebKitMutationObserver,Ko=oi.document,Jo=oi.process,Rs=oi.Promise,Xo=Uv(oi,"queueMicrotask"),Za=Xo&&Xo.value,Si,va,ba,Cs,Zo;if(!Za){var xs=new jv,Ls=function(){var i,e;for(ma&&(i=Jo.domain)&&i.exit();e=xs.get();)try{e()}catch(t){throw xs.head&&Si(),t}i&&i.enter()};!Hv&&!ma&&!Yv&&Qo&&Ko?(va=!0,ba=Ko.createTextNode(""),new Qo(Ls).observe(ba,{characterData:!0}),Si=function(){ba.data=va=!va}):!Gv&&Rs&&Rs.resolve?(Cs=Rs.resolve(void 0),Cs.constructor=Rs,Zo=Wo(Cs.then,Cs),Si=function(){Zo(Ls)}):ma?Si=function(){Jo.nextTick(Ls)}:(pa=Wo(pa,oi),Si=function(){pa(Ls)}),Za=function(i){xs.head||Si(),xs.add(i)}}var zv=Za,qv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Cn=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Wv=Te,Oi=Wv.Promise,Mu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Qv=Mu,Kv=Er,Jv=!Qv&&!Kv&&typeof window=="object"&&typeof document=="object",Xv=Te,as=Oi,Zv=pe,eb=du,tb=Pu,ib=De,sb=Jv,rb=Mu,ga=Ql,el=as&&as.prototype,ab=ib("species"),en=!1,Vu=Zv(Xv.PromiseRejectionEvent),nb=eb("Promise",function(){var i=tb(as),e=i!==String(as);if(!e&&ga===66||!(el.catch&&el.finally))return!0;if(!ga||ga<51||!/native code/.test(i)){var t=new as(function(n){n(1)}),s=function(n){n(function(){},function(){})},r=t.constructor={};if(r[ab]=s,en=t.then(function(){})instanceof s,!en)return!0}return!e&&(sb||rb)&&!Vu}),bs={CONSTRUCTOR:nb,REJECTION_EVENT:Vu,SUBCLASSING:en},Bi={},tl=ci,ob=TypeError,lb=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw ob("Bad Promise constructor");e=s,t=r}),this.resolve=tl(e),this.reject=tl(t)};Bi.f=function(i){return new lb(i)};var ub=at,Zs=Er,Ft=Te,gs=He,db=wn,cb=_n,hb=Xm,fb=ci,tn=pe,pb=Ct,mb=tv,vb=Cu,Fu=Nu.set,xn=zv,bb=qv,gb=Cn,Sb=Bu,Uu=su,sn=Oi,Ln=bs,ju=Bi,$r="Promise",Hu=Ln.CONSTRUCTOR,yb=Ln.REJECTION_EVENT;Ln.SUBCLASSING;var Sa=Uu.getterFor($r),Tb=Uu.set,Eb=sn&&sn.prototype,Ai=sn,ya=Eb,Gu=Ft.TypeError,rn=Ft.document,Nn=Ft.process,an=ju.f,$b=an,kb=!!(rn&&rn.createEvent&&Ft.dispatchEvent),Yu="unhandledrejection",Ab="rejectionhandled",il=0,zu=1,wb=2,On=1,qu=2,Ns,sl,Pb,Wu=function(i){var e;return pb(i)&&tn(e=i.then)?e:!1},Qu=function(i,e){var t=e.value,s=e.state==zu,r=s?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{r?(s||(e.rejection===qu&&Db(e),e.rejection=On),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===i.promise?o(Gu("Promise-chain cycle")):(u=Wu(d))?gs(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Ku=function(i,e){i.notified||(i.notified=!0,xn(function(){for(var t=i.reactions,s;s=t.get();)Qu(s,i);i.notified=!1,e&&!i.rejection&&_b(i)}))},Ju=function(i,e,t){var s,r;kb?(s=rn.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Ft.dispatchEvent(s)):s={promise:e,reason:t},!yb&&(r=Ft["on"+i])?r(s):i===Yu&&bb("Unhandled promise rejection",t)},_b=function(i){gs(Fu,Ft,function(){var e=i.facade,t=i.value,s=rl(i),r;if(s&&(r=gb(function(){Zs?Nn.emit("unhandledRejection",t,e):Ju(Yu,e,t)}),i.rejection=Zs||rl(i)?qu:On,r.error))throw r.value})},rl=function(i){return i.rejection!==On&&!i.parent},Db=function(i){gs(Fu,Ft,function(){var e=i.facade;Zs?Nn.emit("rejectionHandled",e):Ju(Ab,e,i.value)})},wi=function(i,e,t){return function(s){i(e,s,t)}},Di=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=wb,Ku(i,!0))},nn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Gu("Promise can't be resolved itself");var s=Wu(e);s?xn(function(){var r={done:!1};try{gs(s,e,wi(nn,r,i),wi(Di,r,i))}catch(n){Di(r,n,i)}}):(i.value=e,i.state=zu,Ku(i,!1))}catch(r){Di({done:!1},r,i)}}};Hu&&(Ai=function(e){mb(this,ya),fb(e),gs(Ns,this);var t=Sa(this);try{e(wi(nn,t),wi(Di,t))}catch(s){Di(t,s)}},ya=Ai.prototype,Ns=function(e){Tb(this,{type:$r,done:!1,notified:!1,parent:!1,reactions:new Sb,rejection:!1,state:il,value:void 0})},Ns.prototype=db(ya,"then",function(e,t){var s=Sa(this),r=an(vb(this,Ai));return s.parent=!0,r.ok=tn(e)?e:!0,r.fail=tn(t)&&t,r.domain=Zs?Nn.domain:void 0,s.state==il?s.reactions.add(r):xn(function(){Qu(r,s)}),r.promise}),sl=function(){var i=new Ns,e=Sa(i);this.promise=i,this.resolve=wi(nn,e),this.reject=wi(Di,e)},ju.f=an=function(i){return i===Ai||i===Pb?new sl(i):$b(i)});ub({global:!0,constructor:!0,wrap:!0,forced:Hu},{Promise:Ai});cb(Ai,$r,!1,!0);hb($r);var Ib=De,Xu=Ib("iterator"),Zu=!1;try{var Rb=0,al={next:function(){return{done:!!Rb++}},return:function(){Zu=!0}};al[Xu]=function(){return this},Array.from(al,function(){throw 2})}catch(i){}var Cb=function(i,e){if(!e&&!Zu)return!1;var t=!1;try{var s={};s[Xu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},xb=Oi,Lb=Cb,Nb=bs.CONSTRUCTOR,ed=Nb||!Lb(function(i){xb.all(i).then(void 0,function(){})}),Ob=at,Bb=He,Mb=ci,Vb=Bi,Fb=Cn,Ub=Dn,jb=ed;Ob({target:"Promise",stat:!0,forced:jb},{all:function(e){var t=this,s=Vb.f(t),r=s.resolve,n=s.reject,o=Fb(function(){var l=Mb(t.resolve),d=[],u=0,c=1;Ub(e,function(h){var f=u++,p=!1;c++,Bb(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||r(d))},n)}),--c||r(d)});return o.error&&n(o.value),s.promise}});var Hb=at,Gb=bs.CONSTRUCTOR,nl=Oi;nl&&nl.prototype;Hb({target:"Promise",proto:!0,forced:Gb,real:!0},{catch:function(i){return this.then(void 0,i)}});var Yb=at,zb=He,qb=ci,Wb=Bi,Qb=Cn,Kb=Dn,Jb=ed;Yb({target:"Promise",stat:!0,forced:Jb},{race:function(e){var t=this,s=Wb.f(t),r=s.reject,n=Qb(function(){var o=qb(t.resolve);Kb(e,function(l){zb(o,t,l).then(s.resolve,r)})});return n.error&&r(n.value),s.promise}});var Xb=at,Zb=He,eg=Bi,tg=bs.CONSTRUCTOR;Xb({target:"Promise",stat:!0,forced:tg},{reject:function(e){var t=eg.f(this);return Zb(t.reject,void 0,e),t.promise}});var ig=xt,sg=Ct,rg=Bi,td=function(i,e){if(ig(i),sg(e)&&e.constructor===i)return e;var t=rg.f(i),s=t.resolve;return s(e),t.promise},ag=at,ng=di,og=Bc,lg=Oi,ug=bs.CONSTRUCTOR,dg=td,cg=ng("Promise"),hg=!ug;ag({target:"Promise",stat:!0,forced:og},{resolve:function(e){return dg(hg&&this===cg?lg:this,e)}});var fg=at,on=Oi,pg=Ke,mg=di,vg=pe,bg=Cu,ol=td,gg=on&&on.prototype,Sg=!!on&&pg(function(){gg.finally.call({then:function(){}},function(){})});fg({target:"Promise",proto:!0,real:!0,forced:Sg},{finally:function(i){var e=bg(this,mg("Promise")),t=vg(i);return this.then(t?function(s){return ol(e,i()).then(function(){return s})}:i,t?function(s){return ol(e,i()).then(function(){throw s})}:i)}});var yg=di,Bn=yg,Tg=Bn,Eg=Tg("Promise","finally"),$g=Eg,kg=$g,Ag=kg,wg=Ag,Ss=fr(wg),ae;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ae||(ae={}));var Pe=(i,e=0,t=ae.OFFSET_P)=>{switch(t){case ae.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ae.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ae.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:a.assertNever(t)}return i};const er=(i,e)=>{var t;switch(e){case ae.OFFSET_P:return NaN;case ae.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ae.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var w=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.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,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||a.isNonNullable(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const Pg=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var G;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(G||(G={}));const _g=5,Dg=5,Ig=500,ll=7e3;class Rg{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new ee(G.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===Y.Requested&&s!==G.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case G.PLAYING:case G.PAUSED:case G.READY:break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){case G.PLAYING:break;case G.PAUSED:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.READY:this.videoState.startTransitionTo(G.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PAUSED:{switch(s){case G.PLAYING:this.videoState.startTransitionTo(G.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case G.PAUSED:break;case G.READY:this.videoState.startTransitionTo(G.PAUSED),this.videoState.setState(G.PAUSED);break;case G.STOPPED:this.videoState.startTransitionTo(G.READY),this.prepare();break;default:a.assertNever(s)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(Pg(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(Ig)).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)>_g)&&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<Dg&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===G.PAUSED||e===G.PLAYING)&&(this.videoState.setState(G.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===G.PLAYING||e===G.PAUSED)&&(this.videoState.setState(G.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===G.READY&&this.videoState.setState(G.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==G.STOPPED&&this.videoState.setState(G.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=s[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=Pe(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(ll).subscribe(()=>n(`timeout(${ll})`)))});Ss(Promise.race([t,s]).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 Cg=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&s&&(e==null||e())}}},!0)},xg=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,s=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,g;const S=ni(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(b=>b.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const b=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:b*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const v=(m=S["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(g={1:!0,0:!1}[S["x-reused"]])!==null&&g!==void 0?g:void 0;s.next(v),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...g){return d(this),p(...g)},f.progress=function(...g){return u(this),m(...g)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},Ut=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Lg=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Ut}),!0),Ng=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,n]=s.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(s.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),s.request.url=o.toString(),s.request.range=void 0}t(s)}}},!0)};const rt=(i,e,t,{equal:s=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=i.getState();s(c,h)&&i.setState(c)},n)),s(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},Ht=(i,e,t)=>rt(e,()=>i.loop,s=>{a.isNonNullable(s)&&(i.loop=s)},{onError:t}),vt=(i,e,t,s)=>rt(e,()=>({muted:i.muted,volume:i.volume}),r=>{a.isNonNullable(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),Lt=(i,e,t,s)=>rt(e,()=>i.playbackRate,r=>{a.isNonNullable(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Og=i=>["__",i.language,i.label].join("|"),Bg=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.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,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(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 s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),a.filterChanged((s,r)=>s.length===r.length&&s.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),a.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),a.filterChanged()).subscribe(this.current$));const t=s=>{var r,n;return this.applyCueSettings((n=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(s=>{var r,n;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(nt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:n}=e,o=e.id?e.id:Og(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(s=this.internalTracks.get(o))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:n})=>!this.internalTracks.has(s)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!Bg(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Mn=i=>{i.removeAttribute("src"),i.load()},Mg=i=>{try{i.pause(),i.playbackRate=0,Mn(i),i.remove()}catch(e){console.error(e)}};class Vg{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 ln=window.WeakMap?new WeakMap:new Vg,bt=i=>{let e=i.querySelector("video");const t=!!e;return e?Mn(e):(e=document.createElement("video"),i.appendChild(e)),ln.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},gt=i=>{const e=ln.get(i);ln.delete(i),e?Mn(i):Mg(i)};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 id=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},ul=i=>{const e=id(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Fg=i=>{const e=id(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},un=3;class Ug{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<un&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||un))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?s(t,n):l?s(r,e):r<e&&n>t?(s(t,n),s(r,e)):s(r,n))})}destroy(){this._buffer=[]}}var sd=(i,e,t=un)=>{let s=0,r=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,r=l,!t)return{from:s,to:r};for(let d=n-1;d>=0;d--)i.end(d)+t>=s&&(s=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=r&&(r=i.end(d))}}return{from:s,to:r}};const St=i=>{const e=b=>a.fromEvent(i,b).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=a.merge(...t.map(b=>a.fromEvent(i,b))).pipe(a.map(b=>b.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>sd(i.buffered,i.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>!!(i.error||i.played.length)),a.map(()=>{var b;const T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(b=i.error)!==null&&b!==void 0?b:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(b=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(b)&&p>=i.duration-f&&b<=f&&h.next(p),p=b});const m=a.fromEvent(i,"enterpictureinpicture"),g=a.fromEvent(i,"leavepictureinpicture"),S=new a.ValueSubject(Fg(i));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));const v=new a.ValueSubject(ul(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>ul(i))).subscribe(v),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:S,inFullscreen$:v}},kr=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var jg=at,Hg=Sr,Gg=An,Yg=kn;jg({target:"Array",proto:!0},{at:function(e){var t=Hg(this),s=Gg(t),r=Yg(e),n=r>=0?r:s+r;return n<0||n>=s?void 0:t[n]}});var zg=Bn,qg=zg("Array","at"),Wg=qg,Qg=Wg,Kg=Qg,Jg=Kg,ge=fr(Jg);let Vn=!1,_t={};const Xg=i=>{Vn=i},Zg=()=>{_t={}},eS=i=>{i(_t)},Os=(i,e)=>{var t;Vn&&(_t.meta=(t=_t.meta)!==null&&t!==void 0?t:{},_t.meta[i]=e)};class ct{constructor(e){this.name=e}next(e){var t,s;if(!Vn)return;_t.series=(t=_t.series)!==null&&t!==void 0?t:{};const r=(s=_t.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),_t.series[this.name]=r}}var si;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(si||(si={}));const tS=new ct("best_bitrate"),iS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class rd{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=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,g,S;a.assertNotEmptyArray(i,sS);const v=s.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*s.containerSizeFactor,height:e.height*v*s.containerSizeFactor},b=y&&a.videoSizeToQuality(y),T=s.considerPlaybackRate&&a.isNonNullable(l)?l:1,E=i.filter(R=>!a.isInvariantQuality(R.quality)).sort((R,_)=>a.isHigher(R.quality,_.quality)?-1:1),P=(p=ge(E,-1))===null||p===void 0?void 0:p.quality,N=(m=ge(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),L=T*iS(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),B={},D=E.filter(R=>(b?a.isLower(R.quality,b):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(R.bitrate)?t-n>=R.bitrate*L:!0)?s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<s.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=(g=D!=null?D:E[Math.ceil((E.length-1)/2)])!==null&&g!==void 0?g:i[0];I.quality!==((S=u==null?void 0:u.last)===null||S===void 0?void 0:S.quality)&&h({message:`
|
|
6
|
+
"use strict";var Rd=Object.create;var Yn=Object.defineProperty;var Cd=Object.getOwnPropertyDescriptor;var xd=Object.getOwnPropertyNames;var Ld=Object.getPrototypeOf,Nd=Object.prototype.hasOwnProperty;var Od=(i,e,t,s)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of xd(e))!Nd.call(i,r)&&r!==t&&Yn(i,r,{get:()=>e[r],enumerable:!(s=Cd(e,r))||s.enumerable});return i};var zn=(i,e,t)=>(t=i!=null?Rd(Ld(i)):{},Od(e||!i||!i.__esModule?Yn(t,"default",{value:i,enumerable:!0}):t,i));var a=require("@vkontakte/videoplayer-shared/es2015.cjs.js"),Bd=require("lodash/debounce.js"),Md=require("lodash");const Vl="2.0.98-dev.5902fe89.0";exports.PlaybackState=void 0;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(i){i.MPEG="MPEG",i.DASH="DASH",i.DASH_SEP="DASH_SEP",i.DASH_SEP_VK="DASH_SEP",i.DASH_WEBM="DASH_WEBM",i.DASH_WEBM_AV1="DASH_WEBM_AV1",i.DASH_WEBM_VK="DASH_WEBM",i.DASH_ONDEMAND="DASH_ONDEMAND",i.DASH_ONDEMAND_VK="DASH_ONDEMAND",i.DASH_LIVE="DASH_LIVE",i.DASH_LIVE_CMAF="DASH_LIVE_CMAF",i.DASH_LIVE_WEBM="DASH_LIVE_WEBM",i.HLS="HLS",i.HLS_ONDEMAND="HLS_ONDEMAND",i.HLS_JS="HLS",i.HLS_LIVE="HLS_LIVE",i.HLS_LIVE_CMAF="HLS_LIVE_CMAF",i.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var Ae;(function(i){i.SCREEN="SCREEN",i.CHROMECAST="CHROMECAST"})(Ae||(Ae={}));exports.ChromecastState=void 0;(function(i){i.NOT_AVAILABLE="NOT_AVAILABLE",i.AVAILABLE="AVAILABLE",i.CONNECTING="CONNECTING",i.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(i){i.HTTP1="http1",i.HTTP2="http2",i.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var Y;(function(i){i.None="none",i.Requested="requested",i.Applying="applying"})(Y||(Y={}));exports.Surface=void 0;(function(i){i.NONE="none",i.INLINE="inline",i.FULLSCREEN="fullscreen",i.SECOND_SCREEN="second_screen",i.PIP="pip"})(exports.Surface||(exports.Surface={}));function F(i,e,t,s){function r(n){return n instanceof t?n:new t(function(o){o(n)})}return new(t||(t=Promise))(function(n,o){function l(c){try{u(s.next(c))}catch(h){o(h)}}function d(c){try{u(s.throw(c))}catch(h){o(h)}}function u(c){c.done?n(c.value):r(c.value).then(l,d)}u((s=s.apply(i,e||[])).next())})}function A(i){return this instanceof A?(this.v=i,this):new A(i)}function Z(i,e,t){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var s=t.apply(i,e||[]),r,n=[];return r={},o("next"),o("throw"),o("return"),r[Symbol.asyncIterator]=function(){return this},r;function o(f){s[f]&&(r[f]=function(p){return new Promise(function(m,g){n.push([f,p,m,g])>1||l(f,p)})})}function l(f,p){try{d(s[f](p))}catch(m){h(n[0][3],m)}}function d(f){f.value instanceof A?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 Vd=i=>new Promise((e,t)=>{const s=document.createElement("script");s.setAttribute("src",i),s.onload=()=>e,s.onerror=()=>t,document.body.appendChild(s)});class Fd{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const s="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Vd("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var s,r,n;(n=(r=(s=cast.framework.CastContext.getInstance())===null||s===void 0?void 0:s.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=s.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([s.getCastState()])).pipe(a.filterChanged(),a.map(Ud),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=s.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,s,r;try{t=cast.framework.CastContext.getInstance(),s=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:s,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Ud=i=>{switch(i){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(i)}};var Ur=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function fr(i){return i&&i.__esModule&&Object.prototype.hasOwnProperty.call(i,"default")?i.default:i}var Ke=function(i){try{return!!i()}catch(e){return!0}},jd=Ke,pr=!jd(function(){var i=function(){}.bind();return typeof i!="function"||i.hasOwnProperty("prototype")}),Fl=pr,Ul=Function.prototype,Ua=Ul.call,Hd=Fl&&Ul.bind.bind(Ua,Ua),Je=Fl?Hd:function(i){return function(){return Ua.apply(i,arguments)}},jl=Je,Gd=jl({}.toString),Yd=jl("".slice),cs=function(i){return Yd(Gd(i),8,-1)},zd=Je,qd=Ke,Wd=cs,jr=Object,Qd=zd("".split),Kd=qd(function(){return!jr("z").propertyIsEnumerable(0)})?function(i){return Wd(i)=="String"?Qd(i,""):jr(i)}:jr,hs=function(i){return i==null},Jd=hs,Xd=TypeError,mn=function(i){if(Jd(i))throw Xd("Can't call method on "+i);return i},Zd=Kd,ec=mn,fs=function(i){return Zd(ec(i))},Ni={},$s=function(i){return i&&i.Math==Math&&i},Te=$s(typeof globalThis=="object"&&globalThis)||$s(typeof window=="object"&&window)||$s(typeof self=="object"&&self)||$s(typeof Ur=="object"&&Ur)||function(){return this}()||Ur||Function("return this")(),ja=typeof document=="object"&&document.all,tc=typeof ja=="undefined"&&ja!==void 0,Hl={all:ja,IS_HTMLDDA:tc},Gl=Hl,ic=Gl.all,pe=Gl.IS_HTMLDDA?function(i){return typeof i=="function"||i===ic}:function(i){return typeof i=="function"},sc=Te,rc=pe,qn=sc.WeakMap,ac=rc(qn)&&/native code/.test(String(qn)),Wn=pe,Yl=Hl,nc=Yl.all,Ct=Yl.IS_HTMLDDA?function(i){return typeof i=="object"?i!==null:Wn(i)||i===nc}:function(i){return typeof i=="object"?i!==null:Wn(i)},oc=Ke,jt=!oc(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),ui={},lc=Te,Qn=Ct,Ha=lc.document,uc=Qn(Ha)&&Qn(Ha.createElement),vn=function(i){return uc?Ha.createElement(i):{}},dc=jt,cc=Ke,hc=vn,zl=!dc&&!cc(function(){return Object.defineProperty(hc("div"),"a",{get:function(){return 7}}).a!=7}),fc=jt,pc=Ke,ql=fc&&pc(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),mc=Ct,vc=String,bc=TypeError,xt=function(i){if(mc(i))return i;throw bc(vc(i)+" is not an object")},gc=pr,ks=Function.prototype.call,He=gc?ks.bind(ks):function(){return ks.apply(ks,arguments)},bn={},Hr=bn,Gr=Te,Sc=pe,Kn=function(i){return Sc(i)?i:void 0},di=function(i,e){return arguments.length<2?Kn(Hr[i])||Kn(Gr[i]):Hr[i]&&Hr[i][e]||Gr[i]&&Gr[i][e]},yc=Je,mr=yc({}.isPrototypeOf),vr=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Wl=Te,Yr=vr,Jn=Wl.process,Xn=Wl.Deno,Zn=Jn&&Jn.versions||Xn&&Xn.version,eo=Zn&&Zn.v8,st,Ks;eo&&(st=eo.split("."),Ks=st[0]>0&&st[0]<4?1:+(st[0]+st[1]));!Ks&&Yr&&(st=Yr.match(/Edge\/(\d+)/),(!st||st[1]>=74)&&(st=Yr.match(/Chrome\/(\d+)/),st&&(Ks=+st[1])));var Ql=Ks,to=Ql,Tc=Ke,Ec=Te,$c=Ec.String,Kl=!!Object.getOwnPropertySymbols&&!Tc(function(){var i=Symbol();return!$c(i)||!(Object(i)instanceof Symbol)||!Symbol.sham&&to&&to<41}),kc=Kl,Jl=kc&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Ac=di,wc=pe,Pc=mr,_c=Jl,Dc=Object,Xl=_c?function(i){return typeof i=="symbol"}:function(i){var e=Ac("Symbol");return wc(e)&&Pc(e.prototype,Dc(i))},Ic=String,br=function(i){try{return Ic(i)}catch(e){return"Object"}},Rc=pe,Cc=br,xc=TypeError,ci=function(i){if(Rc(i))return i;throw xc(Cc(i)+" is not a function")},Lc=ci,Nc=hs,gr=function(i,e){var t=i[e];return Nc(t)?void 0:Lc(t)},zr=He,qr=pe,Wr=Ct,Oc=TypeError,Bc=function(i,e){var t,s;if(e==="string"&&qr(t=i.toString)&&!Wr(s=zr(t,i))||qr(t=i.valueOf)&&!Wr(s=zr(t,i))||e!=="string"&&qr(t=i.toString)&&!Wr(s=zr(t,i)))return s;throw Oc("Can't convert object to primitive value")},Zl={exports:{}},Mc=!0,io=Te,Vc=Object.defineProperty,Fc=function(i,e){try{Vc(io,i,{value:e,configurable:!0,writable:!0})}catch(t){io[i]=e}return e},Uc=Te,jc=Fc,so="__core-js_shared__",Hc=Uc[so]||jc(so,{}),gn=Hc,ro=gn;(Zl.exports=function(i,e){return ro[i]||(ro[i]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var eu=Zl.exports,Gc=mn,Yc=Object,Sr=function(i){return Yc(Gc(i))},zc=Je,qc=Sr,Wc=zc({}.hasOwnProperty),mt=Object.hasOwn||function(e,t){return Wc(qc(e),t)},Qc=Je,Kc=0,Jc=Math.random(),Xc=Qc(1 .toString),tu=function(i){return"Symbol("+(i===void 0?"":i)+")_"+Xc(++Kc+Jc,36)},Zc=Te,eh=eu,ao=mt,th=tu,ih=Kl,sh=Jl,ki=Zc.Symbol,Qr=eh("wks"),rh=sh?ki.for||ki:ki&&ki.withoutSetter||th,De=function(i){return ao(Qr,i)||(Qr[i]=ih&&ao(ki,i)?ki[i]:rh("Symbol."+i)),Qr[i]},ah=He,no=Ct,oo=Xl,nh=gr,oh=Bc,lh=De,uh=TypeError,dh=lh("toPrimitive"),ch=function(i,e){if(!no(i)||oo(i))return i;var t=nh(i,dh),s;if(t){if(e===void 0&&(e="default"),s=ah(t,i,e),!no(s)||oo(s))return s;throw uh("Can't convert object to primitive value")}return e===void 0&&(e="number"),oh(i,e)},hh=ch,fh=Xl,Sn=function(i){var e=hh(i,"string");return fh(e)?e:e+""},ph=jt,mh=zl,vh=ql,As=xt,lo=Sn,bh=TypeError,Kr=Object.defineProperty,gh=Object.getOwnPropertyDescriptor,Jr="enumerable",Xr="configurable",Zr="writable";ui.f=ph?vh?function(e,t,s){if(As(e),t=lo(t),As(s),typeof e=="function"&&t==="prototype"&&"value"in s&&Zr in s&&!s[Zr]){var r=gh(e,t);r&&r[Zr]&&(e[t]=s.value,s={configurable:Xr in s?s[Xr]:r[Xr],enumerable:Jr in s?s[Jr]:r[Jr],writable:!1})}return Kr(e,t,s)}:Kr:function(e,t,s){if(As(e),t=lo(t),As(s),mh)try{return Kr(e,t,s)}catch(r){}if("get"in s||"set"in s)throw bh("Accessors not supported");return"value"in s&&(e[t]=s.value),e};var yr=function(i,e){return{enumerable:!(i&1),configurable:!(i&2),writable:!(i&4),value:e}},Sh=jt,yh=ui,Th=yr,ps=Sh?function(i,e,t){return yh.f(i,e,Th(1,t))}:function(i,e,t){return i[e]=t,i},Eh=eu,$h=tu,uo=Eh("keys"),yn=function(i){return uo[i]||(uo[i]=$h(i))},Tn={},kh=ac,iu=Te,Ah=Ct,wh=ps,ea=mt,ta=gn,Ph=yn,_h=Tn,co="Object already initialized",Ga=iu.TypeError,Dh=iu.WeakMap,Js,os,Xs,Ih=function(i){return Xs(i)?os(i):Js(i,{})},Rh=function(i){return function(e){var t;if(!Ah(e)||(t=os(e)).type!==i)throw Ga("Incompatible receiver, "+i+" required");return t}};if(kh||ta.state){var lt=ta.state||(ta.state=new Dh);lt.get=lt.get,lt.has=lt.has,lt.set=lt.set,Js=function(i,e){if(lt.has(i))throw Ga(co);return e.facade=i,lt.set(i,e),e},os=function(i){return lt.get(i)||{}},Xs=function(i){return lt.has(i)}}else{var vi=Ph("state");_h[vi]=!0,Js=function(i,e){if(ea(i,vi))throw Ga(co);return e.facade=i,wh(i,vi,e),e},os=function(i){return ea(i,vi)?i[vi]:{}},Xs=function(i){return ea(i,vi)}}var su={set:Js,get:os,has:Xs,enforce:Ih,getterFor:Rh},Ch=pr,ru=Function.prototype,ho=ru.apply,fo=ru.call,au=typeof Reflect=="object"&&Reflect.apply||(Ch?fo.bind(ho):function(){return fo.apply(ho,arguments)}),xh=cs,Lh=Je,nu=function(i){if(xh(i)==="Function")return Lh(i)},En={},ou={},lu={}.propertyIsEnumerable,uu=Object.getOwnPropertyDescriptor,Nh=uu&&!lu.call({1:2},1);ou.f=Nh?function(e){var t=uu(this,e);return!!t&&t.enumerable}:lu;var Oh=jt,Bh=He,Mh=ou,Vh=yr,Fh=fs,Uh=Sn,jh=mt,Hh=zl,po=Object.getOwnPropertyDescriptor;En.f=Oh?po:function(e,t){if(e=Fh(e),t=Uh(t),Hh)try{return po(e,t)}catch(s){}if(jh(e,t))return Vh(!Bh(Mh.f,e,t),e[t])};var Gh=Ke,Yh=pe,zh=/#|\.prototype\./,ms=function(i,e){var t=Wh[qh(i)];return t==Kh?!0:t==Qh?!1:Yh(e)?Gh(e):!!e},qh=ms.normalize=function(i){return String(i).replace(zh,".").toLowerCase()},Wh=ms.data={},Qh=ms.NATIVE="N",Kh=ms.POLYFILL="P",du=ms,mo=nu,Jh=ci,Xh=pr,Zh=mo(mo.bind),Tr=function(i,e){return Jh(i),e===void 0?i:Xh?Zh(i,e):function(){return i.apply(e,arguments)}},ws=Te,ef=au,tf=nu,sf=pe,rf=En.f,af=du,bi=bn,nf=Tr,gi=ps,vo=mt,of=function(i){var e=function(t,s,r){if(this instanceof e){switch(arguments.length){case 0:return new i;case 1:return new i(t);case 2:return new i(t,s)}return new i(t,s,r)}return ef(i,this,arguments)};return e.prototype=i.prototype,e},at=function(i,e){var t=i.target,s=i.global,r=i.stat,n=i.proto,o=s?ws:r?ws[t]:(ws[t]||{}).prototype,l=s?bi:bi[t]||gi(bi,t,{})[t],d=l.prototype,u,c,h,f,p,m,g,S,v;for(f in e)u=af(s?f:t+(r?".":"#")+f,i.forced),c=!u&&o&&vo(o,f),m=l[f],c&&(i.dontCallGetSet?(v=rf(o,f),g=v&&v.value):g=o[f]),p=c&&g?g:e[f],!(c&&typeof m==typeof p)&&(i.bind&&c?S=nf(p,ws):i.wrap&&c?S=of(p):n&&sf(p)?S=tf(p):S=p,(i.sham||p&&p.sham||m&&m.sham)&&gi(S,"sham",!0),gi(l,f,S),n&&(h=t+"Prototype",vo(bi,h)||gi(bi,h,{}),gi(bi[h],f,p),i.real&&d&&(u||!d[f])&&gi(d,f,p)))},Ya=jt,lf=mt,cu=Function.prototype,uf=Ya&&Object.getOwnPropertyDescriptor,$n=lf(cu,"name"),df=$n&&function(){}.name==="something",cf=$n&&(!Ya||Ya&&uf(cu,"name").configurable),hf={EXISTS:$n,PROPER:df,CONFIGURABLE:cf},hu={},ff=Math.ceil,pf=Math.floor,mf=Math.trunc||function(e){var t=+e;return(t>0?pf:ff)(t)},vf=mf,kn=function(i){var e=+i;return e!==e||e===0?0:vf(e)},bf=kn,gf=Math.max,Sf=Math.min,yf=function(i,e){var t=bf(i);return t<0?gf(t+e,0):Sf(t,e)},Tf=kn,Ef=Math.min,$f=function(i){return i>0?Ef(Tf(i),9007199254740991):0},kf=$f,An=function(i){return kf(i.length)},Af=fs,wf=yf,Pf=An,bo=function(i){return function(e,t,s){var r=Af(e),n=Pf(r),o=wf(s,n),l;if(i&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((i||o in r)&&r[o]===t)return i||o||0;return!i&&-1}},_f={includes:bo(!0),indexOf:bo(!1)},Df=Je,ia=mt,If=fs,Rf=_f.indexOf,Cf=Tn,go=Df([].push),xf=function(i,e){var t=If(i),s=0,r=[],n;for(n in t)!ia(Cf,n)&&ia(t,n)&&go(r,n);for(;e.length>s;)ia(t,n=e[s++])&&(~Rf(r,n)||go(r,n));return r},fu=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Lf=xf,Nf=fu,Of=Object.keys||function(e){return Lf(e,Nf)},Bf=jt,Mf=ql,Vf=ui,Ff=xt,Uf=fs,jf=Of;hu.f=Bf&&!Mf?Object.defineProperties:function(e,t){Ff(e);for(var s=Uf(t),r=jf(t),n=r.length,o=0,l;n>o;)Vf.f(e,l=r[o++],s[l]);return e};var Hf=di,pu=Hf("document","documentElement"),Gf=xt,Yf=hu,So=fu,zf=Tn,qf=pu,Wf=vn,Qf=yn,yo=">",To="<",za="prototype",qa="script",mu=Qf("IE_PROTO"),sa=function(){},vu=function(i){return To+qa+yo+i+To+"/"+qa+yo},Eo=function(i){i.write(vu("")),i.close();var e=i.parentWindow.Object;return i=null,e},Kf=function(){var i=Wf("iframe"),e="java"+qa+":",t;return i.style.display="none",qf.appendChild(i),i.src=String(e),t=i.contentWindow.document,t.open(),t.write(vu("document.F=Object")),t.close(),t.F},Ps,zs=function(){try{Ps=new ActiveXObject("htmlfile")}catch(e){}zs=typeof document!="undefined"?document.domain&&Ps?Eo(Ps):Kf():Eo(Ps);for(var i=So.length;i--;)delete zs[za][So[i]];return zs()};zf[mu]=!0;var bu=Object.create||function(e,t){var s;return e!==null?(sa[za]=Gf(e),s=new sa,sa[za]=null,s[mu]=e):s=zs(),t===void 0?s:Yf.f(s,t)},Jf=Ke,Xf=!Jf(function(){function i(){}return i.prototype.constructor=null,Object.getPrototypeOf(new i)!==i.prototype}),Zf=mt,ep=pe,tp=Sr,ip=yn,sp=Xf,$o=ip("IE_PROTO"),Wa=Object,rp=Wa.prototype,gu=sp?Wa.getPrototypeOf:function(i){var e=tp(i);if(Zf(e,$o))return e[$o];var t=e.constructor;return ep(t)&&e instanceof t?t.prototype:e instanceof Wa?rp:null},ap=ps,wn=function(i,e,t,s){return s&&s.enumerable?i[e]=t:ap(i,e,t),i},np=Ke,op=pe,lp=Ct,up=bu,ko=gu,dp=wn,cp=De,Qa=cp("iterator"),Su=!1,Dt,ra,aa;[].keys&&(aa=[].keys(),"next"in aa?(ra=ko(ko(aa)),ra!==Object.prototype&&(Dt=ra)):Su=!0);var hp=!lp(Dt)||np(function(){var i={};return Dt[Qa].call(i)!==i});hp?Dt={}:Dt=up(Dt);op(Dt[Qa])||dp(Dt,Qa,function(){return this});var yu={IteratorPrototype:Dt,BUGGY_SAFARI_ITERATORS:Su},fp=De,pp=fp("toStringTag"),Tu={};Tu[pp]="z";var Pn=String(Tu)==="[object z]",mp=Pn,vp=pe,qs=cs,bp=De,gp=bp("toStringTag"),Sp=Object,yp=qs(function(){return arguments}())=="Arguments",Tp=function(i,e){try{return i[e]}catch(t){}},vs=mp?qs:function(i){var e,t,s;return i===void 0?"Undefined":i===null?"Null":typeof(t=Tp(e=Sp(i),gp))=="string"?t:yp?qs(e):(s=qs(e))=="Object"&&vp(e.callee)?"Arguments":s},Ep=Pn,$p=vs,kp=Ep?{}.toString:function(){return"[object "+$p(this)+"]"},Ap=Pn,wp=ui.f,Pp=ps,_p=mt,Dp=kp,Ip=De,Ao=Ip("toStringTag"),_n=function(i,e,t,s){if(i){var r=t?i:i.prototype;_p(r,Ao)||wp(r,Ao,{configurable:!0,value:e}),s&&!Ap&&Pp(r,"toString",Dp)}},Rp=yu.IteratorPrototype,Cp=bu,xp=yr,Lp=_n,Np=Ni,Op=function(){return this},Bp=function(i,e,t,s){var r=e+" Iterator";return i.prototype=Cp(Rp,{next:xp(+!s,t)}),Lp(i,r,!1,!0),Np[r]=Op,i},Mp=at,Vp=He,Eu=hf,Fp=Bp,Up=gu,jp=_n,wo=wn,Hp=De,Po=Ni,$u=yu,Gp=Eu.PROPER;Eu.CONFIGURABLE;$u.IteratorPrototype;var _s=$u.BUGGY_SAFARI_ITERATORS,na=Hp("iterator"),_o="keys",Ds="values",Do="entries",Yp=function(){return this},zp=function(i,e,t,s,r,n,o){Fp(t,e,s);var l=function(v){if(v===r&&f)return f;if(!_s&&v in c)return c[v];switch(v){case _o:return function(){return new t(this,v)};case Ds:return function(){return new t(this,v)};case Do:return function(){return new t(this,v)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=i.prototype,h=c[na]||c["@@iterator"]||r&&c[r],f=!_s&&h||l(r),p=e=="Array"&&c.entries||h,m,g,S;if(p&&(m=Up(p.call(new i)),m!==Object.prototype&&m.next&&(jp(m,d,!0,!0),Po[d]=Yp)),Gp&&r==Ds&&h&&h.name!==Ds&&(u=!0,f=function(){return Vp(h,this)}),r)if(g={values:l(Ds),keys:n?f:l(_o),entries:l(Do)},o)for(S in g)(_s||u||!(S in c))&&wo(c,S,g[S]);else Mp({target:e,proto:!0,forced:_s||u},g);return o&&c[na]!==f&&wo(c,na,f,{name:r}),Po[e]=f,g},qp=function(i,e){return{value:i,done:e}},Wp=fs,Io=Ni,ku=su;ui.f;var Qp=zp,Is=qp,Au="Array Iterator",Kp=ku.set,Jp=ku.getterFor(Au);Qp(Array,"Array",function(i,e){Kp(this,{type:Au,target:Wp(i),index:0,kind:e})},function(){var i=Jp(this),e=i.target,t=i.kind,s=i.index++;return!e||s>=e.length?(i.target=void 0,Is(void 0,!0)):t=="keys"?Is(s,!1):t=="values"?Is(e[s],!1):Is([s,e[s]],!1)},"values");Io.Arguments=Io.Array;var Xp=De,Zp=Ni,em=Xp("iterator"),tm=Array.prototype,im=function(i){return i!==void 0&&(Zp.Array===i||tm[em]===i)},sm=vs,Ro=gr,rm=hs,am=Ni,nm=De,om=nm("iterator"),wu=function(i){if(!rm(i))return Ro(i,om)||Ro(i,"@@iterator")||am[sm(i)]},lm=He,um=ci,dm=xt,cm=br,hm=wu,fm=TypeError,pm=function(i,e){var t=arguments.length<2?hm(i):e;if(um(t))return dm(lm(t,i));throw fm(cm(i)+" is not iterable")},mm=He,Co=xt,vm=gr,bm=function(i,e,t){var s,r;Co(i);try{if(s=vm(i,"return"),!s){if(e==="throw")throw t;return t}s=mm(s,i)}catch(n){r=!0,s=n}if(e==="throw")throw t;if(r)throw s;return Co(s),t},gm=Tr,Sm=He,ym=xt,Tm=br,Em=im,$m=An,xo=mr,km=pm,Am=wu,Lo=bm,wm=TypeError,Ws=function(i,e){this.stopped=i,this.result=e},No=Ws.prototype,Dn=function(i,e,t){var s=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=gm(e,s),u,c,h,f,p,m,g,S=function(y){return u&&Lo(u,"normal",y),new Ws(!0,y)},v=function(y){return r?(ym(y),l?d(y[0],y[1],S):d(y[0],y[1])):l?d(y,S):d(y)};if(n)u=i.iterator;else if(o)u=i;else{if(c=Am(i),!c)throw wm(Tm(i)+" is not iterable");if(Em(c)){for(h=0,f=$m(i);f>h;h++)if(p=v(i[h]),p&&xo(No,p))return p;return new Ws(!1)}u=km(i,c)}for(m=n?i.next:u.next;!(g=Sm(m,u)).done;){try{p=v(g.value)}catch(y){Lo(u,"throw",y)}if(typeof p=="object"&&p&&xo(No,p))return p}return new Ws(!1)},Pm=Sn,_m=ui,Dm=yr,Im=function(i,e,t){var s=Pm(e);s in i?_m.f(i,s,Dm(0,t)):i[s]=t},Rm=at,Cm=Dn,xm=Im;Rm({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Cm(e,function(s,r){xm(t,s,r)},{AS_ENTRIES:!0}),t}});var Lm=bn,Nm=Lm.Object.fromEntries,Om={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},Bm=Om,Mm=Te,Vm=vs,Fm=ps,Oo=Ni,Um=De,Bo=Um("toStringTag");for(var oa in Bm){var Mo=Mm[oa],la=Mo&&Mo.prototype;la&&Vm(la)!==Bo&&Fm(la,Bo,oa),Oo[oa]=Oo.Array}var jm=Nm,Hm=jm,Gm=Hm,Ym=Gm,ni=fr(Ym),zm=cs,Er=typeof process!="undefined"&&zm(process)=="process",qm=ui,Wm=function(i,e,t){return qm.f(i,e,t)},Qm=di,Km=Wm,Jm=De,Xm=jt,Vo=Jm("species"),Zm=function(i){var e=Qm(i);Xm&&e&&!e[Vo]&&Km(e,Vo,{configurable:!0,get:function(){return this}})},ev=mr,tv=TypeError,iv=function(i,e){if(ev(e,i))return i;throw tv("Incorrect invocation")},sv=Je,rv=pe,Ka=gn,av=sv(Function.toString);rv(Ka.inspectSource)||(Ka.inspectSource=function(i){return av(i)});var Pu=Ka.inspectSource,nv=Je,ov=Ke,_u=pe,lv=vs,uv=di,dv=Pu,Du=function(){},cv=[],Iu=uv("Reflect","construct"),In=/^\s*(?:class|function)\b/,hv=nv(In.exec),fv=!In.exec(Du),Ki=function(e){if(!_u(e))return!1;try{return Iu(Du,cv,e),!0}catch(t){return!1}},Ru=function(e){if(!_u(e))return!1;switch(lv(e)){case"AsyncFunction":case"GeneratorFunction":case"AsyncGeneratorFunction":return!1}try{return fv||!!hv(In,dv(e))}catch(t){return!0}};Ru.sham=!0;var pv=!Iu||ov(function(){var i;return Ki(Ki.call)||!Ki(Object)||!Ki(function(){i=!0})||i})?Ru:Ki,mv=pv,vv=br,bv=TypeError,gv=function(i){if(mv(i))return i;throw bv(vv(i)+" is not a constructor")},Fo=xt,Sv=gv,yv=hs,Tv=De,Ev=Tv("species"),Cu=function(i,e){var t=Fo(i).constructor,s;return t===void 0||yv(s=Fo(t)[Ev])?e:Sv(s)},$v=Je,kv=$v([].slice),Av=TypeError,wv=function(i,e){if(i<e)throw Av("Not enough arguments");return i},Pv=vr,xu=/(?:ipad|iphone|ipod).*applewebkit/i.test(Pv),je=Te,_v=au,Dv=Tr,Uo=pe,Iv=mt,Lu=Ke,jo=pu,Rv=kv,Ho=vn,Cv=wv,xv=xu,Lv=Er,Ja=je.setImmediate,Xa=je.clearImmediate,Nv=je.process,ua=je.Dispatch,Ov=je.Function,Go=je.MessageChannel,Bv=je.String,da=0,rs={},Yo="onreadystatechange",ls,ti,ca,ha;Lu(function(){ls=je.location});var Rn=function(i){if(Iv(rs,i)){var e=rs[i];delete rs[i],e()}},fa=function(i){return function(){Rn(i)}},zo=function(i){Rn(i.data)},qo=function(i){je.postMessage(Bv(i),ls.protocol+"//"+ls.host)};(!Ja||!Xa)&&(Ja=function(e){Cv(arguments.length,1);var t=Uo(e)?e:Ov(e),s=Rv(arguments,1);return rs[++da]=function(){_v(t,void 0,s)},ti(da),da},Xa=function(e){delete rs[e]},Lv?ti=function(i){Nv.nextTick(fa(i))}:ua&&ua.now?ti=function(i){ua.now(fa(i))}:Go&&!xv?(ca=new Go,ha=ca.port2,ca.port1.onmessage=zo,ti=Dv(ha.postMessage,ha)):je.addEventListener&&Uo(je.postMessage)&&!je.importScripts&&ls&&ls.protocol!=="file:"&&!Lu(qo)?(ti=qo,je.addEventListener("message",zo,!1)):Yo in Ho("script")?ti=function(i){jo.appendChild(Ho("script"))[Yo]=function(){jo.removeChild(this),Rn(i)}}:ti=function(i){setTimeout(fa(i),0)});var Nu={set:Ja,clear:Xa},Ou=function(){this.head=null,this.tail=null};Ou.prototype={add:function(i){var e={item:i,next:null},t=this.tail;t?t.next=e:this.head=e,this.tail=e},get:function(){var i=this.head;if(i){var e=this.head=i.next;return e===null&&(this.tail=null),i.item}}};var Bu=Ou,Mv=vr,Vv=/ipad|iphone|ipod/i.test(Mv)&&typeof Pebble!="undefined",Fv=vr,Uv=/web0s(?!.*chrome)/i.test(Fv),oi=Te,Wo=Tr,jv=En.f,pa=Nu.set,Hv=Bu,Gv=xu,Yv=Vv,zv=Uv,ma=Er,Qo=oi.MutationObserver||oi.WebKitMutationObserver,Ko=oi.document,Jo=oi.process,Rs=oi.Promise,Xo=jv(oi,"queueMicrotask"),Za=Xo&&Xo.value,Si,va,ba,Cs,Zo;if(!Za){var xs=new Hv,Ls=function(){var i,e;for(ma&&(i=Jo.domain)&&i.exit();e=xs.get();)try{e()}catch(t){throw xs.head&&Si(),t}i&&i.enter()};!Gv&&!ma&&!zv&&Qo&&Ko?(va=!0,ba=Ko.createTextNode(""),new Qo(Ls).observe(ba,{characterData:!0}),Si=function(){ba.data=va=!va}):!Yv&&Rs&&Rs.resolve?(Cs=Rs.resolve(void 0),Cs.constructor=Rs,Zo=Wo(Cs.then,Cs),Si=function(){Zo(Ls)}):ma?Si=function(){Jo.nextTick(Ls)}:(pa=Wo(pa,oi),Si=function(){pa(Ls)}),Za=function(i){xs.head||Si(),xs.add(i)}}var qv=Za,Wv=function(i,e){try{arguments.length==1?console.error(i):console.error(i,e)}catch(t){}},Cn=function(i){try{return{error:!1,value:i()}}catch(e){return{error:!0,value:e}}},Qv=Te,Oi=Qv.Promise,Mu=typeof Deno=="object"&&Deno&&typeof Deno.version=="object",Kv=Mu,Jv=Er,Xv=!Kv&&!Jv&&typeof window=="object"&&typeof document=="object",Zv=Te,as=Oi,eb=pe,tb=du,ib=Pu,sb=De,rb=Xv,ab=Mu,ga=Ql,el=as&&as.prototype,nb=sb("species"),en=!1,Vu=eb(Zv.PromiseRejectionEvent),ob=tb("Promise",function(){var i=ib(as),e=i!==String(as);if(!e&&ga===66||!(el.catch&&el.finally))return!0;if(!ga||ga<51||!/native code/.test(i)){var t=new as(function(n){n(1)}),s=function(n){n(function(){},function(){})},r=t.constructor={};if(r[nb]=s,en=t.then(function(){})instanceof s,!en)return!0}return!e&&(rb||ab)&&!Vu}),bs={CONSTRUCTOR:ob,REJECTION_EVENT:Vu,SUBCLASSING:en},Bi={},tl=ci,lb=TypeError,ub=function(i){var e,t;this.promise=new i(function(s,r){if(e!==void 0||t!==void 0)throw lb("Bad Promise constructor");e=s,t=r}),this.resolve=tl(e),this.reject=tl(t)};Bi.f=function(i){return new ub(i)};var db=at,Zs=Er,Ft=Te,gs=He,cb=wn,hb=_n,fb=Zm,pb=ci,tn=pe,mb=Ct,vb=iv,bb=Cu,Fu=Nu.set,xn=qv,gb=Wv,Sb=Cn,yb=Bu,Uu=su,sn=Oi,Ln=bs,ju=Bi,$r="Promise",Hu=Ln.CONSTRUCTOR,Tb=Ln.REJECTION_EVENT;Ln.SUBCLASSING;var Sa=Uu.getterFor($r),Eb=Uu.set,$b=sn&&sn.prototype,Ai=sn,ya=$b,Gu=Ft.TypeError,rn=Ft.document,Nn=Ft.process,an=ju.f,kb=an,Ab=!!(rn&&rn.createEvent&&Ft.dispatchEvent),Yu="unhandledrejection",wb="rejectionhandled",il=0,zu=1,Pb=2,On=1,qu=2,Ns,sl,_b,Wu=function(i){var e;return mb(i)&&tn(e=i.then)?e:!1},Qu=function(i,e){var t=e.value,s=e.state==zu,r=s?i.ok:i.fail,n=i.resolve,o=i.reject,l=i.domain,d,u,c;try{r?(s||(e.rejection===qu&&Ib(e),e.rejection=On),r===!0?d=t:(l&&l.enter(),d=r(t),l&&(l.exit(),c=!0)),d===i.promise?o(Gu("Promise-chain cycle")):(u=Wu(d))?gs(u,d,n,o):n(d)):o(t)}catch(h){l&&!c&&l.exit(),o(h)}},Ku=function(i,e){i.notified||(i.notified=!0,xn(function(){for(var t=i.reactions,s;s=t.get();)Qu(s,i);i.notified=!1,e&&!i.rejection&&Db(i)}))},Ju=function(i,e,t){var s,r;Ab?(s=rn.createEvent("Event"),s.promise=e,s.reason=t,s.initEvent(i,!1,!0),Ft.dispatchEvent(s)):s={promise:e,reason:t},!Tb&&(r=Ft["on"+i])?r(s):i===Yu&&gb("Unhandled promise rejection",t)},Db=function(i){gs(Fu,Ft,function(){var e=i.facade,t=i.value,s=rl(i),r;if(s&&(r=Sb(function(){Zs?Nn.emit("unhandledRejection",t,e):Ju(Yu,e,t)}),i.rejection=Zs||rl(i)?qu:On,r.error))throw r.value})},rl=function(i){return i.rejection!==On&&!i.parent},Ib=function(i){gs(Fu,Ft,function(){var e=i.facade;Zs?Nn.emit("rejectionHandled",e):Ju(wb,e,i.value)})},wi=function(i,e,t){return function(s){i(e,s,t)}},Di=function(i,e,t){i.done||(i.done=!0,t&&(i=t),i.value=e,i.state=Pb,Ku(i,!0))},nn=function(i,e,t){if(!i.done){i.done=!0,t&&(i=t);try{if(i.facade===e)throw Gu("Promise can't be resolved itself");var s=Wu(e);s?xn(function(){var r={done:!1};try{gs(s,e,wi(nn,r,i),wi(Di,r,i))}catch(n){Di(r,n,i)}}):(i.value=e,i.state=zu,Ku(i,!1))}catch(r){Di({done:!1},r,i)}}};Hu&&(Ai=function(e){vb(this,ya),pb(e),gs(Ns,this);var t=Sa(this);try{e(wi(nn,t),wi(Di,t))}catch(s){Di(t,s)}},ya=Ai.prototype,Ns=function(e){Eb(this,{type:$r,done:!1,notified:!1,parent:!1,reactions:new yb,rejection:!1,state:il,value:void 0})},Ns.prototype=cb(ya,"then",function(e,t){var s=Sa(this),r=an(bb(this,Ai));return s.parent=!0,r.ok=tn(e)?e:!0,r.fail=tn(t)&&t,r.domain=Zs?Nn.domain:void 0,s.state==il?s.reactions.add(r):xn(function(){Qu(r,s)}),r.promise}),sl=function(){var i=new Ns,e=Sa(i);this.promise=i,this.resolve=wi(nn,e),this.reject=wi(Di,e)},ju.f=an=function(i){return i===Ai||i===_b?new sl(i):kb(i)});db({global:!0,constructor:!0,wrap:!0,forced:Hu},{Promise:Ai});hb(Ai,$r,!1,!0);fb($r);var Rb=De,Xu=Rb("iterator"),Zu=!1;try{var Cb=0,al={next:function(){return{done:!!Cb++}},return:function(){Zu=!0}};al[Xu]=function(){return this},Array.from(al,function(){throw 2})}catch(i){}var xb=function(i,e){if(!e&&!Zu)return!1;var t=!1;try{var s={};s[Xu]=function(){return{next:function(){return{done:t=!0}}}},i(s)}catch(r){}return t},Lb=Oi,Nb=xb,Ob=bs.CONSTRUCTOR,ed=Ob||!Nb(function(i){Lb.all(i).then(void 0,function(){})}),Bb=at,Mb=He,Vb=ci,Fb=Bi,Ub=Cn,jb=Dn,Hb=ed;Bb({target:"Promise",stat:!0,forced:Hb},{all:function(e){var t=this,s=Fb.f(t),r=s.resolve,n=s.reject,o=Ub(function(){var l=Vb(t.resolve),d=[],u=0,c=1;jb(e,function(h){var f=u++,p=!1;c++,Mb(l,t,h).then(function(m){p||(p=!0,d[f]=m,--c||r(d))},n)}),--c||r(d)});return o.error&&n(o.value),s.promise}});var Gb=at,Yb=bs.CONSTRUCTOR,nl=Oi;nl&&nl.prototype;Gb({target:"Promise",proto:!0,forced:Yb,real:!0},{catch:function(i){return this.then(void 0,i)}});var zb=at,qb=He,Wb=ci,Qb=Bi,Kb=Cn,Jb=Dn,Xb=ed;zb({target:"Promise",stat:!0,forced:Xb},{race:function(e){var t=this,s=Qb.f(t),r=s.reject,n=Kb(function(){var o=Wb(t.resolve);Jb(e,function(l){qb(o,t,l).then(s.resolve,r)})});return n.error&&r(n.value),s.promise}});var Zb=at,eg=He,tg=Bi,ig=bs.CONSTRUCTOR;Zb({target:"Promise",stat:!0,forced:ig},{reject:function(e){var t=tg.f(this);return eg(t.reject,void 0,e),t.promise}});var sg=xt,rg=Ct,ag=Bi,td=function(i,e){if(sg(i),rg(e)&&e.constructor===i)return e;var t=ag.f(i),s=t.resolve;return s(e),t.promise},ng=at,og=di,lg=Mc,ug=Oi,dg=bs.CONSTRUCTOR,cg=td,hg=og("Promise"),fg=!dg;ng({target:"Promise",stat:!0,forced:lg},{resolve:function(e){return cg(fg&&this===hg?ug:this,e)}});var pg=at,on=Oi,mg=Ke,vg=di,bg=pe,gg=Cu,ol=td,Sg=on&&on.prototype,yg=!!on&&mg(function(){Sg.finally.call({then:function(){}},function(){})});pg({target:"Promise",proto:!0,real:!0,forced:yg},{finally:function(i){var e=gg(this,vg("Promise")),t=bg(i);return this.then(t?function(s){return ol(e,i()).then(function(){return s})}:i,t?function(s){return ol(e,i()).then(function(){throw s})}:i)}});var Tg=di,Bn=Tg,Eg=Bn,$g=Eg("Promise","finally"),kg=$g,Ag=kg,wg=Ag,Pg=wg,Ss=fr(Pg),ae;(function(i){i[i.OFFSET_P=0]="OFFSET_P",i[i.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",i[i.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ae||(ae={}));var Pe=(i,e=0,t=ae.OFFSET_P)=>{switch(t){case ae.OFFSET_P:return i.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ae.PLAYBACK_SHIFT:{if(e===0)return i;const s=new URL(i);return s.searchParams.append("playback_shift",e.toFixed(0)),s.toString()}case ae.DASH_CMAF_OFFSET_P:{const s=new URL(i);return!s.searchParams.get("offset_p")&&e===0?i:(s.searchParams.set("offset_p",e.toFixed(0)),s.toString())}default:a.assertNever(t)}return i};const er=(i,e)=>{var t;switch(e){case ae.OFFSET_P:return NaN;case ae.PLAYBACK_SHIFT:{const s=new URL(i);return Number(s.searchParams.get("playback_shift"))}case ae.DASH_CMAF_OFFSET_P:{const s=new URL(i);return Number((t=s.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var w=(i,e,t=!1)=>{const s=i.getTransition();(t||!s||s.to===e)&&i.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,s=this.state;this.transition=void 0,this.prevState=s,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:s,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,s=this.state;s===e||a.isNonNullable(t)&&t.to===e||(this.prevState=s,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const _g=i=>{switch(i){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(i)}};var H;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(H||(H={}));const Dg=5,Ig=5,Rg=500,ll=7e3;class Cg{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new ee(H.STOPPED),this.syncPlayback=()=>{const s=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${s}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){s!==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&&s!==H.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(s){case H.PLAYING:case H.PAUSED:case H.READY:break;case H.STOPPED:this.videoState.startTransitionTo(H.READY),this.prepare();break;default:a.assertNever(s)}break}case exports.PlaybackState.PLAYING:{switch(s){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(s)}break}case exports.PlaybackState.PAUSED:{switch(s){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(s)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(_g(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(Rg)).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)>Dg)&&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<Ig&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const s=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(s,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(H.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(H.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const s=this.params.output.isLive$.getValue();this.params.output.duration$.next(s?0:t.duration),this.params.output.position$.next(s?0:t.currentTime),this.params.desiredState.seekState.setState({state:Y.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),s=this.createLoadRequest(t);this.loadMedia(s)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===H.PAUSED||e===H.PLAYING)&&(this.videoState.setState(H.PAUSED),w(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),w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==H.STOPPED&&this.videoState.setState(H.STOPPED)}handleRemoteVolumeChange(e){var t,s;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(s=e.muted)!==null&&s!==void 0?s:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:s}=this.params.connection;t.currentTime=e,s.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const s=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=s[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=s[e];a.assertNonNullable(c),r=Pe(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const s=this.params.desiredState.seekState.getState();return s.state===Y.Applying||s.state===Y.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:s.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),s=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(ll).subscribe(()=>n(`timeout(${ll})`)))});Ss(Promise.race([t,s]).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 xg=i=>{let e,t=!1,s=!1;i.on("playbackTimeUpdated",({timeToEnd:r})=>{s=r<=3,t&&s&&(e==null||e())}),i.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&s&&(e==null||e())}}},!0)},Lg=i=>{const e=new a.ValueSubject(1/0),t=new a.Subject,s=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,g;const S=ni(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(b=>b.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const b=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:b*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const v=(m=S["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(g={1:!0,0:!1}[S["x-reused"]])!==null&&g!==void 0?g:void 0;s.next(v),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return i.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...g){return d(this),p(...g)},f.progress=function(...g){return u(this),m(...g)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:s}},Ut=i=>{const e=new URL(i);return e.searchParams.set("quic","1"),e.toString()},Ng=i=>i.extend("RequestModifier",()=>({modifyRequestURL:Ut}),!0),Og=i=>{i.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:s=>{if(s.request&&s.request.range){const[r,n]=s.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(s.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),s.request.url=o.toString(),s.request.range=void 0}t(s)}}},!0)};const rt=(i,e,t,{equal:s=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=i.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=i.getState();s(c,h)&&i.setState(c)},n)),s(l,o)||(t(o),d&&i.setState(o)),u.add(i.stateChangeStarted$.subscribe(c=>{t(c.to),d&&i.setState(c.to)},n)),u},Ht=(i,e,t)=>rt(e,()=>i.loop,s=>{a.isNonNullable(s)&&(i.loop=s)},{onError:t}),vt=(i,e,t,s)=>rt(e,()=>({muted:i.muted,volume:i.volume}),r=>{a.isNonNullable(r)&&(i.muted=r.muted,i.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:s}),Lt=(i,e,t,s)=>rt(e,()=>i.playbackRate,r=>{a.isNonNullable(r)&&(i.playbackRate=r)},{changed$:t,onError:s}),Bg=i=>["__",i.language,i.label].join("|"),Mg=(i,e)=>{if(i.id===e)return!0;const[t,s,r]=e.split("|");return i.language===s&&i.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,s){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(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 s=this.current$.getValue();s&&this.select(s)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(s=>this.htmlTextTrackToITextTrack(s))),a.filterChanged((s,r)=>s.length===r.length&&s.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:s})=>s==="showing")),a.map(s=>s&&this.htmlTextTrackToITextTrack(s).id),a.filterChanged()).subscribe(this.current$));const t=s=>{var r,n;return this.applyCueSettings((n=(r=s.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(s=>{var r,n;(r=s.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=s.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(s=>{var r;(r=s.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const s of Array.from(e)){const r=s;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(nt.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,s;const{language:r,label:n}=e,o=e.id?e.id:Bg(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(s=this.internalTracks.get(o))===null||s===void 0?void 0:s.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(s=>s.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:s,language:r,isAuto:n})=>!this.internalTracks.has(s)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(s=>this.attach(s)),Array.from(this.internalTracks).filter(([s])=>!e.find(r=>r.id===s)).forEach(([,s])=>this.detach(s))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!Mg(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),s=>s.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const Mn=i=>{i.removeAttribute("src"),i.load()},Vg=i=>{try{i.pause(),i.playbackRate=0,Mn(i),i.remove()}catch(e){console.error(e)}};class Fg{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 ln=window.WeakMap?new WeakMap:new Fg,bt=i=>{let e=i.querySelector("video");const t=!!e;return e?Mn(e):(e=document.createElement("video"),i.appendChild(e)),ln.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},gt=i=>{const e=ln.get(i);ln.delete(i),e?Mn(i):Vg(i)};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 id=i=>{var e;let t=i;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},ul=i=>{const e=id(i);return!!(e&&e.fullscreenElement&&e.fullscreenElement===i)},Ug=i=>{const e=id(i);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===i)},un=3;class jg{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,s=this._source.buffered.length;t<s;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<un&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,s){return t.from-s.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const s=this.getNext(e);if(s&&s.from-e.to<(t||un))return s}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,s){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?s(t,n):l?s(r,e):r<e&&n>t?(s(t,n),s(r,e)):s(r,n))})}destroy(){this._buffer=[]}}var sd=(i,e,t=un)=>{let s=0,r=0;for(let n=0;n<i.length;n++){const o=i.start(n),l=i.end(n);if(o<=e&&e<=l){if(s=o,r=l,!t)return{from:s,to:r};for(let d=n-1;d>=0;d--)i.end(d)+t>=s&&(s=i.start(d));for(let d=n+1;d<i.length;d++)i.start(d)-t<=r&&(r=i.end(d))}}return{from:s,to:r}};const St=i=>{const e=b=>a.fromEvent(i,b).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],s=a.merge(...t.map(b=>a.fromEvent(i,b))).pipe(a.map(b=>b.type==="ended"?i.readyState<2:i.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(i,"progress"),a.fromEvent(i,"timeupdate")).pipe(a.map(()=>sd(i.buffered,i.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(i,"volumechange").pipe(a.map(()=>({muted:i.muted,volume:i.volume}))),d=a.fromEvent(i,"ratechange").pipe(a.map(()=>i.playbackRate)),u=a.fromEvent(i,"error").pipe(a.filter(()=>!!(i.error||i.played.length)),a.map(()=>{var b;const T=i.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(b=i.error)!==null&&b!==void 0?b:void 0}})),c=a.fromEvent(i,"timeupdate").pipe(a.map(()=>i.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(b=>{i.loop&&a.isNonNullable(p)&&a.isNonNullable(b)&&p>=i.duration-f&&b<=f&&h.next(p),p=b});const m=a.fromEvent(i,"enterpictureinpicture"),g=a.fromEvent(i,"leavepictureinpicture"),S=new a.ValueSubject(Ug(i));m.subscribe(()=>S.next(!0)),g.subscribe(()=>S.next(!1));const v=new a.ValueSubject(ul(i));return a.fromEvent(i,"fullscreenchange").pipe(a.map(()=>ul(i))).subscribe(v),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!i.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:a.fromEvent(i,"durationchange").pipe(a.map(()=>i.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:S,inFullscreen$:v}},kr=i=>{if(i.includes("/")){const e=i.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(i)};var Hg=at,Gg=Sr,Yg=An,zg=kn;Hg({target:"Array",proto:!0},{at:function(e){var t=Gg(this),s=Yg(t),r=zg(e),n=r>=0?r:s+r;return n<0||n>=s?void 0:t[n]}});var qg=Bn,Wg=qg("Array","at"),Qg=Wg,Kg=Qg,Jg=Kg,Xg=Jg,ge=fr(Xg);let Vn=!1,_t={};const Zg=i=>{Vn=i},eS=()=>{_t={}},tS=i=>{i(_t)},Os=(i,e)=>{var t;Vn&&(_t.meta=(t=_t.meta)!==null&&t!==void 0?t:{},_t.meta[i]=e)};class ct{constructor(e){this.name=e}next(e){var t,s;if(!Vn)return;_t.series=(t=_t.series)!==null&&t!==void 0?t:{};const r=(s=_t.series[this.name])!==null&&s!==void 0?s:[];r.push([Date.now(),e]),_t.series[this.name]=r}}var si;(function(i){i.FitsContainer="FitsContainer",i.FitsThroughput="FitsThroughput",i.Buffer="Buffer",i.DroppedFramesLimit="DroppedFramesLimit",i.FitsQualityLimits="FitsQualityLimits"})(si||(si={}));const iS=new ct("best_bitrate"),sS=(i,e,t)=>(e-t)*Math.pow(2,-10*i)+t;class rd{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const rS='Assertion "ABR Tracks is empty array" failed',hi=(i,{container:e,throughput:t,tuning:s,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,g,S;a.assertNotEmptyArray(i,rS);const v=s.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=s.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*s.containerSizeFactor,height:e.height*v*s.containerSizeFactor},b=y&&a.videoSizeToQuality(y),T=s.considerPlaybackRate&&a.isNonNullable(l)?l:1,E=i.filter(R=>!a.isInvariantQuality(R.quality)).sort((R,_)=>a.isHigher(R.quality,_.quality)?-1:1),P=(p=ge(E,-1))===null||p===void 0?void 0:p.quality,N=(m=ge(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),L=T*sS(o!=null?o:.5,s.bitrateFactorAtEmptyBuffer,s.bitrateFactorAtFullBuffer),B={},D=E.filter(R=>(b?a.isLower(R.quality,b):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(R.bitrate)?t-n>=R.bitrate*L:!0)?s.lazyQualitySwitch&&a.isNonNullable(s.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<s.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&&iS.next(D.bitrate);const I=(g=D!=null?D:E[Math.ceil((E.length-1)/2)])!==null&&g!==void 0?g:i[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
|
${i.map(R=>`{ id: ${R.id}, quality: ${R.quality}, bitrate: ${R.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
@@ -32,15 +32,15 @@
|
|
|
32
32
|
|
|
33
33
|
[best track] ${D==null?void 0:D.quality}
|
|
34
34
|
[selected track] ${I==null?void 0:I.quality}
|
|
35
|
-
`});const
|
|
35
|
+
`});const U=I&&u&&u.history[I.id]&&a.now()-u.history[I.id]<=s.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!U&&u.recordSelection(I),U&&(u!=null&&u.last)){const R=u.last;return u==null||u.recordSwitch(R),h({message:`
|
|
36
36
|
[last selected] ${R==null?void 0:R.quality}
|
|
37
|
-
`}),R}return u==null||u.recordSwitch(I),I};var _e=i=>new URL(i).hostname;const rS=300,us=(i,e=rS)=>new a.Observable(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(Bd(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()});class Ts{constructor(){this.onDroopedVideoFramesLimit$=new a.Subject,this.subscription=new a.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new a.Subject,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!a.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(r-n)/r;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&a.isHigher(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),s=a.merge(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>a.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Ji={};var Q;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const fe=(i,e)=>new a.Observable(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class dl{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(Q.DOWNLOADING_LIB),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.videoTracks$=new a.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new ys,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===Q.DOWNLOADING_LIB||t===Q.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===Y.Requested&&t!==Q.STOPPED&&s!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),s){case exports.PlaybackState.STOPPED:{switch(t){case Q.STOPPED:break;case Q.PLAYING:case Q.PAUSED:case Q.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case Q.STOPPED:this.prepare();break;case Q.PLAYING:case Q.PAUSED:case Q.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case Q.PLAYING:break;case Q.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Q.READY:this.play();break;case Q.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case Q.PLAYING:this.pause(),this.liveOffset.pause();break;case Q.PAUSED:break;case Q.READY:this.videoState.setState(Q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Q.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(s)}},this.video=bt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ss(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Ji.MediaPlayer=r.MediaPlayer,Ji.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(Ji.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Ji.Debug,"dashjs not loaded"),this.player=Ji.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?kr(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Ng(this.player),Cg(this.player),this.params.tuning.requestQuick&&Lg(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=b=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:b})},r=(b,T)=>this.subscription.add(b.subscribe(T,s));r(us(this.video),this.elementSize$),r(fe(this.player,"error").pipe(a.map(b=>{const T=typeof b.error=="object"?b.error.code:b.error,E=typeof b.error=="object"?b.error.message:void 0;return{id:`DashJS#${T}`,message:E}})),e.error$),r(fe(this.player,"playbackError").pipe(a.map(b=>({id:"DashJSPlayback",message:b.error}))),e.error$);const n=fe(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:b})=>b==="video"),a.map(({newQuality:b})=>{var T;return(T=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===b))===null||T===void 0?void 0:T.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:b})=>b===Q.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(rt(t.videoTrack,()=>{var b;const T=this.player.getQualityFor("video");return(b=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===T))===null||b===void 0?void 0:b.track},b=>{var T;if(a.isNullable(b))return;const E=(T=this.videoTracks$.getValue().find(({track:P})=>P.id===b.id))===null||T===void 0?void 0:T.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n,onError:s}))},s)),this.subscription.add(rt(t.autoVideoTrackSwitching,()=>{var b,T,E;return(E=(T=(b=this.player.getSettings().streaming)===null||b===void 0?void 0:b.abr)===null||T===void 0?void 0:T.autoSwitchBitrate)===null||E===void 0?void 0:E.video},b=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:b}}}}),{onError:s})),r(fe(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:b})=>b==="video"),a.map(({state:b})=>b==="bufferStalled")),e.isBuffering$),r(fe(this.player,"fragmentLoadingStarted"),({mediaType:b,request:{url:T}})=>{var E,P;const N=this.player.getDashMetrics(),V=N.getLatestFragmentRequestHeaderValueByID(b,"X-Reused"),L=(E=N.getLatestFragmentRequestHeaderValueByID(b,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,B=(P={1:!0,0:!1}[V])!==null&&P!==void 0?P:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(B),e.hostname$.next(_e(T))}),r(fe(this.player,"streamInitialized"),({streamInfo:{duration:b,manifestInfo:{isDynamic:T,availableFrom:E}}})=>{this.isLive$.next(T),this.availableFrom$.next(E.getTime()),T||e.duration$.next(b);const P=[],N=this.player.getQualityFor("video");let V;for(const L of this.player.getBitrateInfoListFor("video")){const B=L.qualityIndex.toString(10),M=a.videoSizeToQuality(L),D=L.bitrate/1e3,I={width:L.width,height:L.height},F=this.frameRatesByFrameHeight[L.height];if(M){const R={id:B,quality:M,bitrate:D,size:I,fps:F};P.push({track:R,bitrateInfo:L}),L.qualityIndex===N&&(V=R)}}this.videoTracks$.next(P),e.availableVideoTracks$.next(P.map(({track:L})=>L)),V&&e.currentVideoTrack$.next(V),this.videoState.setState(Q.STREAM_INITIALIZED),this.videoState.startTransitionTo(Q.READY)}),r(fe(this.player,"fragmentLoadingCompleted"),({request:b})=>{if(!b.requestEndDate||!b.firstByteDate||!b.bytesLoaded)return;const T=b.requestEndDate.getTime()-b.firstByteDate.getTime(),E=b.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,T)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const b=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=hi(this.videoTracks$.getValue().map(({track:N})=>N),{container:this.elementSize$.getValue(),throughput:b,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),E=t.autoVideoTrackLimits.getTransition();E&&e.autoVideoTrackLimits$.next(E.to);const P=this.videoTracks$.getValue().find(({track:N})=>N===T);P!=null&&P.bitrateInfo&&this.player.setQualityFor("video",P==null?void 0:P.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:b})=>b),a.map(({maxSeekBackTime:b})=>-b/1e3)),this.params.output.duration$);const o=fe(this.player,"playbackTimeUpdated").pipe(a.map(({time:b})=>b!=null?b:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:b,currentTime:T})=>this.params.output.liveTime$.next(b+T*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(fe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(fe(this.player,"playbackEnded"),e.endedEvent$),r(fe(this.player,"playbackProgress").pipe(a.map(()=>sd(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(fe(this.player,"playbackPlaying"),()=>{this.videoState.setState(Q.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)}),r(fe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(fe(this.player,"playbackPaused"),()=>{this.videoState.setState(Q.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)}),r(fe(this.player,"canPlay"),()=>{var b;((b=this.videoState.getTransition())===null||b===void 0?void 0:b.to)===Q.READY&&this.videoState.setState(Q.READY)}),r(this.isLive$,e.isLive$),r(us(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=xg(this.player);r(c,this.params.output.httpConnectionType$),r(h,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(a.once()),e.firstBytesEvent$),r(fe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(b=>b<60))}),({isLive:b,isShort:T})=>{const E=!b&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),r(o.pipe(a.filter(b=>b>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(fe(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(fe(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),r(fe(this.player,"manifestLoaded"),b=>{var T,E,P,N,V,L,B;if(!((E=(T=b.data)===null||T===void 0?void 0:T.Period)===null||E===void 0)&&E.AdaptationSet){const M=[];for(const D of(N=(P=b.data)===null||P===void 0?void 0:P.Period)===null||N===void 0?void 0:N.AdaptationSet)if(D.contentType==="text"){const I=(V=D.Representation)===null||V===void 0?void 0:V.id,F=new URL((L=D.Representation)===null||L===void 0?void 0:L.BaseURL,(B=b.data)===null||B===void 0?void 0:B.baseUri).toString(),R="internal",_=D.lang;M.push({id:I,url:F,type:R,language:_})}t.internalTextTracks.startTransitionTo(M)}}),this.subscription.add(Ht(this.video,t.isLooped,s));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:g,inFullscreen$:S,pause$:v,playing$:y}=St(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:y,pause$:v,tracks$:this.videoTracks$.pipe(a.map(b=>b.map(({track:T})=>T)))}),this.subscription.add(vt(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Lt(this.video,t.playbackRate,m,s)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(S.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Q.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Q.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Pe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ae.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(Q.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}gt(this.video),this.params.output.element$.next(void 0)}}var Mi=i=>{switch(i){case"mobile":return a.VideoQuality.Q_144P;case"lowest":return a.VideoQuality.Q_240P;case"low":return a.VideoQuality.Q_360P;case"sd":case"medium":return a.VideoQuality.Q_480P;case"hd":case"high":return a.VideoQuality.Q_720P;case"fullhd":case"full":return a.VideoQuality.Q_1080P;case"quadhd":case"quad":return a.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return a.VideoQuality.Q_2160P}};const cl=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Nt=i=>H(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!cl(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return cl(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function we(){return a.now()}function ad(i){return we()-i}function hl(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=o=>s.test(o);return{resolve:(o,l,d=!1)=>{r(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function aS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Qs(i,e,t,s){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,g=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const D=ad(c);let I;if(D<g){I=g-D,setTimeout(S,I);return}g*=2,g>m&&(g=m),o&&o.abort(),o=new r,P()};const v=D=>(n=D,M),y=D=>(h=D,M),b=()=>(p="json",M),T=()=>{if(!d){if(--u>=0){S(),s&&s();return}d=!0,h&&h(),t&&t()}},E=D=>(f=D,M),P=()=>{c=we(),o=new r,o.open("get",i);let D=0,I,F=0;const R=()=>(a.assertNonNullable(c),Math.max(c,Math.max(I||0,F||0)));if(n&&o.addEventListener("progress",_=>{const O=we();n.updateChunk&&_.loaded>D&&(n.updateChunk(R(),_.loaded-D),D=_.loaded,I=O)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const _=o.status;if(_>=200&&_<300){if(o.response.byteLength&&n){const O=o.response.byteLength-D;O&&n.updateChunk&&n.updateChunk(R(),O)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const _=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(F=we(),o.removeEventListener("readystatechange",_))};o.addEventListener("readystatechange",_)}return o.responseType=p,o.send(),M},M={withBitrateReporting:v,withParallel:E,withJSONResponse:b,withRetryCount:D=>(u=D,M),withRetryInterval:(D,I)=>(a.isNonNullable(D)&&(g=D),a.isNonNullable(I)&&(m=I),M),withTimeout:D=>(l=D,M),withFinally:y,send:P,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return M}const nS=100,oS=2e3,lS=500;let uS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-lS;if(t-e>oS){let s=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&s>0){const n=r*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>nS&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class dS{constructor(e,t,s,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=we(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=we()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Qs(t,n,()=>r("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=we()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=we();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=r,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Bs=1e4,Ms=3,cS=300,hS=2e3,fS=6e4,pS=10,mS=1,vS=500;class bS{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new uS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=hl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!r||n.bitrate>r.bitrate)&&(r=n):(!s||s.bitrate>n.bitrate)&&(s=n));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{aS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new dS(Ms,Bs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const T=n&&(!c||c===this.rep);return T||t("Not running!"),T},f=(T,E,P)=>{d&&d.abort(),d=Qs(this.urlResolver.resolve(T,!1),E,P,()=>this._retryCallback()).withTimeout(Bs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ms).withFinally(()=>{d=null}).send()},p=(T,E,P)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,P,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=T=>{const E=s.playbackRate;s.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),s.playbackRate=T)},g=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const P=we()-1e4;let N=0;for(let L=0;L<this.bufferStates.length;L++){const B=this.bufferStates[L];T=Math.min(T,B.buf),B.ts<P&&N++}this.bufferStates.splice(0,N),t(`update playback rate; minBuffer=${T} drop=${N} jitter=${this.sourceJitter}`);let V=T-mS;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?m(1.15):V>1?m(1.1):V>.3?m(1.05):m(1)}},v=T=>{let E;const P=()=>E&&E.start?E.start.length:0,N=_=>E.start[_]/1e3,V=_=>E.dur[_]/1e3,L=_=>E.fragIndex+_,B=(_,O)=>({chunkIdx:L(_),startTS:N(_),dur:V(_),discontinuity:O}),M=()=>{let _=0;if(E&&E.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=O;this.sourceJitter>1&&(te+=this.sourceJitter-1);let ne=E.dur.length-1;for(;ne>=0&&(te-=E.dur[ne],!(te<=0));--ne);_=Math.min(ne,E.dur.length-1-z),_=Math.max(_,0)}return B(_,!0)},D=_=>{const O=P();if(!(O<=0)){if(a.isNonNullable(_)){for(let z=0;z<O;z++)if(N(z)>_)return B(z)}return M()}},I=_=>{const O=P(),z=_?_.chunkIdx+1:0,te=z-E.fragIndex;if(!(O<=0)){if(!_||te<0||te-O>pS)return t(`Resync: offset=${te} bChunks=${O} chunk=`+JSON.stringify(_)),M();if(!(te>=O))return B(z-E.fragIndex,!1)}},F=(_,O,z)=>{u&&u.abort(),u=Qs(this.urlResolver.resolve(_,!0,this.lowLatency),O,z,()=>this._retryCallback()).withTimeout(Bs).withRetryCount(Ms).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(_,O)=>{F(T,z=>{if(!h())return;E=z;const te=!!E.lowLatency;te!==this.lowLatency&&g(te);let ne=0;for(let me=0;me<E.dur.length;++me)ne+=E.dur[me];ne>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ne/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,_(D(O))},()=>this._handleNetworkError())},nextChunk:I}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:P}=this.params;let N=v(e.jidxUrl),V,L,B,M,D=0,I,F,R;const _=()=>{I&&(clearTimeout(I),I=void 0);const q=Math.max(vS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=D+q,Re=we(),ve=Math.min(1e4,Ee-Re);D=Re;const ce=()=>{u||h()&&N.seek(()=>{h()&&(D=we(),O(),_())})};ve>0?I=window.setTimeout(()=>{this.paused?_():ce()},ve):ce()},O=()=>{let q;for(;q=N.nextChunk(M);)M=q,Ie(q);const Ee=N.nextChunk(B);if(Ee){if(B&&Ee.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?_():(y(),this._initPlayerWith(e));return}me(Ee)}else _()},z=(q,Ee)=>{if(!h()||!this.sourceBuffer)return;let Re,ve,ce;const Tt=Et=>{window.setTimeout(()=>{h()&&z(q,Ee)},Et)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),Tt(100);else{const Et=we(),Bt=E.currentTime;!this.paused&&E.buffered.length>1&&F===Bt&&Et-R>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),F!==Bt&&(F=Bt,R=Et);const $t=this._getBufferSizeSec();if($t>30)P(`Buffered ${$t} seconds; delaying appendBuffer`),Tt(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:Et,buf:$t}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(fi){if(fi.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),ce=this.sourceBuffer.buffered.length,ce!==0&&(Re=this.sourceBuffer.buffered.start(0),ve=Bt,ve-Re>4&&this.sourceBuffer.remove(Re,ve-3)),Tt(1e3);else throw fi}}},te=()=>{L&&V&&(P([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(B)]),z(L,function(){L=null,O()}))},ne=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),me=q=>{h()&&p(ne(q),(Ee,Re)=>{if(h()){if(Re/=1e3,L=Ee,B=q,o=q.startTS,Re){const ve=Math.min(10,q.dur/Re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}te()}},()=>this._handleNetworkError())},Ie=q=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ne(q),!1)))},Ge=q=>{h()&&(e.cachedHeader=q,z(q,()=>{V=!0,te()}))};n=!0,N.seek(q=>{if(h()){if(D=we(),!q){_();return}M=q,!a.isNullable(T)||q.startTS>T?me(q):(B=q,O())}},T),e.cachedHeader?Ge(e.cachedHeader):f(e.headerUrl,Ge,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const m=we();if(this.chunkRateEstimator.addInterval(f,m,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&ad(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=we();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=Qs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Bs).withRetryCount(Ms).withRetryInterval(cS,hS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Nt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},fS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var W;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const gS=[W.PAUSED,W.PLAYING,W.READY],SS=[W.PAUSED,W.PLAYING,W.READY];class yS{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(W.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ys,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Mi(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,g=Object.assign({},h.video);if(!p)continue;const S={id:f,quality:p,bitrate:m,size:g};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.MANIFEST_READY&&this.videoState.setState(W.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(W.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(SS.includes(r)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===Y.Requested&&gS.includes(r)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(r){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_READY),this.dash.attachSource(Pe(this.params.source.url));return;case W.MANIFEST_READY:this.videoState.startTransitionTo(W.READY),this.prepare();break;case W.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(W.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(W.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(W.PAUSED)})}return;case W.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case W.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(W.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(W.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.dash.reinit(Pe(this.params.source.url,h))}return;default:return a.assertNever(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=bt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=St(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(a.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===W.READY&&this.videoState.setState(W.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(W.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(Ht(this.video,this.params.desiredState.isLooped,t)).add(vt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Lt(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const n=r&&a.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var n;switch(r.to){case W.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.MANIFEST_READY:case W.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case W.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),gt(this.video)}createLiveDashPlayer(){const e=new bS({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:hi(l.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=c==null?void 0:c.id,f=this.params.desiredState.videoTrack.getTransition(),p=(n=this.params.desiredState.videoTrack.getState())===null||n===void 0?void 0:n.id,m=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(f||h!==p)&&this.setVideoTrack(c),m&&this.setAutoQuality(u),f||m||h!==p){const g=(o=l.find(({track:S})=>S.id===h))===null||o===void 0?void 0:o.representation;a.assertNonNullable(g,"Representations missing"),this.dash.startPlay(g,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;a.assertNonNullable(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===W.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Pe(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}}var Fn=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Le=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,n=i.end(s)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const TS=i=>{const e=document.createElement("a");return e.href=i,e.origin},ES=i=>{const e=document.createElement("a");return e.href=i,e.host};class nd{constructor(e,t=[],s,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,n,o,l,d,u;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=ni(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace(ES(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class tr{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=g=>{r(tr._str2ua(g.substr(d))),d=g.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=Ut(m)),this._lastXhr=new nd(m,e.failoverHosts,g=>{this._lastXhr=void 0,p(g);const S=Date.now()-u;this._params.onBandwidthChange({size:g.length,duration:S,speed:8*g.length/(S/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),n==null||n()},g=>{if(g.length-d>l&&p(g),h===0){h=Date.now();return}f=g.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=g.length,h=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},o,(g,S,v)=>this._params.onError(g,S,v))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=tr._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class $S{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},r=t.exec(e),n=(r==null?void 0:r[1])==="-"?-1:1,o={years:s(r==null?void 0:r[2],n),months:s(r==null?void 0:r[3],n),weeks:s(r==null?void 0:r[4],n),days:s(r==null?void 0:r[5],n),hours:s(r==null?void 0:r[6],n),minutes:s(r==null?void 0:r[7],n),seconds:s(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Ut(s)),new nd(s,t,r=>{this.attachManifest(r,t,TS(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,m,g,S,v,y,b,T,E,P,N,V,L,B,M,D;const I=u.getElementsByTagName("SegmentBase")[0],F=I&&o(I,"indexRange").split("-"),R=I&&I.getElementsByTagName("Initialization")[0],_=R&&o(R,"range").split("-");if(!_||!F){const Ie=u.parentElement;if((Ie==null?void 0:Ie.getAttribute("contentType"))==="text"){const Ge=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,q=(s?s+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),Ee=(g=Ie.getAttribute("lang"))!==null&&g!==void 0?g:void 0;q&&d.push({id:Ge,url:q,language:Ee})}return}const O=.1,z=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),te=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ne;const me=(y=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&y!==void 0?y:void 0;ne=me?kr(me):void 0,l.push({width:Number((b=u.attributes.getNamedItem("width"))===null||b===void 0?void 0:b.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:z,baseURL:te,failoverHosts:t,indexFrom:Number(F[0]),indexTo:Number(F[1]),initFrom:Number(_[0]),initTo:Number(_[1]),codecs:(P=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&P!==void 0?P:void 0,mimeType:(V=(N=u.attributes.getNamedItem("mimeType"))===null||N===void 0?void 0:N.value)!==null&&V!==void 0?V:void 0,fps:ne,bufferSize:O*z/8,bufferLength:O,name:(B=(L=u.attributes.getNamedItem("okQuality"))===null||L===void 0?void 0:L.value)!==null&&B!==void 0?B:void 0,id:(D=(M=u.attributes.getNamedItem("id"))===null||M===void 0?void 0:M.value)!==null&&D!==void 0?D:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),m=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,d=m}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new tr({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||l(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<s.to+n){const o=this._findRef(r.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<s.length;n++){const o=s[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=s[s.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var K;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(K||(K={}));const kS=[K.PAUSED,K.PLAYING];class AS{constructor(e){this.videoState=new ee(K.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,n,o;const l=[];for(const d of t){const u=(n=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Mi(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(s==null?void 0:s.length)>0){const d=[];for(const u of s){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(K.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:n})=>n===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!s)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===Y.Requested&&kS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case K.STOPPED:this.videoState.startTransitionTo(K.MANIFEST_LOADED),this.prepare();return;case K.MANIFEST_LOADED:this.videoState.startTransitionTo(K.INITIAL_REPRESENTATION_SELECTED);return;case K.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(K.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case K.METADATA_LOADED:this.videoState.startTransitionTo(K.READY),this.dash.updateRefsForCurrentTime();return;case K.READY:r===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=bt(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ug(this.video),this.dash=new $S({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=St(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==Y.Applying)&&(this.videoState.getState()===K.PLAYING||this.videoState.getState()===K.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ht(this.video,t.isLooped,s)),this.subscription.add(vt(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Lt(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(a.map(l=>l.map(({track:d})=>d)))}),o(us(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(K.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u,c;const h=this.currentRepresentation$.getValue(),f=this.representations$.getValue(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=(l=this.params.desiredState.videoTrack.getState())===null||l===void 0?void 0:l.id,g=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),v=r();p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to);let y;if(!v&&a.isNonNullable(m))y=m;else{const b=Le(this.video.buffered,this.video.currentTime*1e3),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(b/T,1);y=(u=hi(f.map(({track:N})=>N),{container:S,throughput:g,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(d=f.find(({representation:N})=>N===h))===null||d===void 0?void 0:d.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||u===void 0?void 0:u.id;const P=t.autoVideoTrackLimits.getTransition();P&&e.autoVideoTrackLimits$.next(P.to)}return a.isNonNullable(y)?(c=f.find(({track:b})=>b.id===y))===null||c===void 0?void 0:c.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,s)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===K.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(K.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?l.height<=d.height:l===d)).subscribe(l=>{const d=Le(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(_e(l.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Fn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var ir;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ir||(ir={}));var qe;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(qe||(qe={}));var J;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(J||(J={}));var Ii;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ii||(Ii={}));var sr;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(sr||(sr={}));var le;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(le||(le={}));class fl{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,n=s.length;r<n;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,n=s.length;r<n;r++){const o=s[r];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class od extends fl{constructor(){super(),this.listeners||fl.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let ld=class{constructor(){Object.defineProperty(this,"signal",{value:new od,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ld.prototype[Symbol.toStringTag]="AbortController",od.prototype[Symbol.toStringTag]="AbortSignal");function ud(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function wS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!ud({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ar=ud({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),dd=Ar?wS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,li=Ar?dd.fetch:window.fetch;Ar?dd.Request:window.Request;const Qe=Ar?ld:window.AbortController;var Ri=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const PS=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},_S=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",rr=_S?PS:window.requestIdleCallback;var Ta,Ea;const DS=16;let cd=!1;try{cd=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Ea=(Ta=navigator.userAgent.match(/Version\/(\d+)/))===null||Ta===void 0?void 0:Ta[1])!==null&&Ea!==void 0?Ea:"",10)<=DS}catch(i){console.error(i)}let IS=class{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return H(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return H(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return H(this,void 0,void 0,function*(){return new Promise(t=>{let s;cd&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}};var ar=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};let yt=class{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}},hd=class extends yt{},RS=class extends yt{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}},CS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},xS=class extends yt{constructor(e){super(e),this.data=this.content}},Es=class extends yt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},LS=class extends Es{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}},NS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},OS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}};var ri;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(ri||(ri={}));let BS=class extends Es{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=ri.MONOSCOPIC;break;case 1:this.stereoMode=ri.TOP_BOTTOM;break;case 2:this.stereoMode=ri.LEFT_RIGHT;break;case 3:this.stereoMode=ri.STEREO_CUSTOM;break;case 4:this.stereoMode=ri.RIGHT_LEFT;break}this.cursor+=1}},MS=class extends Es{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},VS=class extends Es{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},FS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},US=class extends Es{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()}},jS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},HS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}};const GS={ftyp:RS,moov:CS,mdat:xS,sidx:LS,trak:NS,mdia:FS,tkhd:US,minf:jS,sv3d:OS,st3d:BS,prhd:MS,proj:HS,equi:VS,unknown:hd};let YS=class{createBox(e,t){const s=GS[e];return s?new s(t):new hd(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return wr.createBox(s,new DataView(e.buffer,e.byteOffset))}};const wr=new YS;function is(i,e){const t=new TextDecoder("ascii");let s=i.byteOffset,r=[];for(;s<i.byteLength;){const n=t.decode(new DataView(i.buffer,s,1));if(n===e[r.length]?r.push(n):r=[],r.length===4&&r.join("")===e){const l=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+l>i.byteLength?null:wr.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function zS(i,e){const t=[];let s=0;for(;s<i.byteLength;){const r=is(new DataView(i.buffer,i.byteOffset+s,i.byteLength-s),e);if(r)t.push(r),s+=r.size+r.source.byteOffset;else break}return t}function Vi(i){const e=[];let t=0;for(;t<i.byteLength;){const s=wr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const qS=new TextDecoder("ascii"),WS=i=>qS.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",QS=i=>{const e=wr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:J.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},KS=i=>{const e=zS(i,"mdat");if(e.length){const t=e.reduce((s,r)=>s+r.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},JS=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(is(i,"sv3d")){e.is3dVideo=!0;const s=is(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=is(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=is(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},XS={validateData:WS,parseInit:JS,getIndexRange:()=>{},parseSegments:QS,parseFeedableSegmentChunk:KS};var $;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})($||($={}));var C;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(C||(C={}));const pl={[$.EBML]:{type:C.Master},[$.EBMLVersion]:{type:C.UnsignedInteger},[$.EBMLReadVersion]:{type:C.UnsignedInteger},[$.EBMLMaxIDLength]:{type:C.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[$.DocType]:{type:C.String},[$.DocTypeVersion]:{type:C.UnsignedInteger},[$.DocTypeReadVersion]:{type:C.UnsignedInteger},[$.Void]:{type:C.Binary},[$.Segment]:{type:C.Master},[$.SeekHead]:{type:C.Master},[$.Seek]:{type:C.Master},[$.SeekID]:{type:C.Binary},[$.SeekPosition]:{type:C.UnsignedInteger},[$.Info]:{type:C.Master},[$.TimestampScale]:{type:C.UnsignedInteger},[$.Duration]:{type:C.Float},[$.Tracks]:{type:C.Master},[$.TrackEntry]:{type:C.Master},[$.Video]:{type:C.Master},[$.Projection]:{type:C.Master},[$.ProjectionType]:{type:C.UnsignedInteger},[$.ProjectionPrivate]:{type:C.Master},[$.Chapters]:{type:C.Master},[$.Cluster]:{type:C.Master},[$.Timestamp]:{type:C.UnsignedInteger},[$.SilentTracks]:{type:C.Master},[$.SilentTrackNumber]:{type:C.UnsignedInteger},[$.Position]:{type:C.UnsignedInteger},[$.PrevSize]:{type:C.UnsignedInteger},[$.SimpleBlock]:{type:C.Binary},[$.BlockGroup]:{type:C.Master},[$.EncryptedBlock]:{type:C.Binary},[$.Attachments]:{type:C.Master},[$.Tags]:{type:C.Master},[$.Cues]:{type:C.Master},[$.CuePoint]:{type:C.Master},[$.CueTime]:{type:C.UnsignedInteger},[$.CueTrackPositions]:{type:C.Master},[$.CueTrack]:{type:C.UnsignedInteger},[$.CueClusterPosition]:{type:C.UnsignedInteger},[$.CueRelativePosition]:{type:C.UnsignedInteger},[$.CueDuration]:{type:C.UnsignedInteger},[$.CueBlockNumber]:{type:C.UnsignedInteger},[$.CueCodecState]:{type:C.UnsignedInteger},[$.CueReference]:{type:C.Master},[$.CueRefTime]:{type:C.UnsignedInteger}},fd=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=nr(i,t),r=s in pl,n=r?pl[s].type:C.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=nr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},nr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ht=(i,e)=>{switch(e){case C.SignedInteger:return i.getInt8(0);case C.UnsignedInteger:return nr(i);case C.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(i);case C.UTF8:return new TextDecoder("utf-8").decode(i);case C.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case C.Master:return i;case C.Binary:return i;default:a.assertNever(e)}},Ci=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=fd(s);if(!e(r))return;r.type===C.Master&&Ci(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},ZS=i=>{if(i.getUint32(0)!==$.EBML)return!1;let e,t,s;const r=fd(i);return Ci(r.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=ht(l,o):n===$.DocType?t=ht(l,o):n===$.DocTypeReadVersion&&(s=ht(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},pd=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],ey=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],ty=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Ci(i,({tag:f,type:p,value:m,valueSize:g})=>{if(f===$.SeekID){const S=ht(m,p);u=nr(S)}else f!==$.SeekPosition&&(u=void 0);return f===$.Segment?(e=m.byteOffset,t=m.byteOffset+g):f===$.Info?n=!0:f===$.SeekHead?o=!0:f===$.TimestampScale?s=ht(m,p):f===$.Duration?r=ht(m,p):f===$.SeekPosition&&u===$.Cues?d=ht(m,p):f===$.Tracks?Ci(m,({tag:S,type:v,value:y})=>S===$.ProjectionType?(c=ht(y,v)===1,!1):!0):n&&o&&pd.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},iy=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},sy=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Ci(i,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&r(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=ht(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=ht(u,d));break;default:t&&pd.includes(l)&&(s=!0)}return!(t&&s)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:J.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},ry=i=>{let e=0,t=!1;try{Ci(i,s=>s.tag===$.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):ey.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},ay={validateData:ZS,parseInit:ty,getIndexRange:iy,parseSegments:sy,parseFeedableSegmentChunk:ry},md=1e4,ny=3e4,oy=5e3,ly=md,uy=({id:i,width:e,height:t,bitrate:s,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:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},dy=({id:i,bitrate:e})=>({id:i,bitrate:e}),cy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=ge(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:ge(i,-1)},hy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Vs=i=>{const e=[];let t=0,s=i.length-1;for(;t<md&&s>=0;)e.unshift(i[s]),t+=i[s].time.to-i[s].time.from,s--;return e};let ml=class{constructor(e,t,s,r,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.isSeekingLive=!1,this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Qe,this.destroyAbortController=new Qe,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(c){return Z(this,arguments,function*(){const h=this.representations.get(c);a.assertNonNullable(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new IS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),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(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield A(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(a.assertNonNullable(f,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield A(void 0);this.searchGaps(p,h),yield yield A(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(c){return Z(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield A(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);a.assertNonNullable(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(a.isNullable(p)||a.isNullable(f)?yield yield A(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield A(p)),f=this.segments.get(c),a.assertNonNullable(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield A(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield A(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.searchGaps(f,h),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(c){return Z(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield A(void 0);for(const S of this.representations.keys()){const v=c.find(T=>T.id===S);v&&this.representations.set(S,v);const y=this.representations.get(S);if(!y)return yield A(void 0);const b=Vs(y.segmentReference.segments);this.segments.set(y.id,b)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,f=this.representations.get(h);a.assertNonNullable(f);const p=Vs(f.segmentReference.segments),m=this.initData.get(f.id);if(a.assertNonNullable(m,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(m instanceof ArrayBuffer))return yield A(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield A(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(p,f),yield yield A(this.sourceBufferTaskQueue.append(m,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isLive=!!(u!=null&&u.dynamic),this.container=s,s){case Ii.MP4:this.containerParser=XS;break;case Ii.WEBM:this.containerParser=ay;break;default:a.assertNever(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Qe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Le(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Le(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=ge(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===J.FED&&!l.length&&Le(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=ge(s,-1);d&&d.status===J.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let s=0;for(const r of e)r.time.from-s>0&&this.gaps.push({representation:t.id,from:s,to:r.time.from}),s=r.time.to;a.isNonNullable(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o)return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:J.NONE,size:void 0})),d=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(r=ge(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.round(u)>=Math.round(h.time.from)&&Math.round(u)<=Math.round(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=Vs(l);this.segments.set(o.id,[...h])}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const g=f<=s&&p>=s,S=f>s||g||m===0&&s===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+v||p<=s+v;return(h===J.NONE||h===J.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!Ri(this.sourceBuffer.buffered,s))&&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===J.NONE||f.status===J.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,s="auto"){return H(this,void 0,void 0,function*(){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case qe.BYTE_RANGE:{r=t.segmentReference.url,n={from:ge(e,0).byte.from,to:ge(e,-1).byte.to};break}case qe.TEMPLATE:{const u=ge(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=J.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Z(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield A(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,u=>{if(u.name!=="AbortError"){for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)}})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=Le((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=J.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const m of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])m.status===J.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=J.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===qe.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const S=p?f.byte.from-s:0,v=p?f.byte.to-s:e.byteLength,y=S<r,b=v<=r;if(f.status===J.DOWNLOADING&&y&&b){f.status=J.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(m,r-S),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===m?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=J.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(P=>{if(n.aborted)o();else if(P)h.fedBytes+=E.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===J.PARTIALLY_FED||e.status===J.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=J.NONE),e.status=J.PARTIALLY_EJECTED):e.status=J.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=rr(()=>Ss(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return H(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Z(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield A(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>H(this,void 0,void 0,function*(){if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,this.isLive?Vs(c):c),d&&this.parsedInitData.set(e.id,d)})).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,s=!1){return H(this,void 0,void 0,function*(){if(!this.sourceBuffer||!this.playingRepresentationId||a.isNullable(e)||this.sourceBuffer.updating)return!1;let r=0,n=1/0,o=-1/0,l=!1;const d=u=>{var c;n=Math.min(n,u.time.from),o=Math.max(o,u.time.to);const h="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;r+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===J.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===J.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===J.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===J.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:n})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:n}=r;if(n!==J.FED&&n!==J.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=J.PARTIALLY_EJECTED:r.status=J.NONE)}}};var Pi;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Pi||(Pi={}));let fy=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Qe,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 A(li(n,{signal:this.abortAllController.signal}).catch(Xi));return o?(this.onHeadersReceived(o.headers),yield A(o.text())):yield A(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(r,{rangeMethod:n=this.compatibilityMode?Pi.HEADER:Pi.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return Z(this,arguments,function*(){let g=r;const S=new Headers;if(o)switch(n){case Pi.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case Pi.PARAM:{const O=new URL(g,location.href);O.searchParams.append("bytes",`${o.from}-${o.to}`),g=O.toString();break}default:a.assertNever(n)}this.requestQuic&&(g=Ut(g));let v=this.abortAllController.signal,y;if(u){const O=new Qe;if(y=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{O.abort()}catch(z){Xi(z)}}),this.abortAllController.signal.aborted||u.aborted)try{O.abort()}catch(z){Xi(z)}v=O.signal}const b=a.now(),T=yield yield A(li(g,{priority:d,headers:S,signal:v}).catch(Xi)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-b),!T)return y==null||y.unsubscribe(),yield A(null);if(!T.ok||!T.body)return y==null||y.unsubscribe(),yield A(Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`)));this.onHeadersReceived(T.headers);const P=parseInt((f=T.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!P){const O=yield yield A(T.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(O.byteLength,a.now()-E),l==null||l(new DataView(O),O.byteLength),y==null||y.unsubscribe(),yield A(O)}if(!l&&!c)return y==null||y.unsubscribe(),yield A(T.arrayBuffer());const[N,V]=T.body.tee(),L=N.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(V));let B=0;const M=new ArrayBuffer(P),D=new Uint8Array(M),I=new DataView(M);let F=!1;const R=O=>{y==null||y.unsubscribe(),F=!0,Xi(O)},_=a.abortable(v,function({done:O,value:z}){return Z(this,arguments,function*(){if(B===0&&this.lastRequestFirstBytes$.next(a.now()-b),v.aborted)return y==null||y.unsubscribe(),yield A(void 0);!O&&z&&(D.set(z,B),B+=z.byteLength,l==null||l(I,B),yield yield A(L==null?void 0:L.read().then(_,R)))})}.bind(this));return yield yield A(L==null?void 0:L.read().then(_,R)),y==null||y.unsubscribe(),yield A(F?null:M)})}.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 A(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 g=yield yield A(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!g)return yield A(null);const S=new DataView(g,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const v=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let b;if(f)b=new DataView(g,y.from-c,y.to-y.from+1);else{const E=yield yield A(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!E)return yield A(null);b=new DataView(E)}const T=n.parseSegments(b,v,y);return yield A({init:v,dataView:new DataView(g),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 A(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield A(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield A(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:J.NONE,size:void 0}));return yield A({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Fn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,n;return H(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case qe.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case qe.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const Xi=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var py=Ct,my=cs,vy=De,by=vy("match"),gy=function(i){var e;return py(i)&&((e=i[by])!==void 0?!!e:my(i)=="RegExp")},Sy=vs,yy=String,Ty=function(i){if(Sy(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return yy(i)},Ey=xt,$y=function(){var i=Ey(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},ky=He,Ay=mt,wy=mr,Py=$y,vl=RegExp.prototype,_y=function(i){var e=i.flags;return e===void 0&&!("flags"in vl)&&!Ay(i,"flags")&&wy(vl,i)?ky(Py,i):e},Un=Je,Dy=Sr,Iy=Math.floor,$a=Un("".charAt),Ry=Un("".replace),ka=Un("".slice),Cy=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,xy=/\$([$&'`]|\d{1,2})/g,Ly=function(i,e,t,s,r,n){var o=t+i.length,l=s.length,d=xy;return r!==void 0&&(r=Dy(r),d=Cy),Ry(n,d,function(u,c){var h;switch($a(c,0)){case"$":return"$";case"&":return i;case"`":return ka(e,0,t);case"'":return ka(e,o);case"<":h=r[ka(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Iy(f/10);return p===0?u:p<=l?s[p-1]===void 0?$a(c,1):s[p-1]+$a(c,1):u}h=s[f-1]}return h===void 0?"":h})},Ny=at,Oy=He,jn=Je,bl=mn,By=pe,My=hs,Vy=gy,yi=Ty,Fy=gr,Uy=_y,jy=Ly,Hy=De,Gy=Hy("replace"),Yy=TypeError,vd=jn("".indexOf),zy=jn("".replace),gl=jn("".slice),qy=Math.max,Sl=function(i,e,t){return t>i.length?-1:e===""?t:vd(i,e,t)};Ny({target:"String",proto:!0},{replaceAll:function(e,t){var s=bl(this),r,n,o,l,d,u,c,h,f,p=0,m=0,g="";if(!My(e)){if(r=Vy(e),r&&(n=yi(bl(Uy(e))),!~vd(n,"g")))throw Yy("`.replaceAll` does not allow non-global regexes");if(o=Fy(e,Gy),o)return Oy(o,e,s,t);if(r)return zy(yi(s),e,t)}for(l=yi(s),d=yi(e),u=By(t),u||(t=yi(t)),c=d.length,h=qy(1,c),p=Sl(l,d,0);p!==-1;)f=u?yi(t(d,p,l)):jy(d,l,p,[],void 0,t),g+=gl(l,m,p)+f,m=p+c,p=Sl(l,d,p+h);return m<l.length&&(g+=gl(l,m)),g}});var Wy=Bn,Qy=Wy("String","replaceAll"),Ky=Qy,Jy=Ky,Xy=Jy,Zy=Xy,or=fr(Zy);const yl=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Aa=(i,e)=>{let t=i;t=or(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(s)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},e0=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,p,m,g,S,v,y,b,T,E,P,N,V,L,B,M,D,I,F,R,_,O,z,te,ne,me,Ie,Ge,q;const Re=new DOMParser().parseFromString(i,"application/xml"),ve={video:[],audio:[],text:[]},ce=Re.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 $e;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)$e=yl(Fi);else if(Ui){const oe=yl(Ui);a.isNonNullable(oe)&&($e=oe)}else ji&&($e=parseInt(ji,10));let _r=0;const zt=(s=(t=ce.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Dr=zt.includes(ir.WEBM_AS_IN_FFMPEG)||zt.includes(ir.WEBM_AS_IN_SPEC)?Ii.WEBM:Ii.MP4;for(const oe of Et){const kt=oe.getAttribute("mimeType"),Ir=oe.getAttribute("codecs"),Hi=(r=oe.getAttribute("contentType"))!==null&&r!==void 0?r:kt==null?void 0:kt.split("/")[0],Rr=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gi=oe.querySelectorAll("Representation"),Cr=oe.querySelector("SegmentTemplate");if(Hi===Se.TEXT){for(const U of Gi){const be=U.getAttribute("id")||"",At=oe.getAttribute("lang"),Ne=(u=(d=(l=U.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(Ne,e).toString(),Wt=be.includes("_auto");ve[Se.TEXT].push({id:be,lang:At,isAuto:Wt,kind:Se.TEXT,url:qt})}continue}for(const U of Gi){const be=(c=U.getAttribute("mimeType"))!==null&&c!==void 0?c:kt,At=(f=(h=U.getAttribute("codecs"))!==null&&h!==void 0?h:Ir)!==null&&f!==void 0?f:"",Ne=(m=(p=U.getAttribute("contentType"))!==null&&p!==void 0?p:be==null?void 0:be.split("/")[0])!==null&&m!==void 0?m:Hi,qt=(S=(g=oe.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&S!==void 0?S:[],Wt=parseInt((v=U.getAttribute("width"))!==null&&v!==void 0?v:"",10),Yi=parseInt((y=U.getAttribute("height"))!==null&&y!==void 0?y:"",10),zi=parseInt((b=U.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,qi=(T=U.getAttribute("frameRate"))!==null&&T!==void 0?T:"",xr=(E=U.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Lr=qi?kr(qi):void 0,Nr=(P=U.getAttribute("id"))!==null&&P!==void 0?P:(_r++).toString(10),Or=Ne==="video"?`${Yi}p`:Ne==="audio"?`${zi}Kbps`:At,Br=`${Nr}@${Or}`,Mr=(L=(V=(N=U.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||V===void 0?void 0:V.trim())!==null&&L!==void 0?L:"",Wi=new URL(Mr,e).toString(),Vr=[...zt,...Rr,...qt];let Qt;const Fr=U.querySelector("SegmentBase"),ke=(B=U.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Cr;if(Fr){const Oe=(D=(M=U.querySelector("SegmentBase Initialization"))===null||M===void 0?void 0:M.getAttribute("range"))!==null&&D!==void 0?D:"",[Be,Jt]=Oe.split("-").map(Me=>parseInt(Me,10)),Ce={from:Be,to:Jt},Ze=(I=U.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Xt,wt]=Ze?Ze.split("-").map(Me=>parseInt(Me,10)):[],et=Ze?{from:Xt,to:wt}:void 0;Qt={type:qe.BYTE_RANGE,url:Wi,initRange:Ce,indexRange:et}}else if(ke){const Oe={representationId:(F=U.getAttribute("id"))!==null&&F!==void 0?F:void 0,bandwidth:(R=U.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Be=parseInt((_=ke.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Jt=(O=ke.getAttribute("initialization"))!==null&&O!==void 0?O:"",Ce=ke.getAttribute("media"),Ze=(te=parseInt((z=ke.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&te!==void 0?te:1,Xt=Aa(Jt,Oe);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");const wt=(ne=ke.querySelectorAll("SegmentTimeline S"))!==null&&ne!==void 0?ne:[],et=[];let Me=0;if(wt.length){let Zt=Ze,Ve=0;for(const ei of wt){const Fe=parseInt((me=ei.getAttribute("d"))!==null&&me!==void 0?me:"",10),he=parseInt((Ie=ei.getAttribute("r"))!==null&&Ie!==void 0?Ie:"",10)||0,tt=parseInt((Ge=ei.getAttribute("t"))!==null&&Ge!==void 0?Ge:"",10);Ve=Number.isFinite(tt)?tt:Ve;const xe=Fe/Be*1e3,ot=Ve/Be*1e3;for(let Pt=0;Pt<he+1;Pt++){const Qi=Aa(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:Zt.toString(10),segmentTime:(Ve+Pt*Fe).toString(10)})),pi=(ot||0)+Pt*xe,mi=pi+xe;Zt++,et.push({time:{from:pi,to:mi},url:Qi})}Ve+=(he+1)*Fe,Me+=(he+1)*xe}}else if(a.isNonNullable($e)){const Ve=parseInt((q=ke.getAttribute("duration"))!==null&&q!==void 0?q:"",10)/Be*1e3,ei=Math.ceil($e/Ve);let Fe=0;for(let he=1;he<ei;he++){const tt=Aa(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:he.toString(10),segmentTime:Fe.toString(10)}));et.push({time:{from:Fe,to:Fe+Ve},url:tt}),Fe+=Ve}}Qt={type:qe.TEMPLATE,baseUrl:Wi,initUrl:Xt,totalSegmentsDurationMs:Me,segments:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ne||!be)continue;const Kt={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[Ne];Kt&&ve[Kt].push({id:Br,kind:Kt,segmentReference:Qt,profiles:Vr,duration:$e,bitrate:zi,mime:be,codecs:At,width:Wt,height:Yi,fps:Lr,quality:xr})}}return{dynamic:Bt,liveAvailabilityStartTime:fi,duration:$e,container:Dr,representations:ve}},dn=1e3,Tl=["timeupdate","progress","play","seeked","stalled","waiting"];var Ye;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Ye||(Ye={}));let t0=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(Ye.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Qe,this.initManifest=a.abortable(this.destroyController.signal,function(t,s,r){var n;return Z(this,arguments,function*(){this.element=t,this.manifestUrlString=Pe(s,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ye.MANIFEST_READY),this.manifest=yield yield A(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Ye.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 s=yield yield A(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!s)return yield A(this.manifest);let r;try{r=e0(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return yield A(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===Se.TEXT)};return this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield A(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,s){return Z(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ye.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new ml(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new ml(Se.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(dn).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=Pe(this.manifestUrlString,u+1e3,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Tl.map(l=>a.fromEvent(this.element,l))).pipe(a.throttle(dn),a.map(l=>this.element?Le(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(d=>{var u,c;let h=0;if(d){const f=((c=(u=this.element)===null||u===void 0?void 0:u.currentTime)!==null&&c!==void 0?c:0)*1e3;h=Math.min(...this.bufferManagers.map(m=>{var g,S;return(S=(g=m.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.to)!==null&&S!==void 0?S:0}))-f}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(d=>H(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const u=this.element.playbackRate,c=er(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P),h=ny*u,f=ly*u,p=oy*u;l=d>l?d:l;const m=c===0&&d<p,g=c!==0&&d<h+p&&d>=h,S=c!==0&&d<h;if(S||g){const v=l-(h+f),y=Math.trunc(c+v/u);let b;d?y>0?b=y:b=0:b=c,this.manifestUrlString=Pe(this.manifestUrlString,b,ae.DASH_CMAF_OFFSET_P)}(m||S||g)&&(yield this.updateLive(),l=0)})))}const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield A(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield A(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield A(this.videoBufferManager.startWith(t)),this.state$.setState(Ye.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new fy({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,s,r,n;return H(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.manifestUrlString=Pe(this.manifestUrlString,e,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Ye.RUNNING),this.subscription.add(a.merge(...Tl.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.tick()}switchRepresentation(e,t){return H(this,void 0,void 0,function*(){const s={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),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(Ye.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}updateLive(){var e;return H(this,void 0,void 0,function*(){this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class i0{constructor(e,t){this.fov=e,this.orientation=t}}class s0{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var r0=`#define GLSLIFY 1
|
|
38
|
-
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,
|
|
37
|
+
`}),R}return u==null||u.recordSwitch(I),I};var _e=i=>new URL(i).hostname;const aS=300,us=(i,e=aS)=>new a.Observable(t=>{const{width:s,height:r}=i.getBoundingClientRect();if(t.next({width:s,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(Bd(o=>{const l=o[0];if(!l)return;let d,u;l.contentBoxSize&&l.contentBoxSize[0]?(u=l.contentBoxSize[0].blockSize,d=l.contentBoxSize[0].inlineSize):l.contentRect&&(d=l.contentRect.width,u=l.contentRect.height),a.isNonNullable(d)&&a.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(i),()=>n.disconnect()});class Ts{constructor(){this.onDroopedVideoFramesLimit$=new a.Subject,this.subscription=new a.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new a.Subject,this.isForceCheckCounter=0,this.prevTotalVideoFrames=0,this.prevDroppedVideoFrames=0,this.limitCounts={},this.handleChangeVideoQuality=()=>{const e=this.tracks.find(({size:t})=>(t==null?void 0:t.height)===this.video.videoHeight&&(t==null?void 0:t.width)===this.video.videoWidth);e&&!a.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,n=s-this.prevDroppedVideoFrames,o=1-(r-n)/r;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&a.isHigher(this.currentQuality,this.droppedFramesChecker.minQualityBanLimit)&&(this.limitCounts[this.currentQuality]=((e=this.limitCounts[this.currentQuality])!==null&&e!==void 0?e:0)+1,this.maxQualityLimit=this.getMaxQualityLimit(this.currentQuality),this.currentTimer&&window.clearTimeout(this.currentTimer),this.currentTimer=window.setTimeout(()=>this.maxQualityLimit=this.getMaxQualityLimit(),this.droppedFramesChecker.qualityUpWaitingTime),this.onDroopedVideoFramesLimitTrigger()),this.savePrevFrameCounts(t,s)}}connect(e){this.log=e.logger.createComponentLog("DroppedFramesManager"),this.video=e.video,this.isAuto=e.isAuto,this.droppedFramesChecker=e.droppedFramesChecker,this.subscription.add(e.playing$.subscribe(()=>this.playing=!0)),this.subscription.add(e.pause$.subscribe(()=>this.playing=!1)),this.subscription.add(e.tracks$.subscribe(t=>this.tracks=t)),this.isEnabled&&this.subscribe()}destroy(){this.currentTimer&&window.clearTimeout(this.currentTimer),this.subscription.unsubscribe()}get droppedVideoMaxQualityLimit(){return this.maxQualityLimit}subscribe(){this.subscription.add(a.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=a.interval(this.droppedFramesChecker.checkTime).pipe(a.filter(()=>this.playing),a.filter(()=>{const r=!!this.isForceCheckCounter;return r&&(this.isForceCheckCounter-=1),!r})),t=this.forceChecker$.pipe(a.debounce(this.droppedFramesChecker.checkTime)),s=a.merge(e,t);this.subscription.add(s.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:s}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,s),this.isForceCheckCounter=this.droppedFramesChecker.tickCountAfterQualityChange,this.forceChecker$.next()}onDroopedVideoFramesLimitTrigger(){this.isAuto.getState()&&(this.log({message:`[onDroopedVideoFramesLimit]. maxQualityLimit: ${this.maxQualityLimit}`}),this.onDroopedVideoFramesLimit$.next())}getMaxQualityLimit(e){var t,s;const r=(s=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>a.isLower(n,o)?-1:1))===null||t===void 0?void 0:t[0])===null||s===void 0?void 0:s[0];return e!=null?e:r}get isEnabled(){return this.droppedFramesChecker.enabled&&this.isDroppedFramesCheckerSupport}get isDroppedFramesCheckerSupport(){return!!this.video&&typeof this.video.getVideoPlaybackQuality=="function"}savePrevFrameCounts(e,t){this.prevTotalVideoFrames=e,this.prevDroppedVideoFrames=t}}const Ji={};var Q;(function(i){i.DOWNLOADING_LIB="downloading_lib",i.STOPPED="stopped",i.STREAM_INITIALIZED="stream_initialized",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(Q||(Q={}));const fe=(i,e)=>new a.Observable(t=>{const s=r=>t.next(r);return i.on(e,s),()=>i.off(e,s)});class dl{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(Q.DOWNLOADING_LIB),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.videoTracks$=new a.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new a.ValueSubject(void 0),this.maxSeekBackTime$=new a.ValueSubject(1/0),this.availableFrom$=new a.ValueSubject(void 0),this.elementSize$=new a.ValueSubject(void 0),this.liveOffset=new ys,this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===Q.DOWNLOADING_LIB||t===Q.STREAM_INITIALIZED))switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===Y.Requested&&t!==Q.STOPPED&&s!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),s){case exports.PlaybackState.STOPPED:{switch(t){case Q.STOPPED:break;case Q.PLAYING:case Q.PAUSED:case Q.READY:this.stop();break;default:a.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case Q.STOPPED:this.prepare();break;case Q.PLAYING:case Q.PAUSED:case Q.READY:break;default:a.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case Q.PLAYING:break;case Q.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case Q.READY:this.play();break;case Q.STOPPED:this.prepare();break;default:a.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case Q.PLAYING:this.pause(),this.liveOffset.pause();break;case Q.PAUSED:break;case Q.READY:this.videoState.setState(Q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Q.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(s)}},this.video=bt(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=r=>{var n;e||this.params.output.error$.next({id:r==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:a.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=r==null?void 0:r.toString)===null||n===void 0?void 0:n.call(r)}`,thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ss(import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(Ji.MediaPlayer=r.MediaPlayer,Ji.Debug=r.Debug,this.init())},t),()=>{window.clearTimeout(s),e=!0})}init(){a.assertNonNullable(Ji.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(Ji.Debug,"dashjs not loaded"),this.player=Ji.MediaPlayer().create(),this.player.updateSettings({debug:{logLevel:3},streaming:{buffer:{fastSwitchEnabled:!0},abr:{limitBitrateByPortal:this.params.tuning.autoTrackSelection.limitByContainer,usePixelRatioInLimitBitrateByPortal:this.params.tuning.autoTrackSelection.usePixelRatio,additionalAbrRules:{insufficientBufferRule:!1}},utcSynchronization:{useManifestDateHeaderTimeSource:!0}}}),this.player.registerCustomCapabilitiesFilter(e=>(e.height&&(this.frameRatesByFrameHeight[e.height]=e.frameRate?kr(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Og(this.player),xg(this.player),this.params.tuning.requestQuick&&Ng(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Q.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,s=b=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:b})},r=(b,T)=>this.subscription.add(b.subscribe(T,s));r(us(this.video),this.elementSize$),r(fe(this.player,"error").pipe(a.map(b=>{const T=typeof b.error=="object"?b.error.code:b.error,E=typeof b.error=="object"?b.error.message:void 0;return{id:`DashJS#${T}`,message:E}})),e.error$),r(fe(this.player,"playbackError").pipe(a.map(b=>({id:"DashJSPlayback",message:b.error}))),e.error$);const n=fe(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:b})=>b==="video"),a.map(({newQuality:b})=>{var T;return(T=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===b))===null||T===void 0?void 0:T.track}));n.pipe(a.filter(a.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(a.filter(({to:b})=>b===Q.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(rt(t.videoTrack,()=>{var b;const T=this.player.getQualityFor("video");return(b=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===T))===null||b===void 0?void 0:b.track},b=>{var T;if(a.isNullable(b))return;const E=(T=this.videoTracks$.getValue().find(({track:P})=>P.id===b.id))===null||T===void 0?void 0:T.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n,onError:s}))},s)),this.subscription.add(rt(t.autoVideoTrackSwitching,()=>{var b,T,E;return(E=(T=(b=this.player.getSettings().streaming)===null||b===void 0?void 0:b.abr)===null||T===void 0?void 0:T.autoSwitchBitrate)===null||E===void 0?void 0:E.video},b=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:b}}}}),{onError:s})),r(fe(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:b})=>b==="video"),a.map(({state:b})=>b==="bufferStalled")),e.isBuffering$),r(fe(this.player,"fragmentLoadingStarted"),({mediaType:b,request:{url:T}})=>{var E,P;const N=this.player.getDashMetrics(),V=N.getLatestFragmentRequestHeaderValueByID(b,"X-Reused"),L=(E=N.getLatestFragmentRequestHeaderValueByID(b,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,B=(P={1:!0,0:!1}[V])!==null&&P!==void 0?P:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(B),e.hostname$.next(_e(T))}),r(fe(this.player,"streamInitialized"),({streamInfo:{duration:b,manifestInfo:{isDynamic:T,availableFrom:E}}})=>{this.isLive$.next(T),this.availableFrom$.next(E.getTime()),T||e.duration$.next(b);const P=[],N=this.player.getQualityFor("video");let V;for(const L of this.player.getBitrateInfoListFor("video")){const B=L.qualityIndex.toString(10),M=a.videoSizeToQuality(L),D=L.bitrate/1e3,I={width:L.width,height:L.height},U=this.frameRatesByFrameHeight[L.height];if(M){const R={id:B,quality:M,bitrate:D,size:I,fps:U};P.push({track:R,bitrateInfo:L}),L.qualityIndex===N&&(V=R)}}this.videoTracks$.next(P),e.availableVideoTracks$.next(P.map(({track:L})=>L)),V&&e.currentVideoTrack$.next(V),this.videoState.setState(Q.STREAM_INITIALIZED),this.videoState.startTransitionTo(Q.READY)}),r(fe(this.player,"fragmentLoadingCompleted"),({request:b})=>{if(!b.requestEndDate||!b.firstByteDate||!b.bytesLoaded)return;const T=b.requestEndDate.getTime()-b.firstByteDate.getTime(),E=b.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(E,T)}),r(a.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const b=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=hi(this.videoTracks$.getValue().map(({track:N})=>N),{container:this.elementSize$.getValue(),throughput:b,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),E=t.autoVideoTrackLimits.getTransition();E&&e.autoVideoTrackLimits$.next(E.to);const P=this.videoTracks$.getValue().find(({track:N})=>N===T);P!=null&&P.bitrateInfo&&this.player.setQualityFor("video",P==null?void 0:P.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:b})=>b),a.map(({maxSeekBackTime:b})=>-b/1e3)),this.params.output.duration$);const o=fe(this.player,"playbackTimeUpdated").pipe(a.map(({time:b})=>b!=null?b:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:b,currentTime:T})=>this.params.output.liveTime$.next(b+T*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(fe(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(fe(this.player,"playbackEnded"),e.endedEvent$),r(fe(this.player,"playbackProgress").pipe(a.map(()=>sd(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(fe(this.player,"playbackPlaying"),()=>{this.videoState.setState(Q.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)}),r(fe(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Q.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(fe(this.player,"playbackPaused"),()=>{this.videoState.setState(Q.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)}),r(fe(this.player,"canPlay"),()=>{var b;((b=this.videoState.getTransition())===null||b===void 0?void 0:b.to)===Q.READY&&this.videoState.setState(Q.READY)}),r(this.isLive$,e.isLive$),r(us(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));r(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=Lg(this.player);r(c,this.params.output.httpConnectionType$),r(h,this.params.output.httpConnectionReused$),r(d,this.maxSeekBackTime$),r(u.pipe(a.once()),e.firstBytesEvent$),r(fe(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(b=>b<60))}),({isLive:b,isShort:T})=>{const E=!b&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),r(o.pipe(a.filter(b=>b>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(fe(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(fe(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,s))},s)),r(fe(this.player,"manifestLoaded"),b=>{var T,E,P,N,V,L,B;if(!((E=(T=b.data)===null||T===void 0?void 0:T.Period)===null||E===void 0)&&E.AdaptationSet){const M=[];for(const D of(N=(P=b.data)===null||P===void 0?void 0:P.Period)===null||N===void 0?void 0:N.AdaptationSet)if(D.contentType==="text"){const I=(V=D.Representation)===null||V===void 0?void 0:V.id,U=new URL((L=D.Representation)===null||L===void 0?void 0:L.BaseURL,(B=b.data)===null||B===void 0?void 0:B.baseUri).toString(),R="internal",_=D.lang;M.push({id:I,url:U,type:R,language:_})}t.internalTextTracks.startTransitionTo(M)}}),this.subscription.add(Ht(this.video,t.isLooped,s));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:g,inFullscreen$:S,pause$:v,playing$:y}=St(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:y,pause$:v,tracks$:this.videoTracks$.pipe(a.map(b=>b.map(({track:T})=>T)))}),this.subscription.add(vt(this.video,t.volume,f,s)),this.subscription.add(f.subscribe(e.volume$,s)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Lt(this.video,t.playbackRate,m,s)),this.subscription.add(g.subscribe(e.inPiP$)),this.subscription.add(S.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Q.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Q.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3);const r=Pe(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ae.PLAYBACK_SHIFT);this.player.attachSource(r)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(Q.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}gt(this.video),this.params.output.element$.next(void 0)}}var Mi=i=>{switch(i){case"mobile":return a.VideoQuality.Q_144P;case"lowest":return a.VideoQuality.Q_240P;case"low":return a.VideoQuality.Q_360P;case"sd":case"medium":return a.VideoQuality.Q_480P;case"hd":case"high":return a.VideoQuality.Q_720P;case"fullhd":case"full":return a.VideoQuality.Q_1080P;case"quadhd":case"quad":return a.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return a.VideoQuality.Q_2160P}};const cl=i=>{if(i instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(i.message))throw i;return!(i instanceof DOMException&&(i.code===20||i.name==="AbortError"))};var Nt=i=>F(void 0,void 0,void 0,function*(){const e=i.muted;try{yield i.play()}catch(t){if(!cl(t))return!1;if(e)return console.warn(t),!1;i.muted=!0;try{yield i.play()}catch(s){return cl(s)&&(i.muted=!1,console.warn(s)),!1}}return!0});function we(){return a.now()}function ad(i){return we()-i}function hl(i){const e=i.split("/"),t=e.slice(0,e.length-1).join("/"),s=/^([a-z]+:)?\/\//i,r=o=>s.test(o);return{resolve:(o,l,d=!1)=>{r(o)||(o.startsWith("/")||(o="/"+o),o=t+o);let u=o.indexOf("?")>-1?"&":"?";return d&&(o+=u+"lowLat=1",u="&"),l&&(o+=u+"_rnd="+Math.floor(999999999*Math.random())),o}}}function nS(i,e,t){const s=(...r)=>{t.apply(null,r),i.removeEventListener(e,s)};i.addEventListener(e,s)}function Qs(i,e,t,s){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,g=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const D=ad(c);let I;if(D<g){I=g-D,setTimeout(S,I);return}g*=2,g>m&&(g=m),o&&o.abort(),o=new r,P()};const v=D=>(n=D,M),y=D=>(h=D,M),b=()=>(p="json",M),T=()=>{if(!d){if(--u>=0){S(),s&&s();return}d=!0,h&&h(),t&&t()}},E=D=>(f=D,M),P=()=>{c=we(),o=new r,o.open("get",i);let D=0,I,U=0;const R=()=>(a.assertNonNullable(c),Math.max(c,Math.max(I||0,U||0)));if(n&&o.addEventListener("progress",_=>{const O=we();n.updateChunk&&_.loaded>D&&(n.updateChunk(R(),_.loaded-D),D=_.loaded,I=O)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const _=o.status;if(_>=200&&_<300){if(o.response.byteLength&&n){const O=o.response.byteLength-D;O&&n.updateChunk&&n.updateChunk(R(),O)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const _=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(U=we(),o.removeEventListener("readystatechange",_))};o.addEventListener("readystatechange",_)}return o.responseType=p,o.send(),M},M={withBitrateReporting:v,withParallel:E,withJSONResponse:b,withRetryCount:D=>(u=D,M),withRetryInterval:(D,I)=>(a.isNonNullable(D)&&(g=D),a.isNonNullable(I)&&(m=I),M),withTimeout:D=>(l=D,M),withFinally:y,send:P,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return M}const oS=100,lS=2e3,uS=500;let dS=class{constructor(e){this.intervals=[],this.currentRate=0,this.logger=e}_updateRate(e){let t=.2;this.currentRate&&(e<this.currentRate*.1?t=.8:e<this.currentRate*.5?t=.5:e<this.currentRate*.7&&(t=.3)),e=Math.max(1,Math.min(e,100*1024*1024)),this.currentRate=this.currentRate?this.currentRate*(1-t)+e*t:e}_createInterval(e,t,s){return{start:e,end:t,bytes:s}}_doMergeIntervals(e,t){e.start=Math.min(t.start,e.start),e.end=Math.max(t.end,e.end),e.bytes+=t.bytes}_mergeIntervals(e,t){return e.start<=t.end&&t.start<=e.end?(this._doMergeIntervals(e,t),!0):!1}_flushIntervals(){if(!this.intervals.length)return!1;const e=this.intervals[0].start,t=this.intervals[this.intervals.length-1].end-uS;if(t-e>lS){let s=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)s+=n.end-n.start,r+=n.bytes,this.intervals.splice(0,1);else{if(n.start>=t)break;{const o=t-n.start,l=n.end-n.start;s+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&s>0){const n=r*8/(s/1e3);return this._updateRate(n),this.logger(`rate updated, new=${Math.round(n/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(r)}/${Math.round(s)} interval=${Math.round(t-e)}`),!0}}return!1}_joinIntervals(){let e;do{e=!1;for(let t=0;t<this.intervals.length-1;++t)this._mergeIntervals(this.intervals[t],this.intervals[t+1])&&(this.intervals.splice(t+1,1),e=!0)}while(e)}addInterval(e,t,s){return this.intervals.push(this._createInterval(e,t,s)),this._joinIntervals(),this.intervals.length>oS&&(this.logger(`too many intervals (${this.intervals.length}); will merge`,{type:"warn"}),this._doMergeIntervals(this.intervals[1],this.intervals[0]),this.intervals.splice(0,1)),this._flushIntervals()}getBitRate(){return this.currentRate}};class cS{constructor(e,t,s,r,n){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=e,this.TIMEOUT=t,this.BITRATE_ESTIMATOR=s,this.MAX_PARALLEL_REQUESTS=r,this.logger=n}limitCompleteCount(){let e;for(;(e=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const t=e[Math.floor(Math.random()*e.length)];this.logger(`Dropping completed request for url ${t}`,{type:"warn"}),delete this.completeRequests[t]}}_sendRequest(e,t){const s=we(),r=d=>{delete this.activeRequests[t],this.limitCompleteCount(),this.completeRequests[t]=e,this._sendPending(),e._error=1,e._errorMsg=d,e._errorCB?e._errorCB(d):(this.limitCompleteCount(),this.completeRequests[t]=e)},n=d=>{e._complete=1,e._responseData=d,e._downloadTime=we()-s,delete this.activeRequests[t],this._sendPending(),e._cb?e._cb(d,e._downloadTime):(this.limitCompleteCount(),this.completeRequests[t]=e)},o=()=>{e._finallyCB&&e._finallyCB()},l=()=>{e._retry=1,e._retryCB&&e._retryCB()};e._request=Qs(t,n,()=>r("error"),l),e._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally(o),this.activeRequests[t]=e,e._request.send(),this.lastPrefetchStart=we()}_getParallelRequestCount(){return Math.min(this.MAX_PARALLEL_REQUESTS,this.averageSegmentDuration<3e3?3:2)}_getPrefetchDelay(){return Math.max(100,Math.min(5e3,this.averageSegmentDuration/3))}_canSendPending(){const e=this._getParallelRequestCount(),t=we();if(Object.keys(this.activeRequests).length>=e)return!1;const s=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),s>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),s),!1):!0}_sendPending(){for(;this._canSendPending();){const e=this.pendingQueue.pop();if(e){if(this.activeRequests[e]||this.completeRequests[e])continue;this.logger(`Submitting pending request url=${e}`),this._sendRequest({},e)}else return}}_removeFromActive(e){delete this.completeRequests[e],delete this.activeRequests[e]}abortAll(){Object.values(this.activeRequests).forEach(e=>{e&&e._request&&e._request.abort()}),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(e,t,s,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=s,o._retryCB=r,o._finallyCB=n._finallyCB,o._error||o._complete?(this._removeFromActive(e),setTimeout(()=>{o._complete?(this.logger(`Requested url already prefetched, url=${e}`),t(o._responseData,o._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${e}`),s(o._errorMsg)),n._finallyCB&&n._finallyCB()},0)):this.logger(`Attached to active request, url=${e}`);else{const l=this.pendingQueue.indexOf(e);l!==-1&&this.pendingQueue.splice(l,1),this.logger(`Request not prefetched, starting new request, url=${e}${l===-1?"":"; removed pending"}`),this._sendRequest(n,e)}},n._cb=t,n._errorCB=s,n._retryCB=r,n.abort=function(){n.request&&n.request.abort()},n.withFinally=o=>(n._finallyCB=o,n),n}prefetch(e){this.activeRequests[e]||this.completeRequests[e]?this.logger(`Request already active for url=${e}`):(this.logger(`Added to pending queue; url=${e}`),this.pendingQueue.unshift(e),this._sendPending())}optimizeForSegDuration(e){this.averageSegmentDuration=e}}const Bs=1e4,Ms=3,hS=300,fS=2e3,pS=6e4,mS=10,vS=1,bS=500;class gS{constructor(e){this.paused=!1,this.autoQuality=!0,this.maxAutoQuality=void 0,this.buffering=!0,this.destroyed=!1,this.videoPlayStarted=!1,this.lowLatency=!1,this.bitrate=0,this.manifest=[],this.sourceBuffer=0,this.bufferStates=[],this.sourceJitter=-1,this.params=e,this.chunkRateEstimator=new dS(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=hl(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let s=0;s<this.manifest.length;++s)if(t=this.manifest[s],t.name===e){this._switchToQuality(t);return}}catchUp(){this.rep&&this.rep.stop(),this.currentManifestEntry&&(this.paused=!1,this._initPlayerWith(this.currentManifestEntry),this._notifyBuffering(!0))}stop(){this.params.videoElement.pause(),this.rep&&(this.rep.stop(),this.rep=null)}pause(){this.paused=!0,this.params.videoElement.pause(),this.videoPlayStarted=!1,this._notifyBuffering(!1)}play(e){this.paused=!1;const t=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!t?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(e):this._notifyBuffering(!0)):this.catchUp()}startPlay(e,t){this.autoQuality=t,this._initPlayerWith(e)}destroy(){this.destroyed=!0,this.rep&&(this.rep.stop(),this.rep=null),this.manifestRequest&&this.manifestRequest.abort(),this.manifestRefetchTimer&&(clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=void 0)}reinit(e){this.manifestUrl=e,this.urlResolver=hl(e),this.catchUp()}_handleNetworkError(){this.params.logger("Fatal network error"),this.params.playerCallback({name:"error",type:"network"})}_retryCallback(){this.params.playerCallback({name:"retry"})}_getBufferSizeSec(){const e=this.params.videoElement;let t=0;const s=e.buffered.length;return s!==0&&(t=e.buffered.end(s-1)-Math.max(e.currentTime,e.buffered.start(0))),t}_notifyBuffering(e){this.destroyed||(this.params.logger(`buffering: ${e}`),this.params.playerCallback({name:"buffering",isBuffering:e}),this.buffering=e)}_initVideo(){const{videoElement:e,logger:t}=this.params;e.addEventListener("error",()=>{var s;!!e.error&&!this.destroyed&&(t(`Video element error: ${(s=e.error)===null||s===void 0?void 0:s.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const s=this._getBufferSizeSec();!this.paused&&s<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(s+.1)*1e3)):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)}),e.addEventListener("playing",()=>{t("playing")}),e.addEventListener("stalled",()=>this._fixupStall()),e.addEventListener("waiting",()=>this._fixupStall())}_fixupStall(){const{logger:e,videoElement:t}=this.params,s=t.buffered.length;let r;s!==0&&(r=t.buffered.start(s-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let s,r,n;const o=t&&1.62*(window.devicePixelRatio||1)*t.offsetHeight||520;for(let l=0;l<this.manifest.length;++l)n=this.manifest[l],!(this.maxAutoQuality&&n.video.height>this.maxAutoQuality)&&(n.bitrate<e&&o>Math.min(n.video.height,n.video.width)?(!r||n.bitrate>r.bitrate)&&(r=n):(!s||s.bitrate>n.bitrate)&&(s=n));return r||s}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||a.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:s,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,s("setting video src"),r.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,r.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{nS(r,"progress",()=>{r.buffered.length?(r.currentTime=r.buffered.start(0),n({name:"playing"})):o()})};o()}_initPlayerWith(e){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new cS(Ms,Bs,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:s,playerCallback:r}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const T=n&&(!c||c===this.rep);return T||t("Not running!"),T},f=(T,E,P)=>{d&&d.abort(),d=Qs(this.urlResolver.resolve(T,!1),E,P,()=>this._retryCallback()).withTimeout(Bs).withBitrateReporting(this.bitrateSwitcher).withRetryCount(Ms).withFinally(()=>{d=null}).send()},p=(T,E,P)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,P,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=T=>{const E=s.playbackRate;s.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),s.playbackRate=T)},g=T=>{this.lowLatency=T,t(`lowLatency changed to ${T}`),S()},S=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let T=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const P=we()-1e4;let N=0;for(let L=0;L<this.bufferStates.length;L++){const B=this.bufferStates[L];T=Math.min(T,B.buf),B.ts<P&&N++}this.bufferStates.splice(0,N),t(`update playback rate; minBuffer=${T} drop=${N} jitter=${this.sourceJitter}`);let V=T-vS;this.sourceJitter>=0?V-=this.sourceJitter/2:this.sourceJitter-=1,V>3?m(1.15):V>1?m(1.1):V>.3?m(1.05):m(1)}},v=T=>{let E;const P=()=>E&&E.start?E.start.length:0,N=_=>E.start[_]/1e3,V=_=>E.dur[_]/1e3,L=_=>E.fragIndex+_,B=(_,O)=>({chunkIdx:L(_),startTS:N(_),dur:V(_),discontinuity:O}),M=()=>{let _=0;if(E&&E.dur){let O=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,z=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,te=O;this.sourceJitter>1&&(te+=this.sourceJitter-1);let ne=E.dur.length-1;for(;ne>=0&&(te-=E.dur[ne],!(te<=0));--ne);_=Math.min(ne,E.dur.length-1-z),_=Math.max(_,0)}return B(_,!0)},D=_=>{const O=P();if(!(O<=0)){if(a.isNonNullable(_)){for(let z=0;z<O;z++)if(N(z)>_)return B(z)}return M()}},I=_=>{const O=P(),z=_?_.chunkIdx+1:0,te=z-E.fragIndex;if(!(O<=0)){if(!_||te<0||te-O>mS)return t(`Resync: offset=${te} bChunks=${O} chunk=`+JSON.stringify(_)),M();if(!(te>=O))return B(z-E.fragIndex,!1)}},U=(_,O,z)=>{u&&u.abort(),u=Qs(this.urlResolver.resolve(_,!0,this.lowLatency),O,z,()=>this._retryCallback()).withTimeout(Bs).withRetryCount(Ms).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(_,O)=>{U(T,z=>{if(!h())return;E=z;const te=!!E.lowLatency;te!==this.lowLatency&&g(te);let ne=0;for(let me=0;me<E.dur.length;++me)ne+=E.dur[me];ne>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ne/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,_(D(O))},()=>this._handleNetworkError())},nextChunk:I}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),a.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:T=>{const{videoElement:E,logger:P}=this.params;let N=v(e.jidxUrl),V,L,B,M,D=0,I,U,R;const _=()=>{I&&(clearTimeout(I),I=void 0);const q=Math.max(bS,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),Ee=D+q,Re=we(),ve=Math.min(1e4,Ee-Re);D=Re;const ce=()=>{u||h()&&N.seek(()=>{h()&&(D=we(),O(),_())})};ve>0?I=window.setTimeout(()=>{this.paused?_():ce()},ve):ce()},O=()=>{let q;for(;q=N.nextChunk(M);)M=q,Ie(q);const Ee=N.nextChunk(B);if(Ee){if(B&&Ee.discontinuity){P("Detected discontinuity; restarting playback"),this.paused?_():(y(),this._initPlayerWith(e));return}me(Ee)}else _()},z=(q,Ee)=>{if(!h()||!this.sourceBuffer)return;let Re,ve,ce;const Tt=Et=>{window.setTimeout(()=>{h()&&z(q,Ee)},Et)};if(this.sourceBuffer.updating)P("Source buffer is updating; delaying appendBuffer"),Tt(100);else{const Et=we(),Bt=E.currentTime;!this.paused&&E.buffered.length>1&&U===Bt&&Et-R>500&&(P("Stall suspected; trying to fix"),this._fixupStall()),U!==Bt&&(U=Bt,R=Et);const $t=this._getBufferSizeSec();if($t>30)P(`Buffered ${$t} seconds; delaying appendBuffer`),Tt(2e3);else try{this.sourceBuffer.appendBuffer(q),this.videoPlayStarted?(this.bufferStates.push({ts:Et,buf:$t}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),Ee&&Ee()}catch(fi){if(fi.name==="QuotaExceededError")P("QuotaExceededError; delaying appendBuffer"),ce=this.sourceBuffer.buffered.length,ce!==0&&(Re=this.sourceBuffer.buffered.start(0),ve=Bt,ve-Re>4&&this.sourceBuffer.remove(Re,ve-3)),Tt(1e3);else throw fi}}},te=()=>{L&&V&&(P([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(B)]),z(L,function(){L=null,O()}))},ne=q=>e.fragUrlTemplate.replace("%%id%%",q.chunkIdx),me=q=>{h()&&p(ne(q),(Ee,Re)=>{if(h()){if(Re/=1e3,L=Ee,B=q,o=q.startTS,Re){const ve=Math.min(10,q.dur/Re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ve:ve}te()}},()=>this._handleNetworkError())},Ie=q=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ne(q),!1)))},Ge=q=>{h()&&(e.cachedHeader=q,z(q,()=>{V=!0,te()}))};n=!0,N.seek(q=>{if(h()){if(D=we(),!q){_();return}M=q,!a.isNullable(T)||q.startTS>T?me(q):(B=q,O())}},T),e.cachedHeader?Ge(e.cachedHeader):f(e.headerUrl,Ge,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),a.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),t(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,a.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,s=h=>{if(!this.autoQuality)return;let f,p,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(p=this._getBufferSizeSec(),m=h/this.bitrate,p>10&&m>.8||p>15&&m>.5||p>20&&m>.3)){e(`Not switching: buffer=${Math.floor(p)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,p)=>{const m=we();if(this.chunkRateEstimator.addInterval(f,m,p)){const S=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:p,duration:m-f,speed:S}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&ad(o)<3e4)return;s(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=we();h<l&&(o=f),l=h}}}_fetchManifest(e,t,s){this.manifestRequest=Qs(this.urlResolver.resolve(e,!0),t,s,()=>this._retryCallback()).withJSONResponse().withTimeout(Bs).withRetryCount(Ms).withRetryInterval(hS,fS).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Nt(t).then(s=>{s||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:s,videoElement:r}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&r.canPlayType(d.codecs).replace(/no/,"")&&window.MediaSource.isTypeSupported(d.codecs)&&(d.index=u,l.push(d))}),l.sort(function(d,u){return d.video&&u.video?u.video.height-d.video.height:u.bitrate-d.bitrate}),l):(this.params.playerCallback({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),s({name:"manifest",manifest:this.manifest})}_refetchManifest(e){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout(()=>{this._fetchManifest(e,t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(e))},()=>this._refetchManifest(e))},pS))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var W;(function(i){i.STOPPED="stopped",i.MANIFEST_READY="manifest_ready",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(W||(W={}));const SS=[W.PAUSED,W.PLAYING,W.READY],yS=[W.PAUSED,W.PLAYING,W.READY];class TS{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(W.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new ys,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Mi(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,g=Object.assign({},h.video);if(!p)continue;const S={id:f,quality:p,bitrate:m,size:g};c.push({track:S,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.MANIFEST_READY&&this.videoState.setState(W.MANIFEST_READY);break}case"qualitySwitch":{const u=r.quality,c=(d=this.representations$.getValue().find(({representation:h})=>h===u))===null||d===void 0?void 0:d.track;this.params.output.hostname$.next(new URL(u.headerUrl,this.params.source.url).hostname),a.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=r;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(r.shiftDuration||0),this.zeroTime$.next(r.zeroTime);break}}},this.syncPlayback=()=>{const r=this.videoState.getState(),n=this.videoState.getTransition(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${r}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){r!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(W.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(yS.includes(r)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===Y.Requested&&SS.includes(r)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(r){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_READY),this.dash.attachSource(Pe(this.params.source.url));return;case W.MANIFEST_READY:this.videoState.startTransitionTo(W.READY),this.prepare();break;case W.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(W.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(W.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(W.PAUSED)})}return;case W.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(W.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case W.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(W.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(W.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.dash.reinit(Pe(this.params.source.url,h))}return;default:return a.assertNever(r)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=r=>{e.output.error$.next({id:"DashLiveProvider",category:a.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:r})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(r=>({transition:r,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(r=>({transition:r,type:"end"})))).subscribe(({transition:r,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(r)}`})}),this.video=bt(e.container),this.params.output.element$.next(this.video),this.dash=this.createLiveDashPlayer(),this.params.output.duration$.next(1/0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=St(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.representations$.pipe(a.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(s.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===W.READY&&this.videoState.setState(W.READY)},t)).add(s.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},t)).add(s.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===Y.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(W.PLAYING)},t)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(r=>-r/1e3)).subscribe(this.params.output.duration$)).add(a.combine({zeroTime:this.zeroTime$.pipe(a.filter(a.isNonNullable)),position:s.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(Ht(this.video,this.params.desiredState.isLooped,t)).add(vt(this.video,this.params.desiredState.volume,s.volumeState$,t)).add(s.volumeState$.subscribe(this.params.output.volume$,t)).add(Lt(this.video,this.params.desiredState.playbackRate,s.playbackRateState$,t)).add(s.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(s.playing$.subscribe(this.params.output.firstFrameEvent$)).add(s.canplay$.subscribe(this.params.output.canplay$)).add(s.inPiP$.subscribe(this.params.output.inPiP$)).add(s.inFullscreen$.subscribe(this.params.output.inFullscreen$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$.subscribe(({to:{max:r}})=>{const n=r&&a.videoQualityToHeight(r);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:r})})).add(this.videoState.stateChangeEnded$.subscribe(r=>{var n;switch(r.to){case W.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.MANIFEST_READY:case W.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case W.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(r.to)}},t)).add(a.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),gt(this.video)}createLiveDashPlayer(){const e=new gS({videoElement:this.video,config:{maxParallelRequests:this.params.config.maxParallelRequests,minBuffer:this.params.tuning.live.minBuffer,minBufferSegments:this.params.tuning.live.minBufferSegments,lowLatencyMinBuffer:this.params.tuning.live.lowLatencyMinBuffer,lowLatencyMinBufferSegments:this.params.tuning.live.lowLatencyMinBufferSegments,isLiveCatchUpMode:this.params.tuning.live.isLiveCatchUpMode},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:"LiveDashPlayer"})}});return e.pause(),e}prepare(){var e,t,s,r,n,o;const l=this.representations$.getValue(),d=(t=(e=this.params.desiredState.videoTrack.getTransition())===null||e===void 0?void 0:e.to)!==null&&t!==void 0?t:this.params.desiredState.videoTrack.getState(),u=(r=(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||s===void 0?void 0:s.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:hi(l.map(({track:g})=>g),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),h=c==null?void 0:c.id,f=this.params.desiredState.videoTrack.getTransition(),p=(n=this.params.desiredState.videoTrack.getState())===null||n===void 0?void 0:n.id,m=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(c&&(f||h!==p)&&this.setVideoTrack(c),m&&this.setAutoQuality(u),f||m||h!==p){const g=(o=l.find(({track:S})=>S.id===h))===null||o===void 0?void 0:o.representation;a.assertNonNullable(g,"Representations missing"),this.dash.startPlay(g,u)}}setVideoTrack(e){var t;const s=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;a.assertNonNullable(s,`No such representation ${e.id}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}setAutoQuality(e){this.dash.setAutoQualityEnabled(e),this.params.desiredState.autoVideoTrackSwitching.setState(e)}seek(e){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===W.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Pe(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}}var Fn=i=>{var e,t;const s=i.get("X-Delivery-Type"),r=i.get("X-Reused"),n=s===null?exports.HttpConnectionType.HTTP1:(e=s)!==null&&e!==void 0?e:void 0,o=r===null?void 0:(t={1:!0,0:!1}[r])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Le=(i,e)=>{let t=0;for(let s=0;s<i.length;s++){const r=i.start(s)*1e3,n=i.end(s)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const ES=i=>{const e=document.createElement("a");return e.href=i,e.origin},$S=i=>{const e=document.createElement("a");return e.href=i,e.host};class nd{constructor(e,t=[],s,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=s,this._progressCb=r,this._headersCb=n,this._errorCb=o,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open("GET",this._url,!0),this._xhr.overrideMimeType("text/plain; charset=x-user-defined");let e=!1;this._xhr.onreadystatechange=()=>{var t,s,r,n,o,l,d,u;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(s=this._errorCb)===null||s===void 0||s.call(this,`Http${(r=this._xhr)===null||r===void 0?void 0:r.status}`,`XHR response code ${(n=this._xhr)===null||n===void 0?void 0:n.status}`),this.abort();return}if(!(this._xhr.readyState===4&&this._xhr.status===0))try{if(this._xhr.readyState>=2&&!e){e=!0;const c=ni(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var s;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(s=this._errorCb)===null||s===void 0||s.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let r;this._failoverIndex>=this._failoverHosts.length?(r=this._url,this._failoverIndex=0):(r=this._url.replace($S(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",r,!0),this._xhr.send(null)}},500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class tr{constructor(e){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=e,this._mediaSource=e.mediaSource,this._sourceBuffer=e.sourceBuffer,this._onDashCallback=e.onDashCallback}_appendBuffer(e,t){try{this._isFull=!1,(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(e),t==null||t()}catch(s){if(s.name==="QuotaExceededError"){this._isFull=!0;const r=this._sourceBuffer.buffered;let n=0;for(let o=0,l=r.length;o<l;o++)n+=r.end(o)-r.start(o);n&&(this._maxBufferDuration=Math.round(n))}else throw this._params.onError("AppendBuffer","Unknown Buffer error",s),s}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,s,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=g=>{r(tr._str2ua(g.substr(d))),d=g.length};let m=e.baseURL+"&bytes="+t+"-"+s;this._params.requestQuic&&(m=Ut(m)),this._lastXhr=new nd(m,e.failoverHosts,g=>{this._lastXhr=void 0,p(g);const S=Date.now()-u;this._params.onBandwidthChange({size:g.length,duration:S,speed:8*g.length/(S/1e3)}),this._onDashCallback("loading",{size:g.length,done:!0}),n==null||n()},g=>{if(g.length-d>l&&p(g),h===0){h=Date.now();return}f=g.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=g.length,h=Date.now()),this._onDashCallback("loading",{size:g.length,done:!1})},o,(g,S,v)=>this._params.onError(g,S,v))})}abort(e){var t;(t=this._lastXhr)===null||t===void 0||t.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._mediaSource.readyState==="open"&&this._sourceBuffer.abort(),e==null||e()})})}_sbUpdatingWatch(e){if(this._sourceBuffer.updating){const t=()=>{try{this._sbUpdatingStop(t),this._sbUpdatingWatch(e)}catch(s){throw this._params.onError("SourceBuffer","Source Buffer update error",s),s}};return this._sourceBuffer.addEventListener("updateend",t,!1),t}e()}_sbUpdatingStop(e){e&&this._sourceBuffer.removeEventListener("updateend",e,!1)}append(e,t){this._appendPromiseUint8Array?this._appendPromiseUint8Array=tr._concatUint8(this._appendPromiseUint8Array,e):(this._appendPromiseUint8Array=e,this._lastStreamUpdatingCallback=this._sbUpdatingWatch(()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,()=>{this._appendPromiseUint8Array=void 0,t&&this._sbUpdatingWatch(t)})}))}endOfStream(){this._mediaSource.readyState==="open"&&this._sbUpdatingWatch(()=>this._mediaSource.endOfStream())}static _concatUint8(e,t){const s=new Uint8Array(e.byteLength+t.byteLength);return s.set(e,0),s.set(t,e.byteLength),s}static _str2ua(e){const t=new Uint8Array(e.length);for(let s=0;s<e.length;s++)t[s]=e.charCodeAt(s);return t}remove(e,t){this._sbUpdatingWatch(()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(e,t),this._maxBufferDuration=Number.POSITIVE_INFINITY})}destroy(){var e;(e=this._lastXhr)===null||e===void 0||e.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._mediaSource.readyState==="open"&&this._sourceBuffer.abort()}}class kS{constructor(e){var t;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=e,this._video=e.video,this._buffer=e.buffer,this._onDashCallback=(t=e.onDashCallback)!==null&&t!==void 0?t:()=>{},this._config=e.config}_parseDurationFromISO8601(e){const t=/^(-)?P(?:(-?[0-9,.]*)Y)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)W)?(?:(-?[0-9,.]*)D)?(?:T(?:(-?[0-9,.]*)H)?(?:(-?[0-9,.]*)M)?(?:(-?[0-9,.]*)S)?)?$/,s=(l,d)=>{const u=l?parseFloat(l.replace(",",".")):NaN;return(isNaN(u)?0:u)*d},r=t.exec(e),n=(r==null?void 0:r[1])==="-"?-1:1,o={years:s(r==null?void 0:r[2],n),months:s(r==null?void 0:r[3],n),weeks:s(r==null?void 0:r[4],n),days:s(r==null?void 0:r[5],n),hours:s(r==null?void 0:r[6],n),minutes:s(r==null?void 0:r[7],n),seconds:s(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let s=e;this._config.REQUEST_QUIC&&(s=Ut(s)),new nd(s,t,r=>{this.attachManifest(r,t,ES(s))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,s){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,m,g,S,v,y,b,T,E,P,N,V,L,B,M,D;const I=u.getElementsByTagName("SegmentBase")[0],U=I&&o(I,"indexRange").split("-"),R=I&&I.getElementsByTagName("Initialization")[0],_=R&&o(R,"range").split("-");if(!_||!U){const Ie=u.parentElement;if((Ie==null?void 0:Ie.getAttribute("contentType"))==="text"){const Ge=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,q=(s?s+"/":"")+((m=(p=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||p===void 0?void 0:p[0])===null||m===void 0?void 0:m.data),Ee=(g=Ie.getAttribute("lang"))!==null&&g!==void 0?g:void 0;q&&d.push({id:Ge,url:q,language:Ee})}return}const O=.1,z=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),te=(s?s+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ne;const me=(y=(v=u.attributes.getNamedItem("frameRate"))===null||v===void 0?void 0:v.value)!==null&&y!==void 0?y:void 0;ne=me?kr(me):void 0,l.push({width:Number((b=u.attributes.getNamedItem("width"))===null||b===void 0?void 0:b.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:z,baseURL:te,failoverHosts:t,indexFrom:Number(U[0]),indexTo:Number(U[1]),initFrom:Number(_[0]),initTo:Number(_[1]),codecs:(P=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&P!==void 0?P:void 0,mimeType:(V=(N=u.attributes.getNamedItem("mimeType"))===null||N===void 0?void 0:N.value)!==null&&V!==void 0?V:void 0,fps:ne,bufferSize:O*z/8,bufferLength:O,name:(B=(L=u.attributes.getNamedItem("okQuality"))===null||L===void 0?void 0:L.value)!==null&&B!==void 0?B:void 0,id:(D=(M=u.attributes.getNamedItem("id"))===null||M===void 0?void 0:M.value)!==null&&D!==void 0?D:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const s=Date.now();this._stream.load(e,e.initFrom,e.indexTo,r=>{let n=e.initTo-e.initFrom+1;if(!r.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(r.buffer,0,n);const o=new DataView(r.buffer);n+=12;const l=o.getUint32(n+4,!1);n+=8;let d=o.getUint32(n,!1),u=o.getUint32(n+4,!1)+(e.indexTo+1);n+=8;const c=o.getUint16(n+2,!1);n+=4,e.refs=[];for(let f=0;f<c;f+=1){const p=u+(o.getUint32(n,!1)&2147483647),m=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:m/l,fromOffset:u,toOffset:p-1}),u=p,d=m}const h=e.refs[e.refs.length-1];h.toTime-h.fromTime<.3&&e.refs.pop(),this._stream.append(e.initMessage,t)},void 0,r=>{this._params.onResponseHeaders(r),this._params.onIdxRequestPing(Date.now()-s)},e.indexTo-e.initFrom+1)}startPlay(e){const t=window.MediaSource||window.WebKitMediaSource;if(!t){this._params.onError("MediaSourceNotSupported","MediaSource is not supported");return}const s=new t;let r,n;const o=()=>{const u=this._findRef(this._video.currentTime);if(!u||this._video.paused)return;if(!this._cachingPaused&&this._lastLoadOffset!==void 0&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const p=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),p)}const c=this._appendVector[String(u.fromTime)];c!==r&&(r=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const p=this._buffer.getByTime(this._video.currentTime);if(!p){this._onDashCallback("buffering");return}h=p.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==p.to&&(n=p.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(p);m&&(this._video.currentTime=m.from)}catch(m){throw this._params.onError("GapSyncError",`Seek Error ${String(m)}`,m),m}},h*1e3)))}},l=()=>{this._loopTimeout=window.setTimeout(()=>{try{o()}catch(u){throw this._params.onError("LoopError",`Dash Loop exception ${String(u)}`,u),u}l()},250)},d=()=>{if(!this._stream)try{const u=s.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new tr({mediaSource:s,sourceBuffer:u,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(u){throw this._params.onError("DashSourceOpen",`Source open exception ${String(u)}`,u),u}this._loadInitAndSidx(e),s.duration||(s.duration=this._duration),this._loopTimeout||l(),s.removeEventListener("sourceopen",d),s.removeEventListener("webkitsourceopen",d)};s.addEventListener("sourceopen",d,!1),s.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(s),this._video.addEventListener("waiting",()=>{const u=this._video&&this._video.played.length;u&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(u-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}))}_loadRef(e,t,s=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(s){this._isLastRef(n)&&t>=n.toTime&&(t=n.fromTime);const o=this._findRef(this._video.currentTime),l=Math.abs(this._video.currentTime-t),d=r||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||n===o||l<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=d?t:n.fromTime}this._appendVector[String(n.fromTime)]=e,this._stream.load(e,n.fromOffset,n.toOffset,(o,l)=>this._stream.append(o,l),()=>{this._lastLoadOffset=n.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()},o=>this._params.onResponseHeaders(o),e.bufferSize)}})}setQualityByRepresentation(e,t=!1){const s=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!s||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<s.to+n){const o=this._findRef(r.toTime);o&&o.toTime<s.to+n?(this._buffer.smartRemove(r.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(r.fromTime-n,r.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,r.toTime))}}setQuality(e){return this.setQualityByRepresentation(this._representations[e])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(e,t){this._stream&&this._buffer.getByTime(e)?this._video.currentTime=e:this._loadRef(this._params.selectRepresentation(this._representations),e,!0,t)}updateRefsForCurrentTime(){const e=this._video.currentTime;(!this._stream||a.isNullable(this._buffer.getByTime(e)))&&this._loadRef(this._params.selectRepresentation(this._representations),e,!1)}_findRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return;if(Array.isArray(s)&&s.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<s.length;n++){const o=s[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=s[s.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const s=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!s)return!1;const r=s[s.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const s=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>s&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var K;(function(i){i.STOPPED="stopped",i.MANIFEST_LOADED="manifest-loaded",i.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",i.METADATA_LOADED="metadata-loaded",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(K||(K={}));const AS=[K.PAUSED,K.PLAYING];class wS{constructor(e){this.videoState=new ee(K.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new nt,this.droppedFramesManager=new Ts,this.elementSize$=new a.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new a.Subject,responseHeaders$:new a.Subject,manifestReady$:new a.Subject,representationPlay$:new a.Subject,error$:new a.Subject},this.handleManifestReady=({representations:t,textRepresentations:s})=>{var r,n,o;const l=[];for(const d of t){const u=(n=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Mi(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(s==null?void 0:s.length)>0){const d=[];for(const u of s){const c=u.id||`${u.language}_${Date.now()}`;d.push({id:c,type:"internal",url:u.url||"",language:u.language,isAuto:u.isAuto})}this.params.desiredState.internalTextTracks.startTransitionTo(d)}this.videoState.setState(K.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var s;const r=(s=this.representations$.getValue().find(({representation:n})=>n===t))===null||s===void 0?void 0:s.track;r&&(this.params.output.currentVideoTrack$.next(r),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(r))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return a.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!s)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===Y.Requested&&AS.includes(t)&&this.seek(o.position,o.forcePrecise),t){case K.STOPPED:this.videoState.startTransitionTo(K.MANIFEST_LOADED),this.prepare();return;case K.MANIFEST_LOADED:this.videoState.startTransitionTo(K.INITIAL_REPRESENTATION_SELECTED);return;case K.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(K.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case K.METADATA_LOADED:this.videoState.startTransitionTo(K.READY),this.dash.updateRefsForCurrentTime();return;case K.READY:r===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),a.merge(this.videoState.stateChangeStarted$.pipe(a.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:s})=>{this.log({message:`[videoState change] ${s}: ${JSON.stringify(t)}`})}),this.video=bt(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.source.type==="url"&&this.params.output.hostname$.next(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new jg(this.video),this.dash=new kS({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:({representations:t,textRepresentations:s})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:s}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,s,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:s,thrown:r,category:a.ErrorCategory.WTF})},config:{SEEK_IN_SEGMENT_THRESHOLD:this.params.tuning.dashSeekInSegmentDurationThreshold,SEEK_IN_SEGMENT_DELTA:this.params.tuning.dashSeekInSegmentAlwaysSeekDelta,FRONT_CACHE_DURATION:this.params.config.cacheDuration/1e3,REQUEST_QUIC:this.params.tuning.requestQuick}}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"DashProvider",category:a.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},r=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=St(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,s));o(n.timeUpdate$,e.position$),o(n.durationChange$,e.duration$),o(n.ended$,e.endedEvent$),o(n.looped$,e.loopedEvent$),o(n.error$,e.error$),o(n.isBuffering$,e.isBuffering$),o(n.playing$,e.firstFrameEvent$),o(n.canplay$,e.canplay$),o(n.inPiP$,e.inPiP$),o(n.inFullscreen$,e.inFullscreen$),this.subscription.add(n.seeking$.subscribe(()=>{a.isNullable(this.params.desiredState.seekState.getState().state!==Y.Applying)&&(this.videoState.getState()===K.PLAYING||this.videoState.getState()===K.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(Ht(this.video,t.isLooped,s)),this.subscription.add(vt(this.video,t.volume,n.volumeState$,s)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Lt(this.video,t.playbackRate,n.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:n.playing$,pause$:n.pause$,tracks$:this.representations$.pipe(a.map(l=>l.map(({track:d})=>d)))}),o(us(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.READY)},s)).add(n.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},s)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(K.METADATA_LOADED)},s)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},s)).add(this.dashLiteEvents.error$.pipe(a.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:a.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(a.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeStarted$,this.params.output.element$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,a.fromEvent(this.video,"progress")).pipe(a.map(()=>{var l,d,u,c;const h=this.currentRepresentation$.getValue(),f=this.representations$.getValue(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=(l=this.params.desiredState.videoTrack.getState())===null||l===void 0?void 0:l.id,g=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),v=r();p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to);let y;if(!v&&a.isNonNullable(m))y=m;else{const b=Le(this.video.buffered,this.video.currentTime*1e3),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(b/T,1);y=(u=hi(f.map(({track:N})=>N),{container:S,throughput:g,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(d=f.find(({representation:N})=>N===h))===null||d===void 0?void 0:d.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||u===void 0?void 0:u.id;const P=t.autoVideoTrackLimits.getTransition();P&&e.autoVideoTrackLimits$.next(P.to)}return a.isNonNullable(y)?(c=f.find(({track:b})=>b.id===y))===null||c===void 0?void 0:c.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,s)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===K.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(K.INITIAL_REPRESENTATION_SELECTED),s)).add(this.currentRepresentation$.pipe(a.filter(a.isNonNullable),a.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?l.height<=d.height:l===d)).subscribe(l=>{const d=Le(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!r())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(_e(l.baseURL)))},s)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Fn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(a.once(),a.mapTo(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe(l=>this.params.dependencies.throughputEstimator.addRawRtt(l))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){const e=this.params.source;switch(e.type){case"url":this.dash.attachSource(e.url);break;case"raw":this.dash.attachManifest(e.raw);break;default:return a.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}var Se;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(Se||(Se={}));var ir;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ir||(ir={}));var qe;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(qe||(qe={}));var J;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(J||(J={}));var Ii;(function(i){i.MP4="mp4",i.WEBM="webm"})(Ii||(Ii={}));var sr;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(sr||(sr={}));var le;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(le||(le={}));class fl{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,s){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:s})}removeEventListener(e,t){if(!(e in this.listeners))return;const s=this.listeners[e];for(let r=0,n=s.length;r<n;r++)if(s[r].callback===t){s.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const s=this.listeners[e.type].slice();for(let r=0,n=s.length;r<n;r++){const o=s[r];try{o.callback.call(this,e)}catch(l){Promise.resolve().then(()=>{throw l})}o.options&&o.options.once&&this.removeEventListener(e.type,o.callback)}return!e.defaultPrevented}}class od extends fl{constructor(){super(),this.listeners||fl.call(this),Object.defineProperty(this,"aborted",{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,"onabort",{value:null,writable:!0,configurable:!0}),Object.defineProperty(this,"reason",{value:void 0,writable:!0,configurable:!0})}toString(){return"[object AbortSignal]"}dispatchEvent(e){e.type==="abort"&&(this.aborted=!0,typeof this.onabort=="function"&&this.onabort.call(this,e)),super.dispatchEvent(e)}}let ld=class{constructor(){Object.defineProperty(this,"signal",{value:new od,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(r){typeof document!="undefined"?document.createEvent?(t=document.createEvent("Event"),t.initEvent("abort",!1,!1)):(t=document.createEventObject(),t.type="abort"):t={type:"abort",bubbles:!1,cancelable:!1}}let s=e;if(s===void 0)if(typeof document=="undefined")s=new Error("This operation was aborted"),s.name="AbortError";else try{s=new DOMException("signal is aborted without reason")}catch(r){s=new Error("This operation was aborted"),s.name="AbortError"}this.signal.reason=s,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(ld.prototype[Symbol.toStringTag]="AbortController",od.prototype[Symbol.toStringTag]="AbortSignal");function ud(i){return i.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof i.Request=="function"&&!i.Request.prototype.hasOwnProperty("signal")||!i.AbortController}function PS(i){typeof i=="function"&&(i={fetch:i});const{fetch:e,Request:t=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=i;if(!ud({fetch:e,Request:t,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||r)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(p){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((p,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Ar=ud({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),dd=Ar?PS({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,li=Ar?dd.fetch:window.fetch;Ar?dd.Request:window.Request;const Qe=Ar?ld:window.AbortController;var Ri=(i,e)=>{for(let t=0;t<i.length;t++)if(i.start(t)*1e3<=e&&i.end(t)*1e3>e)return!0;return!1};const _S=(i,e={})=>{const s=e.timeout||1,r=performance.now();return window.setTimeout(()=>{i({get didTimeout(){return e.timeout?!1:performance.now()-r-1>s},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},DS=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",rr=DS?_S:window.requestIdleCallback;var Ta,Ea;const IS=16;let cd=!1;try{cd=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Ea=(Ta=navigator.userAgent.match(/Version\/(\d+)/))===null||Ta===void 0?void 0:Ta[1])!==null&&Ea!==void 0?Ea:"",10)<=IS}catch(i){console.error(i)}let RS=class{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return F(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return F(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return F(this,void 0,void 0,function*(){return new Promise(t=>{let s;cd&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}};var ar=i=>{let e=0;for(let t=0;t<i.length;t++)e+=i.end(t)-i.start(t);return e*1e3};let yt=class{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}},hd=class extends yt{},CS=class extends yt{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}},xS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},LS=class extends yt{constructor(e){super(e),this.data=this.content}},Es=class extends yt{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},NS=class extends Es{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}},OS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},BS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}};var ri;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(ri||(ri={}));let MS=class extends Es{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=ri.MONOSCOPIC;break;case 1:this.stereoMode=ri.TOP_BOTTOM;break;case 2:this.stereoMode=ri.LEFT_RIGHT;break;case 3:this.stereoMode=ri.STEREO_CUSTOM;break;case 4:this.stereoMode=ri.RIGHT_LEFT;break}this.cursor+=1}},VS=class extends Es{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},FS=class extends Es{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},US=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},jS=class extends Es{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()}},HS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}},GS=class extends yt{parseChildrenBoxes(){return Vi(this.content)}};const YS={ftyp:CS,moov:xS,mdat:LS,sidx:NS,trak:OS,mdia:US,tkhd:jS,minf:HS,sv3d:BS,st3d:MS,prhd:VS,proj:GS,equi:FS,unknown:hd};let zS=class{createBox(e,t){const s=YS[e];return s?new s(t):new hd(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return wr.createBox(s,new DataView(e.buffer,e.byteOffset))}};const wr=new zS;function is(i,e){const t=new TextDecoder("ascii");let s=i.byteOffset,r=[];for(;s<i.byteLength;){const n=t.decode(new DataView(i.buffer,s,1));if(n===e[r.length]?r.push(n):r=[],r.length===4&&r.join("")===e){const l=new DataView(i.buffer,s-7,4).getUint32(0);return s-7+l>i.byteLength?null:wr.createBox(e,new DataView(i.buffer,s-7))}s++}return null}function qS(i,e){const t=[];let s=0;for(;s<i.byteLength;){const r=is(new DataView(i.buffer,i.byteOffset+s,i.byteLength-s),e);if(r)t.push(r),s+=r.size+r.source.byteOffset;else break}return t}function Vi(i){const e=[];let t=0;for(;t<i.byteLength;){const s=wr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const WS=new TextDecoder("ascii"),QS=i=>WS.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",KS=i=>{const e=wr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:J.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},JS=i=>{const e=qS(i,"mdat");if(e.length){const t=e.reduce((s,r)=>s+r.size,0);return new DataView(i.buffer,i.byteOffset,t)}return null},XS=i=>{const e={is3dVideo:!1,stereoMode:0,projectionType:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(is(i,"sv3d")){e.is3dVideo=!0;const s=is(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=is(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=is(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},ZS={validateData:QS,parseInit:XS,getIndexRange:()=>{},parseSegments:KS,parseFeedableSegmentChunk:JS};var $;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})($||($={}));var C;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(C||(C={}));const pl={[$.EBML]:{type:C.Master},[$.EBMLVersion]:{type:C.UnsignedInteger},[$.EBMLReadVersion]:{type:C.UnsignedInteger},[$.EBMLMaxIDLength]:{type:C.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[$.DocType]:{type:C.String},[$.DocTypeVersion]:{type:C.UnsignedInteger},[$.DocTypeReadVersion]:{type:C.UnsignedInteger},[$.Void]:{type:C.Binary},[$.Segment]:{type:C.Master},[$.SeekHead]:{type:C.Master},[$.Seek]:{type:C.Master},[$.SeekID]:{type:C.Binary},[$.SeekPosition]:{type:C.UnsignedInteger},[$.Info]:{type:C.Master},[$.TimestampScale]:{type:C.UnsignedInteger},[$.Duration]:{type:C.Float},[$.Tracks]:{type:C.Master},[$.TrackEntry]:{type:C.Master},[$.Video]:{type:C.Master},[$.Projection]:{type:C.Master},[$.ProjectionType]:{type:C.UnsignedInteger},[$.ProjectionPrivate]:{type:C.Master},[$.Chapters]:{type:C.Master},[$.Cluster]:{type:C.Master},[$.Timestamp]:{type:C.UnsignedInteger},[$.SilentTracks]:{type:C.Master},[$.SilentTrackNumber]:{type:C.UnsignedInteger},[$.Position]:{type:C.UnsignedInteger},[$.PrevSize]:{type:C.UnsignedInteger},[$.SimpleBlock]:{type:C.Binary},[$.BlockGroup]:{type:C.Master},[$.EncryptedBlock]:{type:C.Binary},[$.Attachments]:{type:C.Master},[$.Tags]:{type:C.Master},[$.Cues]:{type:C.Master},[$.CuePoint]:{type:C.Master},[$.CueTime]:{type:C.UnsignedInteger},[$.CueTrackPositions]:{type:C.Master},[$.CueTrack]:{type:C.UnsignedInteger},[$.CueClusterPosition]:{type:C.UnsignedInteger},[$.CueRelativePosition]:{type:C.UnsignedInteger},[$.CueDuration]:{type:C.UnsignedInteger},[$.CueBlockNumber]:{type:C.UnsignedInteger},[$.CueCodecState]:{type:C.UnsignedInteger},[$.CueReference]:{type:C.Master},[$.CueRefTime]:{type:C.UnsignedInteger}},fd=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=nr(i,t),r=s in pl,n=r?pl[s].type:C.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=nr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},nr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ht=(i,e)=>{switch(e){case C.SignedInteger:return i.getInt8(0);case C.UnsignedInteger:return nr(i);case C.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(i);case C.UTF8:return new TextDecoder("utf-8").decode(i);case C.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case C.Master:return i;case C.Binary:return i;default:a.assertNever(e)}},Ci=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=fd(s);if(!e(r))return;r.type===C.Master&&Ci(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},ey=i=>{if(i.getUint32(0)!==$.EBML)return!1;let e,t,s;const r=fd(i);return Ci(r.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=ht(l,o):n===$.DocType?t=ht(l,o):n===$.DocTypeReadVersion&&(s=ht(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},pd=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],ty=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],iy=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Ci(i,({tag:f,type:p,value:m,valueSize:g})=>{if(f===$.SeekID){const S=ht(m,p);u=nr(S)}else f!==$.SeekPosition&&(u=void 0);return f===$.Segment?(e=m.byteOffset,t=m.byteOffset+g):f===$.Info?n=!0:f===$.SeekHead?o=!0:f===$.TimestampScale?s=ht(m,p):f===$.Duration?r=ht(m,p):f===$.SeekPosition&&u===$.Cues?d=ht(m,p):f===$.Tracks?Ci(m,({tag:S,type:v,value:y})=>S===$.ProjectionType?(c=ht(y,v)===1,!1):!0):n&&o&&pd.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:sr.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},sy=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ry=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Ci(i,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&r(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=ht(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=ht(u,d));break;default:t&&pd.includes(l)&&(s=!0)}return!(t&&s)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:J.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},ay=i=>{let e=0,t=!1;try{Ci(i,s=>s.tag===$.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):ty.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},ny={validateData:ey,parseInit:iy,getIndexRange:sy,parseSegments:ry,parseFeedableSegmentChunk:ay},md=1e4,oy=3e4,ly=5e3,uy=md,dy=({id:i,width:e,height:t,bitrate:s,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:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},cy=({id:i,bitrate:e})=>({id:i,bitrate:e}),hy=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=ge(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:ge(i,-1)},fy=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),Vs=i=>{const e=[];let t=0,s=i.length-1;for(;t<md&&s>=0;)e.unshift(i[s]),t+=i[s].time.to-i[s].time.from,s--;return e};let ml=class{constructor(e,t,s,r,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.isSeekingLive=!1,this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Qe,this.destroyAbortController=new Qe,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=a.abortable(this.destroyAbortController.signal,function(c){return Z(this,arguments,function*(){const h=this.representations.get(c);a.assertNonNullable(h,`Cannot find representation ${c}`),this.playingRepresentationId=c,this.downloadingRepresentationId=c,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${h.mime}; codecs="${h.codecs}"`),this.sourceBufferTaskQueue=new RS(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},g=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:g}))),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(g=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),g)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(g=>this.error$.next(g))),yield yield A(this.loadInit(h,"high",!0));const f=this.initData.get(h.id),p=this.segments.get(h.id),m=this.parsedInitData.get(h.id);if(a.assertNonNullable(f,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(f instanceof ArrayBuffer))return yield A(void 0);this.searchGaps(p,h),yield yield A(this.sourceBufferTaskQueue.append(f,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)})}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,function(c){return Z(this,arguments,function*(){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return yield A(void 0);this.switchingToRepresentationId=c;const h=this.representations.get(c);a.assertNonNullable(h,`No such representation ${c}`);let f=this.segments.get(c),p=this.initData.get(c);if(a.isNullable(p)||a.isNullable(f)?yield yield A(this.loadInit(h,"high",!1)):p instanceof Promise&&(yield yield A(p)),f=this.segments.get(c),a.assertNonNullable(f,"No segments for starting representation"),p=this.initData.get(c),!p||!(p instanceof ArrayBuffer)||!this.sourceBuffer)return yield A(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield yield A(this.sourceBufferTaskQueue.append(p,this.downloadAbortController.signal));const m=this.getCurrentPosition();a.isNonNullable(m)&&(this.searchGaps(f,h),this.maintain(m))})}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,function(c){return Z(this,arguments,function*(){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return yield A(void 0);for(const S of this.representations.keys()){const v=c.find(T=>T.id===S);v&&this.representations.set(S,v);const y=this.representations.get(S);if(!y)return yield A(void 0);const b=Vs(y.segmentReference.segments);this.segments.set(y.id,b)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,f=this.representations.get(h);a.assertNonNullable(f);const p=Vs(f.segmentReference.segments),m=this.initData.get(f.id);if(a.assertNonNullable(m,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),!(m instanceof ArrayBuffer))return yield A(void 0);const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield yield A(this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal))),this.searchGaps(p,f),yield yield A(this.sourceBufferTaskQueue.append(m,this.destroyAbortController.signal)),this.isSeekingLive=!1})}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isLive=!!(u!=null&&u.dynamic),this.container=s,s){case Ii.MP4:this.containerParser=ZS;break;case Ii.WEBM:this.containerParser=ny;break;default:a.assertNever(s)}this.initData=new Map(r.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(c=>[c.id,c])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Qe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Le(this.sourceBuffer.buffered,e),h=r?r.time.to+100:-1/0;r&&c>=r.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&ar(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Le(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=ge(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===J.FED&&!l.length&&Le(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=ge(s,-1);d&&d.status===J.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let s=0;for(const r of e)r.time.from-s>0&&this.gaps.push({representation:t.id,from:s,to:r.time.from}),s=r.time.to;a.isNonNullable(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o)return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:J.NONE,size:void 0})),d=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(r=ge(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.round(u)>=Math.round(h.time.from)&&Math.round(u)<=Math.round(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=Vs(l);this.segments.set(o.id,[...h])}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const g=f<=s&&p>=s,S=f>s||g||m===0&&s===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+v||p<=s+v;return(h===J.NONE||h===J.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!Ri(this.sourceBuffer.buffered,s))&&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===J.NONE||f.status===J.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,s="auto"){return F(this,void 0,void 0,function*(){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case qe.BYTE_RANGE:{r=t.segmentReference.url,n={from:ge(e,0).byte.from,to:ge(e,-1).byte.to};break}case qe.TEMPLATE:{const u=ge(e,0);r=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:a.assertNever(l)}for(const u of o)u.status=J.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield a.abortable(d,function(){return Z(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield A(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),d.aborted))for(const u of this.activeSegments)e.includes(u.segment)&&this.abortSegment(u.segment);return void this.fetcher.fetch(r,{range:n,onProgress:(u,c)=>{if(!d.aborted)try{this.onSomeDataLoaded(u,t.id,n?n.from:0,c,d)}catch(h){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:h})}},signal:d,priority:s}).then(()=>this.failedDownloads=0,u=>{if(u.name!=="AbortError"){for(const c of this.activeSegments)e.includes(c.segment)&&this.abortSegment(c.segment);this.onSegmentDownloadError(u)}})})}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=Le((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,s,r,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=J.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const p of this.representations.values())if(p.id!==t)for(const m of(f=this.segments.get(p.id))!==null&&f!==void 0?f:[])m.status===J.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=J.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,p=u===qe.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=s&&f.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const S=p?f.byte.from-s:0,v=p?f.byte.to-s:e.byteLength,y=S<r,b=v<=r;if(f.status===J.DOWNLOADING&&y&&b){f.status=J.DOWNLOADED,this.activeSegments.delete(h);const T=new DataView(e.buffer,e.byteOffset+S,m);this.sourceBufferTaskQueue.append(T,n).then(E=>E&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(m,r-S),h.loadedBytes>h.feedingBytes)){const T=new DataView(e.buffer,e.byteOffset+S+h.feedingBytes,h.loadedBytes-h.feedingBytes),E=h.loadedBytes===m?T:this.containerParser.parseFeedableSegmentChunk(T);E!=null&&E.byteLength&&(f.status=J.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(P=>{if(n.aborted)o();else if(P)h.fedBytes+=E.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===J.PARTIALLY_FED||e.status===J.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=J.NONE),e.status=J.PARTIALLY_EJECTED):e.status=J.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=rr(()=>Ss(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return F(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Z(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield A(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),this.segments.set(e.id,this.isLive?Vs(c):c),d&&this.parsedInitData.set(e.id,d)})).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,s=!1){return 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="size"in u?(c=u.size)!==null&&c!==void 0?c:0:u.byte.to-u.byte.from;r+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||r>=t)break;c.status===J.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===J.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===J.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===J.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:n})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:n}=r;if(n!==J.FED&&n!==J.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=J.PARTIALLY_EJECTED:r.status=J.NONE)}}};var Pi;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(Pi||(Pi={}));let py=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Qe,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 A(li(n,{signal:this.abortAllController.signal}).catch(Xi));return o?(this.onHeadersReceived(o.headers),yield A(o.text())):yield A(null)})}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,function(r,{rangeMethod:n=this.compatibilityMode?Pi.HEADER:Pi.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;return Z(this,arguments,function*(){let g=r;const S=new Headers;if(o)switch(n){case Pi.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case Pi.PARAM:{const O=new URL(g,location.href);O.searchParams.append("bytes",`${o.from}-${o.to}`),g=O.toString();break}default:a.assertNever(n)}this.requestQuic&&(g=Ut(g));let v=this.abortAllController.signal,y;if(u){const O=new Qe;if(y=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{O.abort()}catch(z){Xi(z)}}),this.abortAllController.signal.aborted||u.aborted)try{O.abort()}catch(z){Xi(z)}v=O.signal}const b=a.now(),T=yield yield A(li(g,{priority:d,headers:S,signal:v}).catch(Xi)),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-b),!T)return y==null||y.unsubscribe(),yield A(null);if(!T.ok||!T.body)return y==null||y.unsubscribe(),yield A(Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`)));this.onHeadersReceived(T.headers);const P=parseInt((f=T.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!P){const O=yield yield A(T.arrayBuffer());return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(O.byteLength,a.now()-E),l==null||l(new DataView(O),O.byteLength),y==null||y.unsubscribe(),yield A(O)}if(!l&&!c)return y==null||y.unsubscribe(),yield A(T.arrayBuffer());const[N,V]=T.body.tee(),L=N.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(V));let B=0;const M=new ArrayBuffer(P),D=new Uint8Array(M),I=new DataView(M);let U=!1;const R=O=>{y==null||y.unsubscribe(),U=!0,Xi(O)},_=a.abortable(v,function({done:O,value:z}){return Z(this,arguments,function*(){if(B===0&&this.lastRequestFirstBytes$.next(a.now()-b),v.aborted)return y==null||y.unsubscribe(),yield A(void 0);!O&&z&&(D.set(z,B),B+=z.byteLength,l==null||l(I,B),yield yield A(L==null?void 0:L.read().then(_,R)))})}.bind(this));return yield yield A(L==null?void 0:L.read().then(_,R)),y==null||y.unsubscribe(),yield A(U?null:M)})}.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 A(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 g=yield yield A(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!g)return yield A(null);const S=new DataView(g,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const v=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let b;if(f)b=new DataView(g,y.from-c,y.to-y.from+1);else{const E=yield yield A(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!E)return yield A(null);b=new DataView(E)}const T=n.parseSegments(b,v,y);return yield A({init:v,dataView:new DataView(g),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 A(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield A(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield A(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:J.NONE,size:void 0}));return yield A({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Fn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="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,s))!==null&&r!==void 0?r:null;case qe.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const Xi=i=>{if(!(i instanceof DOMException)||!(i.name==="AbortError"||i.code===20))throw i};var my=Ct,vy=cs,by=De,gy=by("match"),Sy=function(i){var e;return my(i)&&((e=i[gy])!==void 0?!!e:vy(i)=="RegExp")},yy=vs,Ty=String,Ey=function(i){if(yy(i)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Ty(i)},$y=xt,ky=function(){var i=$y(this),e="";return i.hasIndices&&(e+="d"),i.global&&(e+="g"),i.ignoreCase&&(e+="i"),i.multiline&&(e+="m"),i.dotAll&&(e+="s"),i.unicode&&(e+="u"),i.unicodeSets&&(e+="v"),i.sticky&&(e+="y"),e},Ay=He,wy=mt,Py=mr,_y=ky,vl=RegExp.prototype,Dy=function(i){var e=i.flags;return e===void 0&&!("flags"in vl)&&!wy(i,"flags")&&Py(vl,i)?Ay(_y,i):e},Un=Je,Iy=Sr,Ry=Math.floor,$a=Un("".charAt),Cy=Un("".replace),ka=Un("".slice),xy=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ly=/\$([$&'`]|\d{1,2})/g,Ny=function(i,e,t,s,r,n){var o=t+i.length,l=s.length,d=Ly;return r!==void 0&&(r=Iy(r),d=xy),Cy(n,d,function(u,c){var h;switch($a(c,0)){case"$":return"$";case"&":return i;case"`":return ka(e,0,t);case"'":return ka(e,o);case"<":h=r[ka(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=Ry(f/10);return p===0?u:p<=l?s[p-1]===void 0?$a(c,1):s[p-1]+$a(c,1):u}h=s[f-1]}return h===void 0?"":h})},Oy=at,By=He,jn=Je,bl=mn,My=pe,Vy=hs,Fy=Sy,yi=Ey,Uy=gr,jy=Dy,Hy=Ny,Gy=De,Yy=Gy("replace"),zy=TypeError,vd=jn("".indexOf),qy=jn("".replace),gl=jn("".slice),Wy=Math.max,Sl=function(i,e,t){return t>i.length?-1:e===""?t:vd(i,e,t)};Oy({target:"String",proto:!0},{replaceAll:function(e,t){var s=bl(this),r,n,o,l,d,u,c,h,f,p=0,m=0,g="";if(!Vy(e)){if(r=Fy(e),r&&(n=yi(bl(jy(e))),!~vd(n,"g")))throw zy("`.replaceAll` does not allow non-global regexes");if(o=Uy(e,Yy),o)return By(o,e,s,t);if(r)return qy(yi(s),e,t)}for(l=yi(s),d=yi(e),u=My(t),u||(t=yi(t)),c=d.length,h=Wy(1,c),p=Sl(l,d,0);p!==-1;)f=u?yi(t(d,p,l)):Hy(d,l,p,[],void 0,t),g+=gl(l,m,p)+f,m=p+c,p=Sl(l,d,p+h);return m<l.length&&(g+=gl(l,m)),g}});var Qy=Bn,Ky=Qy("String","replaceAll"),Jy=Ky,Xy=Jy,Zy=Xy,e0=Zy,or=fr(e0);const yl=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Aa=(i,e)=>{let t=i;t=or(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(s)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},t0=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,p,m,g,S,v,y,b,T,E,P,N,V,L,B,M,D,I,U,R,_,O,z,te,ne,me,Ie,Ge,q;const Re=new DOMParser().parseFromString(i,"application/xml"),ve={video:[],audio:[],text:[]},ce=Re.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 $e;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)$e=yl(Fi);else if(Ui){const oe=yl(Ui);a.isNonNullable(oe)&&($e=oe)}else ji&&($e=parseInt(ji,10));let _r=0;const zt=(s=(t=ce.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Dr=zt.includes(ir.WEBM_AS_IN_FFMPEG)||zt.includes(ir.WEBM_AS_IN_SPEC)?Ii.WEBM:Ii.MP4;for(const oe of Et){const kt=oe.getAttribute("mimeType"),Ir=oe.getAttribute("codecs"),Hi=(r=oe.getAttribute("contentType"))!==null&&r!==void 0?r:kt==null?void 0:kt.split("/")[0],Rr=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gi=oe.querySelectorAll("Representation"),Cr=oe.querySelector("SegmentTemplate");if(Hi===Se.TEXT){for(const j of Gi){const be=j.getAttribute("id")||"",At=oe.getAttribute("lang"),Ne=(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(Ne,e).toString(),Wt=be.includes("_auto");ve[Se.TEXT].push({id:be,lang:At,isAuto:Wt,kind:Se.TEXT,url:qt})}continue}for(const j of Gi){const be=(c=j.getAttribute("mimeType"))!==null&&c!==void 0?c:kt,At=(f=(h=j.getAttribute("codecs"))!==null&&h!==void 0?h:Ir)!==null&&f!==void 0?f:"",Ne=(m=(p=j.getAttribute("contentType"))!==null&&p!==void 0?p:be==null?void 0:be.split("/")[0])!==null&&m!==void 0?m:Hi,qt=(S=(g=oe.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&S!==void 0?S:[],Wt=parseInt((v=j.getAttribute("width"))!==null&&v!==void 0?v:"",10),Yi=parseInt((y=j.getAttribute("height"))!==null&&y!==void 0?y:"",10),zi=parseInt((b=j.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,qi=(T=j.getAttribute("frameRate"))!==null&&T!==void 0?T:"",xr=(E=j.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Lr=qi?kr(qi):void 0,Nr=(P=j.getAttribute("id"))!==null&&P!==void 0?P:(_r++).toString(10),Or=Ne==="video"?`${Yi}p`:Ne==="audio"?`${zi}Kbps`:At,Br=`${Nr}@${Or}`,Mr=(L=(V=(N=j.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||V===void 0?void 0:V.trim())!==null&&L!==void 0?L:"",Wi=new URL(Mr,e).toString(),Vr=[...zt,...Rr,...qt];let Qt;const Fr=j.querySelector("SegmentBase"),ke=(B=j.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Cr;if(Fr){const Oe=(D=(M=j.querySelector("SegmentBase Initialization"))===null||M===void 0?void 0:M.getAttribute("range"))!==null&&D!==void 0?D:"",[Be,Jt]=Oe.split("-").map(Me=>parseInt(Me,10)),Ce={from:Be,to:Jt},Ze=(I=j.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Xt,wt]=Ze?Ze.split("-").map(Me=>parseInt(Me,10)):[],et=Ze?{from:Xt,to:wt}:void 0;Qt={type:qe.BYTE_RANGE,url:Wi,initRange:Ce,indexRange:et}}else if(ke){const Oe={representationId:(U=j.getAttribute("id"))!==null&&U!==void 0?U:void 0,bandwidth:(R=j.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Be=parseInt((_=ke.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Jt=(O=ke.getAttribute("initialization"))!==null&&O!==void 0?O:"",Ce=ke.getAttribute("media"),Ze=(te=parseInt((z=ke.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&te!==void 0?te:1,Xt=Aa(Jt,Oe);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");const wt=(ne=ke.querySelectorAll("SegmentTimeline S"))!==null&&ne!==void 0?ne:[],et=[];let Me=0;if(wt.length){let Zt=Ze,Ve=0;for(const ei of wt){const Fe=parseInt((me=ei.getAttribute("d"))!==null&&me!==void 0?me:"",10),he=parseInt((Ie=ei.getAttribute("r"))!==null&&Ie!==void 0?Ie:"",10)||0,tt=parseInt((Ge=ei.getAttribute("t"))!==null&&Ge!==void 0?Ge:"",10);Ve=Number.isFinite(tt)?tt:Ve;const xe=Fe/Be*1e3,ot=Ve/Be*1e3;for(let Pt=0;Pt<he+1;Pt++){const Qi=Aa(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:Zt.toString(10),segmentTime:(Ve+Pt*Fe).toString(10)})),pi=(ot||0)+Pt*xe,mi=pi+xe;Zt++,et.push({time:{from:pi,to:mi},url:Qi})}Ve+=(he+1)*Fe,Me+=(he+1)*xe}}else if(a.isNonNullable($e)){const Ve=parseInt((q=ke.getAttribute("duration"))!==null&&q!==void 0?q:"",10)/Be*1e3,ei=Math.ceil($e/Ve);let Fe=0;for(let he=1;he<ei;he++){const tt=Aa(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:he.toString(10),segmentTime:Fe.toString(10)}));et.push({time:{from:Fe,to:Fe+Ve},url:tt}),Fe+=Ve}}Qt={type:qe.TEMPLATE,baseUrl:Wi,initUrl:Xt,totalSegmentsDurationMs:Me,segments:et}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ne||!be)continue;const Kt={video:Se.VIDEO,audio:Se.AUDIO,text:Se.TEXT}[Ne];Kt&&ve[Kt].push({id:Br,kind:Kt,segmentReference:Qt,profiles:Vr,duration:$e,bitrate:zi,mime:be,codecs:At,width:Wt,height:Yi,fps:Lr,quality:xr})}}return{dynamic:Bt,liveAvailabilityStartTime:fi,duration:$e,container:Dr,representations:ve}},dn=1e3,Tl=["timeupdate","progress","play","seeked","stalled","waiting"];var Ye;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(Ye||(Ye={}));let i0=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(Ye.NONE),this.currentVideoRepresentation$=new a.ValueSubject(void 0),this.currentVideoRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.isLive$=new a.ValueSubject(!1),this.liveDuration$=new a.ValueSubject(0),this.liveAvailabilityStartTime$=new a.ValueSubject(void 0),this.bufferLength$=new a.ValueSubject(0),this.liveLoadBufferLength$=new a.ValueSubject(0),this.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Qe,this.initManifest=a.abortable(this.destroyController.signal,function(t,s,r){var n;return Z(this,arguments,function*(){this.element=t,this.manifestUrlString=Pe(s,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ye.MANIFEST_READY),this.manifest=yield yield A(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Ye.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 s=yield yield A(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!s)return yield A(this.manifest);let r;try{r=t0(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return yield A(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===Se.TEXT)};return this.isLive$.getValue()!==r.dynamic&&(this.isLive$.next(r.dynamic),this.liveDuration$.getValue()!==r.duration&&this.liveDuration$.next(-1*((t=r.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==r.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(r.liveAvailabilityStartTime)),yield A(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,s){return Z(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ye.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new ml(Se.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new ml(Se.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(dn).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=Pe(this.manifestUrlString,u+1e3,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Tl.map(l=>a.fromEvent(this.element,l))).pipe(a.throttle(dn),a.map(l=>this.element?Le(this.element.buffered,this.element.currentTime*1e3):0)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.subscribe(d=>{var u,c;let h=0;if(d){const f=((c=(u=this.element)===null||u===void 0?void 0:u.currentTime)!==null&&c!==void 0?c:0)*1e3;h=Math.min(...this.bufferManagers.map(m=>{var g,S;return(S=(g=m.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.to)!==null&&S!==void 0?S:0}))-f}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(d=>F(this,void 0,void 0,function*(){a.assertNonNullable(this.element);const u=this.element.playbackRate,c=er(this.manifestUrlString,ae.DASH_CMAF_OFFSET_P),h=oy*u,f=uy*u,p=ly*u;l=d>l?d:l;const m=c===0&&d<p,g=c!==0&&d<h+p&&d>=h,S=c!==0&&d<h;if(S||g){const v=l-(h+f),y=Math.trunc(c+v/u);let b;d?y>0?b=y:b=0:b=c,this.manifestUrlString=Pe(this.manifestUrlString,b,ae.DASH_CMAF_OFFSET_P)}(m||S||g)&&(yield this.updateLive(),l=0)})))}const n=a.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(a.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=a.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(a.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(a.merge(this.forceEnded$,a.combine({allBuffersFull:n,someBufferEnded:o}).pipe(a.filter(({allBuffersFull:l,someBufferEnded:d})=>l&&d))).subscribe(()=>{var l;if(this.source&&this.source.readyState==="open"&&Array.from(this.source.sourceBuffers).every(d=>!d.updating))try{(l=this.source)===null||l===void 0||l.endOfStream()}catch(d){this.error$.next({id:"EndOfStream",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(a.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.representationSubscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),this.subscription.add(this.videoBufferManager.playingRepresentationInit$.subscribe(this.currentVideoRepresentationInit$)),this.source.readyState!=="open"&&(yield yield A(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield A(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield A(this.videoBufferManager.startWith(t)),this.state$.setState(Ye.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new py({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}seekLive(e){var t,s,r,n;return F(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.manifestUrlString=Pe(this.manifestUrlString,e,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(Ye.RUNNING),this.subscription.add(a.merge(...Tl.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.tick()}switchRepresentation(e,t){return F(this,void 0,void 0,function*(){const s={[Se.VIDEO]:this.videoBufferManager,[Se.AUDIO]:this.audioBufferManager,[Se.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),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(Ye.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}updateLive(){var e;return F(this,void 0,void 0,function*(){this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class s0{constructor(e,t){this.fov=e,this.orientation=t}}class r0{constructor(e,t){this.rotating=!1,this.fading=!1,this.lastTickTS=0,this.lastCameraTurnTS=0,this.fadeStartSpeed=null,this.fadeTime=0,this.camera=e,this.options=t,this.rotationSpeed={x:0,y:0,z:0},this.fadeCorrection=1/Math.pow(this.options.speedFadeTime/1e3,2)}turnCamera(e=0,t=0,s=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+s)}pointCameraTo(e=0,t=0,s=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=s-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=s,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,s){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=s!=null?s:this.rotationSpeed.z}startRotation(){this.rotating=!0}stopRotation(e=!1){e?(this.setRotationSpeed(0,0,0),this.fadeStartSpeed=null):this.startFading(this.rotationSpeed.x,this.rotationSpeed.y,this.rotationSpeed.z),this.rotating=!1}onCameraRelease(){if(this.lastCameraTurn&&this.lastCameraTurnTS){const e=Date.now()-this.lastCameraTurnTS;if(e<this.options.speedFadeThreshold){const t=(1-e/this.options.speedFadeThreshold)*this.options.rotationSpeedCorrection;this.startFading(this.lastCameraTurn.x*t,this.lastCameraTurn.y*t,this.lastCameraTurn.z*t)}}}startFading(e,t,s){this.setRotationSpeed(e,t,s),this.fadeStartSpeed=Object.assign({},this.rotationSpeed),this.fading=!0}stopFading(){this.fadeStartSpeed=null,this.fading=!0,this.fadeTime=0}limitCameraRotationY(e){return Math.max(-this.options.maxYawAngle,Math.min(e,this.options.maxYawAngle))}tick(e){if(!this.lastTickTS){this.lastTickTS=e,this.lastCameraTurnTS=Date.now();return}const t=e-this.lastTickTS,s=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*Math.pow(this.fadeTime/1e3,2)+1;this.setRotationSpeed(this.fadeStartSpeed.x*r,this.fadeStartSpeed.y*r,this.fadeStartSpeed.z*r),r>0?this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*s,this.rotationSpeed.y*this.options.rotationSpeedCorrection*s,this.rotationSpeed.z*this.options.rotationSpeedCorrection*s):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var a0=`#define GLSLIFY 1
|
|
38
|
+
attribute vec2 a_vertex;attribute vec2 a_texel;varying vec2 v_texel;void main(void){gl_Position=vec4(a_vertex,0.0,1.0);v_texel=a_texel;}`,n0=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
41
41
|
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,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new 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"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(r0,this.gl.VERTEX_SHADER),s=this.createShader(a0,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,n=e-s,o=t-r,l=e+s,d=t-r,u=e+s,c=t+r,h=e-s,f=t+r;return[n,o,l,d,u,c,h,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let gd=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 rd,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==le.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==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),w(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),w(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&&w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var s,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=bt(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(_e(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,s=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:s,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Ye.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(f.video).sort((v,y)=>y.bitrate-v.bitrate),g=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const v of p){const y=dy(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=uy(v);if(y){h.push({track:y,representation:v});const b=!this.params.tuning.isAudioDisabled&&cy(p,m,v);b&&this.audioRepresentations.set(v.id,b)}}this.videoTracks$.next(h);for(const v of g){const y=hy(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(h.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));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===Ye.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!==Ye.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(Se.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(Se.AUDIO,p.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,n,o,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=Le(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),g=Math.max(c&&!d&&(r=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.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:g,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=d?S!=null?S:c:c!=null?c:S;return v&&((l=this.videoTracks$.getValue().find(({track:y})=>y===v))===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),w(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),gt(this.video)}},n0=class extends gd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ye;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ye||(ye={}));var dt;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(dt||(dt={}));var lr;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(lr||(lr={}));var We;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(We||(We={}));var j;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(j||(j={}));var xi;(function(i){i.MP4="mp4",i.WEBM="webm"})(xi||(xi={}));var ur;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(ur||(ur={}));var ue;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ue||(ue={}));var wa,Pa;let Sd=!1;try{Sd=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Pa=(wa=navigator.userAgent.match(/Version\/(\d+)/))===null||wa===void 0?void 0:wa[1])!==null&&Pa!==void 0?Pa:"",10)<16}catch(i){console.error(i)}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 s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return H(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return H(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return H(this,void 0,void 0,function*(){return new Promise(t=>{let s;Sd&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}class Xe{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 yd extends Xe{}class l0 extends Xe{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class u0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class d0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class c0 extends Xe{constructor(e){super(e),this.data=this.content}}class Ot extends Xe{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 s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class f0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class p0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}var ai;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(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 b0 extends Ot{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class g0 extends Xe{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 Xe{parseChildrenBoxes(){return Gt(this.content)}}class T0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class E0 extends Ot{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class $0 extends Xe{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 A0 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 w0 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:g0,mfhd:E0,tkhd:S0,traf:$0,tfhd:k0,tfdt:A0,trun:w0,minf:y0,sv3d:p0,st3d:m0,prhd:v0,proj:T0,equi:b0,unknown:yd};class _0{createBox(e,t){const s=P0[e];return s?new s(t):new yd(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Pr.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Pr=new _0;function ss(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(o=>o.charCodeAt(0));let r=i.byteOffset,n=[];for(;r<t.byteLength;){if(t[r]===s[n.length]?n.push(t[r]):n=[],n.length===4){const l=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+l>i.buffer.byteLength?null:Pr.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function cn(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=ss(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function Gt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=Pr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const D0=new TextDecoder("ascii"),I0=i=>D0.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",R0=i=>{const e=Pr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:j.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},C0=i=>{const e=cn(i,"mdat"),t=cn(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],n=s.source.byteOffset,l=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,n,l)},x0=(i,e)=>{const t=cn(i,"traf"),s=t[t.length-1].children.find(d=>d.type==="tfhd"),r=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,u)=>d+u,0):o=s.defaultSampleDuration*n.sampleCount,(Number(r.baseMediaDecodeTime)+o)/e*1e3},L0=i=>{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(i,"sv3d")){e.is3dVideo=!0;const s=ss(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=ss(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=ss(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},N0={validateData:I0,parseInit:L0,getIndexRange:()=>{},parseSegments:R0,parseFeedableSegmentChunk:C0,getSegmentEndTime:x0};var k;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(k||(k={}));var x;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(x||(x={}));const El={[k.EBML]:{type:x.Master},[k.EBMLVersion]:{type:x.UnsignedInteger},[k.EBMLReadVersion]:{type:x.UnsignedInteger},[k.EBMLMaxIDLength]:{type:x.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:x.UnsignedInteger},[k.DocType]:{type:x.String},[k.DocTypeVersion]:{type:x.UnsignedInteger},[k.DocTypeReadVersion]:{type:x.UnsignedInteger},[k.Void]:{type:x.Binary},[k.Segment]:{type:x.Master},[k.SeekHead]:{type:x.Master},[k.Seek]:{type:x.Master},[k.SeekID]:{type:x.Binary},[k.SeekPosition]:{type:x.UnsignedInteger},[k.Info]:{type:x.Master},[k.TimestampScale]:{type:x.UnsignedInteger},[k.Duration]:{type:x.Float},[k.Tracks]:{type:x.Master},[k.TrackEntry]:{type:x.Master},[k.Video]:{type:x.Master},[k.Projection]:{type:x.Master},[k.ProjectionType]:{type:x.UnsignedInteger},[k.ProjectionPrivate]:{type:x.Master},[k.Chapters]:{type:x.Master},[k.Cluster]:{type:x.Master},[k.Timestamp]:{type:x.UnsignedInteger},[k.SilentTracks]:{type:x.Master},[k.SilentTrackNumber]:{type:x.UnsignedInteger},[k.Position]:{type:x.UnsignedInteger},[k.PrevSize]:{type:x.UnsignedInteger},[k.SimpleBlock]:{type:x.Binary},[k.BlockGroup]:{type:x.Master},[k.EncryptedBlock]:{type:x.Binary},[k.Attachments]:{type:x.Master},[k.Tags]:{type:x.Master},[k.Cues]:{type:x.Master},[k.CuePoint]:{type:x.Master},[k.CueTime]:{type:x.UnsignedInteger},[k.CueTrackPositions]:{type:x.Master},[k.CueTrack]:{type:x.UnsignedInteger},[k.CueClusterPosition]:{type:x.UnsignedInteger},[k.CueRelativePosition]:{type:x.UnsignedInteger},[k.CueDuration]:{type:x.UnsignedInteger},[k.CueBlockNumber]:{type:x.UnsignedInteger},[k.CueCodecState]:{type:x.UnsignedInteger},[k.CueReference]:{type:x.Master},[k.CueRefTime]:{type:x.UnsignedInteger}},Td=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=dr(i,t),r=s in El,n=r?El[s].type:x.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=dr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},dr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ft=(i,e)=>{switch(e){case x.SignedInteger:return i.getInt8(0);case x.UnsignedInteger:return dr(i);case x.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case x.String:return new TextDecoder("ascii").decode(i);case x.UTF8:return new TextDecoder("utf-8").decode(i);case x.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case x.Master:return i;case x.Binary:return i;default:a.assertNever(e)}},Li=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Td(s);if(!e(r))return;r.type===x.Master&&Li(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},O0=i=>{if(i.getUint32(0)!==k.EBML)return!1;let e,t,s;const r=Td(i);return Li(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&&(s=ft(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Ed=[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=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Li(i,({tag:f,type:p,value:m,valueSize:g})=>{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+g):f===k.Info?n=!0:f===k.SeekHead?o=!0:f===k.TimestampScale?s=ft(m,p):f===k.Duration?r=ft(m,p):f===k.SeekPosition&&u===k.Cues?d=ft(m,p):f===k.Tracks?Li(m,({tag:S,type:v,value:y})=>S===k.ProjectionType?(c=ft(y,v)===1,!1):!0):n&&o&&Ed.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},V0=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},F0=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Li(i,({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&&Ed.includes(l)&&(s=!0)}return!(t&&s)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:j.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},U0=i=>{let e=0,t=!1;try{Li(i,s=>s.tag===k.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):B0.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},j0={validateData:O0,parseInit:M0,getIndexRange:V0,parseSegments:F0,parseFeedableSegmentChunk:U0},$l=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},$i=(i,e)=>{let t=i;t=or(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(s)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},H0=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,p,m,g,S,v,y,b,T,E,P,N,V,L,B,M,D,I,F,R,_,O,z,te,ne,me,Ie,Ge,q;const Re=new DOMParser().parseFromString(i,"application/xml"),ve={video:[],audio:[],text:[]},ce=Re.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 $e;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)$e=$l(Fi);else if(Ui){const oe=$l(Ui);a.isNonNullable(oe)&&($e=oe)}else ji&&($e=parseInt(ji,10));let _r=0;const zt=(s=(t=ce.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Dr=zt.includes(lr.WEBM_AS_IN_FFMPEG)||zt.includes(lr.WEBM_AS_IN_SPEC)?xi.WEBM:xi.MP4;for(const oe of Et){const kt=oe.getAttribute("mimeType"),Ir=oe.getAttribute("codecs"),Hi=(r=oe.getAttribute("contentType"))!==null&&r!==void 0?r:kt==null?void 0:kt.split("/")[0],Rr=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gi=oe.querySelectorAll("Representation"),Cr=oe.querySelector("SegmentTemplate");if(Hi===ye.TEXT){for(const U of Gi){const be=U.getAttribute("id")||"",At=oe.getAttribute("lang"),Ne=(u=(d=(l=U.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(Ne,e).toString(),Wt=be.includes("_auto");ve[ye.TEXT].push({id:be,lang:At,isAuto:Wt,kind:ye.TEXT,url:qt})}continue}for(const U of Gi){const be=(c=U.getAttribute("mimeType"))!==null&&c!==void 0?c:kt,At=(f=(h=U.getAttribute("codecs"))!==null&&h!==void 0?h:Ir)!==null&&f!==void 0?f:"",Ne=(m=(p=U.getAttribute("contentType"))!==null&&p!==void 0?p:be==null?void 0:be.split("/")[0])!==null&&m!==void 0?m:Hi,qt=(S=(g=oe.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&S!==void 0?S:[],Wt=parseInt((v=U.getAttribute("width"))!==null&&v!==void 0?v:"",10),Yi=parseInt((y=U.getAttribute("height"))!==null&&y!==void 0?y:"",10),zi=parseInt((b=U.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,qi=(T=U.getAttribute("frameRate"))!==null&&T!==void 0?T:"",xr=(E=U.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Lr=qi?kr(qi):void 0,Nr=(P=U.getAttribute("id"))!==null&&P!==void 0?P:(_r++).toString(10),Or=Ne==="video"?`${Yi}p`:Ne==="audio"?`${zi}Kbps`:At,Br=`${Nr}@${Or}`,Mr=(L=(V=(N=U.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||V===void 0?void 0:V.trim())!==null&&L!==void 0?L:"",Wi=new URL(Mr,e).toString(),Vr=[...zt,...Rr,...qt];let Qt;const Fr=U.querySelector("SegmentBase"),ke=(B=U.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Cr;if(Fr){const Oe=(D=(M=U.querySelector("SegmentBase Initialization"))===null||M===void 0?void 0:M.getAttribute("range"))!==null&&D!==void 0?D:"",[Be,Jt]=Oe.split("-").map(Me=>parseInt(Me,10)),Ce={from:Be,to:Jt},Ze=(I=U.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Xt,wt]=Ze?Ze.split("-").map(Me=>parseInt(Me,10)):[],et=Ze?{from:Xt,to:wt}:void 0;Qt={type:We.BYTE_RANGE,url:Wi,initRange:Ce,indexRange:et}}else if(ke){const Oe={representationId:(F=U.getAttribute("id"))!==null&&F!==void 0?F:void 0,bandwidth:(R=U.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Be=parseInt((_=ke.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Jt=(O=ke.getAttribute("initialization"))!==null&&O!==void 0?O:"",Ce=ke.getAttribute("media"),Ze=(te=parseInt((z=ke.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&te!==void 0?te:1,Xt=$i(Jt,Oe);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");const wt=(ne=ke.querySelectorAll("SegmentTimeline S"))!==null&&ne!==void 0?ne:[],et=[];let Me=0,Zt="",Ve=0;if(wt.length){let Fe=Ze,he=0;for(const tt of wt){const xe=parseInt((me=tt.getAttribute("d"))!==null&&me!==void 0?me:"",10),ot=parseInt((Ie=tt.getAttribute("r"))!==null&&Ie!==void 0?Ie:"",10)||0,Pt=parseInt((Ge=tt.getAttribute("t"))!==null&&Ge!==void 0?Ge:"",10);he=Number.isFinite(Pt)?Pt:he;const Qi=xe/Be*1e3,pi=he/Be*1e3;for(let mi=0;mi<ot+1;mi++){const Dd=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:Fe.toString(10),segmentTime:(he+mi*xe).toString(10)})),Gn=(pi!=null?pi:0)+mi*Qi,Id=Gn+Qi;Fe++,et.push({time:{from:Gn,to:Id},url:Dd})}he+=(ot+1)*xe,Me+=(ot+1)*Qi}Ve=he/Be*1e3,Zt=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:Fe.toString(10),segmentTime:he.toString(10)}))}else if(a.isNonNullable($e)){const he=parseInt((q=ke.getAttribute("duration"))!==null&&q!==void 0?q:"",10)/Be*1e3,tt=Math.ceil($e/he);let xe=0;for(let ot=1;ot<tt;ot++){const Pt=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:ot.toString(10),segmentTime:xe.toString(10)}));et.push({time:{from:xe,to:xe+he},url:Pt}),xe+=he}Ve=xe,Zt=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:tt.toString(10),segmentTime:xe.toString(10)}))}const ei={time:{from:Ve,to:1/0},url:Zt};Qt={type:We.TEMPLATE,baseUrl:Wi,segmentTemplateUrl:Ce,initUrl:Xt,totalSegmentsDurationMs:Me,segments:et,nextSegmentBeyondManifest:ei,timescale:Be}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ne||!be)continue;const Kt={video:ye.VIDEO,audio:ye.AUDIO,text:ye.TEXT}[Ne];Kt&&ve[Kt].push({id:Br,kind:Kt,segmentReference:Qt,profiles:Vr,duration:$e,bitrate:zi,mime:be,codecs:At,width:Wt,height:Yi,fps:Lr,quality:xr})}}return{dynamic:Bt,liveAvailabilityStartTime:fi,duration:$e,container:Dr,representations:ve}},G0=({id:i,width:e,height:t,bitrate:s,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:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},Y0=({id:i,bitrate:e})=>({id:i,bitrate:e}),z0=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=ge(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:ge(i,-1)},q0=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),kl=i=>"size"in i,Ti=i=>i.type===We.TEMPLATE,hn=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class Al{constructor(e,t,s,r,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:d,compatibilityMode:u=!1,manifest:c}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Qe,this.destroyAbortController=new Qe,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 v=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield yield A(this.loadInit(f,"high",!0));const p=this.initData.get(f.id),m=this.segments.get(f.id),g=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 A(void 0);this.searchGaps(m,f),yield yield A(this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(g)})}.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 A(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 A(this.loadInit(f,"high",!1)):m instanceof Promise&&(yield yield A(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 A(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield yield A(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const g=this.getCurrentPosition();a.isNonNullable(g)&&(p.forEach(S=>S.status=j.NONE),this.pruneBuffer(g,1/0,!0),this.maintain(g))})}.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 A(void 0);for(const y of this.representations.keys()){const b=h.find(P=>P.id===y);b&&this.representations.set(y,b);const T=this.representations.get(y);if(!T||!Ti(T.segmentReference))return yield A(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 g=this.segments.get(p);a.assertNonNullable(g,"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 A(void 0);const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield yield A(this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal))),this.searchGaps(g,m),yield yield A(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=s,s){case xi.MP4:this.containerParser=N0;break;case xi.WEBM:this.containerParser=j0;break;default:a.assertNever(s)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Qe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Le(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=Le(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=ge(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===j.FED&&!l.length&&Le(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=ge(s,-1);d&&d.status===j.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:n.time.from+r}),s=n.time.to;a.isNonNullable(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let n=0,o=t.length-1;do r.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<s&&o>=0);return this.liveInitialAdditionalOffset=n-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Ti(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:j.NONE,size:void 0})),d=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(r=ge(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.floor(u)>=Math.floor(h.time.from)&&Math.floor(u)<=Math.floor(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!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(s.id))!==null&&t!==void 0?t:[],d=l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));d&&(d.time.to=e.segment.time.to),!!l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||l.push({status:j.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const g=f<=s&&p>=s,S=f>s||g||m===0&&s===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+v||p<=s+v;return(h===j.NONE||h===j.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!Ri(this.sourceBuffer.buffered,s))&&S&&y});if(r===-1)return[];if(t!==We.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===j.NONE||f.status===j.PARTIALLY_EJECTED)d.push(f);else break}return d}loadSegments(e,t,s="auto"){return H(this,void 0,void 0,function*(){t.segmentReference.type===We.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="auto"){return H(this,void 0,void 0,function*(){e.status=j.DOWNLOADING;const r={segment:e,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id};this.activeSegments.add(r);const{range:n,url:o,signal:l,onProgress:d}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(yield a.abortable(l,function(){return Z(this,arguments,function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield A(new Promise(c=>setTimeout(c,u)))})}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const u=yield this.fetcher.fetch(o,{range:n,signal:l,onProgress:d,priority:s,isLowLatency:this.isActiveLowLatency()});if(!u)return;const c=new DataView(u);if(this.isActiveLowLatency()){const h=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(c,h)}d&&r.feedingBytes?r.segment.status=j.DOWNLOADED:this.sourceBufferTaskQueue.append(c,l).then(h=>{this.onSegmentFullyAppended(r,t.id)}),this.failedDownloads=0}catch(u){if(!hn(u))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(u)}})}loadByteRangeSegments(e,t,s="auto"){return H(this,void 0,void 0,function*(){if(!e.length)return;for(const d of e)d.status=j.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 A(new Promise(u=>setTimeout(u,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(n,{range:r,onProgress:l,signal:o,priority:s}),this.failedDownloads=0}catch(d){if(!hn(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 s=t.segmentReference.url,r={from:ge(e,0).byte.from,to:ge(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:s,range:r,signal:n,onProgress:(d,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ti(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl).toString(),{signal:r}=this.downloadAbortController,n=()=>{this.abort()},l=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(d,u)=>{if(!r.aborted)try{this.onSomeTemplateDataLoaded({dataView:d,loaded:u,signal:r,onSegmentAppendFailed:n,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}:void 0;return{url:s,signal:r,onProgress:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=Le((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:n}){if(!this.activeSegments.size)return;const o=this.representations.get(t);if(o)for(const l of this.activeSegments){const{segment:d}=l;if(l.representationId===t){if(n.aborted){r();continue}if(l.loadedBytes=s,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u);c!=null&&c.byteLength&&(d.status=j.PARTIALLY_FED,l.feedingBytes+=c.byteLength,this.sourceBufferTaskQueue.append(c).then(h=>{l.fedBytes+=c.byteLength,d.status===j.DOWNLOADED&&this.onSegmentFullyAppended(l,o.id)}))}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const d=l.segmentReference.type,u=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===We.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const g=f?h.byte.from-s:0,S=f?h.byte.to-s:e.byteLength,v=g<r,y=S<=r;if(h.status===j.DOWNLOADING&&v&&y){h.status=j.DOWNLOADED;const b=new DataView(e.buffer,e.byteOffset+g,p);this.sourceBufferTaskQueue.append(b,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(c,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(c.loadedBytes=Math.min(p,r-g),c.loadedBytes>c.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===p?b:this.containerParser.parseFeedableSegmentChunk(b);T!=null&&T.byteLength&&(h.status=j.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 s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=j.FED,kl(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const n of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])n.status===j.FED&&n.time.from===e.segment.time.from&&n.time.to===e.segment.time.to&&(n.status=j.NONE);this.isActiveLowLatency()&&this.updateLowLatencyLive(e),this.activeSegments.delete(e),this.detectGapsWhenIdle(t,[e.segment])}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.NONE;for(const s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=rr(()=>Ss(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return H(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Z(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield A(new Promise(d=>setTimeout(d,l)))})}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(l=>H(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),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,s=!1){return H(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=kl(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===j.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===j.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const p of f)if(p.status===j.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===j.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1})}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:n})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:n}=r;if(n!==j.FED&&n!==j.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=j.PARTIALLY_EJECTED:r.status=j.NONE)}}}var _i;(function(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(_i||(_i={}));class W0{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Qe,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 A(li(n,{signal:this.abortAllController.signal}).catch(Zi));return o?(this.onHeadersReceived(o.headers),yield A(o.text())):yield A(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 g=new Headers;if(o)switch(n){case _i.HEADER:{g.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,v;if(u){const I=new Qe;if(v=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{I.abort()}catch(F){Zi(F)}}),this.abortAllController.signal.aborted||u.aborted)try{I.abort()}catch(F){Zi(F)}S=I.signal}const y=a.now(),b=yield yield A(li(m,{priority:d,headers:g,signal:S}).catch(Zi)),T=a.now();if(!b)return v==null||v.unsubscribe(),yield A(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!b.ok||!b.body)return v==null||v.unsubscribe(),yield A(Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`)));if(this.onHeadersReceived(b.headers),!l&&!c)return v==null||v.unsubscribe(),yield A(b.arrayBuffer());const[E,P]=b.body.tee(),N=E.getReader();c&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(P,h));let V=0,L=new Uint8Array(0),B=!1;const M=I=>{v==null||v.unsubscribe(),B=!0,Zi(I)},D=a.abortable(S,function({done:I,value:F}){return Z(this,arguments,function*(){if(V===0&&this.lastRequestFirstBytes$.next(a.now()-y),S.aborted)return v==null||v.unsubscribe(),yield A(void 0);if(!I&&F){const R=new Uint8Array(L.length+F.length);R.set(L),R.set(F,L.length),L=R,V+=F.byteLength,l==null||l(new DataView(L.buffer),V),yield yield A(N==null?void 0:N.read().then(D,M))}})}.bind(this));return yield yield A(N==null?void 0:N.read().then(D,M)),v==null||v.unsubscribe(),yield A(B?null:L.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return Z(this,arguments,function*(){if(r.type!==We.BYTE_RANGE)return yield A(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 g=yield yield A(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!g)return yield A(null);const S=new DataView(g,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const v=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let b;if(f)b=new DataView(g,y.from-c,y.to-y.from+1);else{const E=yield yield A(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!E)return yield A(null);b=new DataView(E)}const T=n.parseSegments(b,v,y);return yield A({init:v,dataView:new DataView(g),segments:T})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return Z(this,arguments,function*(){if(r.type!==We.TEMPLATE)return yield A(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield A(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield A(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:j.NONE,size:void 0}));return yield A({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Fn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,n;return H(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case We.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case We.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Zi=i=>{if(!hn(i))throw i},fn=1e3,cr=(i,e,t)=>t*e+(1-t)*i,$d=(i,e)=>i.reduce((t,s)=>t+s,0)/e,Q0=(i,e,t,s)=>{let r=0,n=t;const o=$d(i,e),l=e<s?e:s;for(let d=0;d<l;d++)i[n]>o?r++:r--,n=(i.length+n-1)%i.length;return Math.abs(r)===l};class Hn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ct(`raw_${s}`),this.smoothedSeries$=new ct(`smoothed_${s}`),this.reportedSeries$=new ct(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class K0 extends Hn{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 Hn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=$d(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const s=Q0(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class X0 extends Hn{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 pn{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new K0({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new J0({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new X0(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const Z0=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},wl=["timeupdate","progress","play","seeked","stalled","waiting"];var ze;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(ze||(ze={}));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(ze.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.forceEnded$=new a.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Qe,this.initManifest=a.abortable(this.destroyController.signal,function(t,s,r){var n;return Z(this,arguments,function*(){this.element=t,this.manifestUrlString=Pe(s,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ze.MANIFEST_READY),this.manifest=yield yield A(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(ze.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 s=yield yield A(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!s)return yield A(this.manifest);let r;try{r=H0(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return yield A(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===ye.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 A(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,s){return Z(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ze.REPRESENTATIOS_READY),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(ye.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new Al(ye.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(fn).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=Pe(this.manifestUrlString,u+fn,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...wl.map(l=>a.fromEvent(this.element,l))).pipe(a.map(l=>this.element?Le(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(l=>!!l)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(a.filter(d=>this.isActiveLowLatency&&!!d)).subscribe(d=>this.liveEstimatedDelay.next(d))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(d=>{if(!this.isActiveLowLatency)return;const u=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,f=d-u;let p=1+Math.sign(f)*h;Math.abs(f)<c?p=1:Math.abs(f)>c*2&&(p=1+Math.sign(f)*h*2),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 g,S;return(S=(g=m.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.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})=>H(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,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,S=this.isActiveLowLatency?u:d;let v=dt.None;if(this.isActiveLowLatency?v=dt.ActiveLowLatency:S<p+g&&S>=p?v=dt.LiveWithTargetOffset:h!==0&&S<p&&(v=dt.LiveForwardBuffering),isFinite(d)&&(l=d>l?d:l),v===dt.LiveForwardBuffering||v===dt.LiveWithTargetOffset){const y=l-(p+m),b=Math.trunc(h+y/c);let T;d?b>0?T=b:T=0:T=h,this.manifestUrlString=Pe(this.manifestUrlString,T,ae.DASH_CMAF_OFFSET_P)}v!==dt.None&&v!==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 A(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield A(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield A(this.videoBufferManager.startWith(t)),this.state$.setState(ze.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new W0({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=pn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator))}seekLive(e){var t,s,r,n;return H(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.manifestUrlString=Pe(this.manifestUrlString,e,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(ze.RUNNING),this.subscription.add(a.merge(...wl.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.tick()}switchRepresentation(e,t){return H(this,void 0,void 0,function*(){const s={[ye.VIDEO]:this.videoBufferManager,[ye.AUDIO]:this.audioBufferManager,[ye.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),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(ze.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}updateLive(){var e;return H(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isLive$.getValue()&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class kd{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 rd,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ue.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==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),w(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),w(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&&w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var s,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=bt(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(_e(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,s=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:s,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ue.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(f.video).sort((v,y)=>y.bitrate-v.bitrate),g=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const v of p){const y=Y0(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=G0(v);if(y){h.push({track:y,representation:v});const b=!this.params.tuning.isAudioDisabled&&z0(p,m,v);b&&this.audioRepresentations.set(v.id,b)}}this.videoTracks$.next(h);for(const v of g){const y=q0(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(h.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));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(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!==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,s,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=Le(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),g=Math.max(c&&!d&&(r=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.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:g,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=d?S!=null?S:c:c!=null?c:S;return v&&((l=this.videoTracks$.getValue().find(({track:y})=>y===v))===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),w(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),gt(this.video)}}class tT extends kd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let iT=class extends gd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(dn),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(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===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 kd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(fn),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(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===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(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const es=(i,e)=>new a.Observable(t=>{const s=(r,n)=>t.next(n);return i.on(e,s),()=>i.off(e,s)});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(),s=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),s){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),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case X.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(s)}},this.video=bt(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(_e(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),gt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ss(import("hls.js").then(r=>{e||(ut.Hls=r.default,ut.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),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,s=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,s));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ht(this.video,e.isLooped,s)),this.subscription.add(vt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Lt(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(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),w(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s)),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:g,height:S}=h,v=(p=Mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:g,height:S});if(!v)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,b={id:m.toString(),quality:v,bitrate:h.bitrate/1e3,size:{width:g,height:S},fps:y};return this.trackLevels.set(m,{track:b,level:h}),c.push(b),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,g="internal";c.push({id:f,url:p,language:m,type:g})}e.internalTextTracks.startTransitionTo(c)}}),n(es(this.hls,ut.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>_e(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:s}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=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$,s),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:s})),n(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(X.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return H(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),w(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),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Pl="X-Playback-Duration";var _l=i=>H(void 0,void 0,void 0,function*(){var e;const t=yield li(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(Pl)?parseInt(t.headers.get(Pl),10):void 0});const aT=i=>{let e=null;if(i.QUALITY&&(e=Mi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=a.videoSizeToQuality({width:t,height:s})}return e!=null?e:null},Ad=(i,e=i)=>H(void 0,void 0,void 0,function*(){var t,s;const o=(yield(yield li(i)).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}`,g=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 v=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 b=new URL(o[++u],e).toString();g&&l.push({id:m,quality:g,url:b,bandwidth:S,size:y,fps:v})}if(f){const p=ni(f[1].split(",").map(v=>v.split("=")).map(([v,y])=>[v,y.replace(/^"|"$/g,"")])),m=(s=p.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),g=p.LANGUAGE,S=p.NAME;m&&g&&d.push({type:"internal",id:g,label:S,language:g,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}}),hr=(i,e)=>{const t=a.isNullable(e)||a.isNonNullable(e.min)&&a.isNonNullable(e.max)&&a.isLower(e.max,e.min),s=a.isNonNullable(i)&&i!==a.VideoQuality.INVARIANT;return t||s&&(a.isNullable(e==null?void 0:e.min)||a.isHigherOrEqual(i,e==null?void 0:e.min))&&(a.isNullable(e==null?void 0:e.max)||a.isLowerOrEqual(i,e==null?void 0:e.max))};var ie;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.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();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),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.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&&c.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:n===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),w(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&&w(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 h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(w(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=bt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},Ad(Pe(this.params.source.url),this.params.source.url).then(({qualityManifests:s})=>{this.allManifests=[...s];const r=this.params.desiredState.autoVideoTrackLimits.getState();this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:n})=>hr(n,r))])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(_e(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,n=s.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo(this.masterManifest),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,s));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.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(_e(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)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},s)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),s)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s)),this.subscription.add(t.autoVideoTrackLimits.stateChangeStarted$.subscribe(l=>{const d=l.to;this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:u})=>hr(u,d))]),this.params.output.autoVideoTrackLimits$.next(l.to)}));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?ae.DASH_CMAF_OFFSET_P:ae.OFFSET_P,s=Pe(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",s),this.video.load(),_l(s).then(r=>{var n;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const o=(n=this.params.source.maxSeekBackTime)!==null&&n!==void 0?n:this.maxSeekBackTime$.getValue();if(a.isNullable(o)||!isFinite(o))try{li(s).then(l=>l.text()).then(l=>{var d;const u=(d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l))===null||d===void 0?void 0:d[1];if(u){const c=new URL(u,s).toString();_l(c).then(h=>{a.isNullable(h)||this.maxSeekBackTime$.next(h)})}})}catch(l){}}})}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.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 s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===exports.PlaybackState.STOPPED){s!==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),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===Y.Requested&&this.seek(u.position),s){case re.READY:r===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(re.PAUSED),w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=bt(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(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ad(this.params.source.url).then(({qualityManifests:t,textTracks:s})=>{this.allManifests=[...t];const r=this.params.desiredState.autoVideoTrackLimits.getState();this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:n})=>hr(n,r))]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},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;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,n=s.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo(this.masterManifest),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=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,s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s).add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.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(_e(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)},s))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s)),this.subscription.add(t.autoVideoTrackLimits.stateChangeStarted$.subscribe(l=>{const d=l.to;this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:u})=>hr(u,d))]),this.params.output.autoVideoTrackLimits$.next(l.to)})),!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"},s))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),w(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(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.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,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==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),w(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=(s=this.trackUrls[c.to.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===Y.Requested&&this.seek(h.position),n){case de.READY:o===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(de.PAUSED),w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ht(this.video,t.isLooped,s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),gt(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:s}=this.trackUrls[t];a.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Ut(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(_e(s))}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const d=(s=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||s===void 0?void 0:s.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 Dl=["stun:videostun.mycdn.me:80"],uT=1e3,dT=3,_a=()=>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=_a,this.externalStopCallback=_a,this.externalErrorCallback=_a,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return H(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 H(this,void 0,void 0,function*(){try{const e={iceServers:[{urls:Dl}]};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 H(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 H(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 H(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 H(this,void 0,void 0,function*(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=yield this.peerConnection.createOffer(e),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),uT)}normalizeOptions(e={}){const t={stunServerList:Dl,maxRetryNumber:dT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.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(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===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),w(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:s===exports.PlaybackState.PAUSED?(this.videoState.setState(se.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case se.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&w(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=bt(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),gt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const r=St(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,s));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===se.READY&&this.videoState.setState(se.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(vt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).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)}},s)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(_e(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,w(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),w(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 Il{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 Da,Ia,Ra,Ca,xa,La,Fs,Na,Us,Oa,js,Ba,Hs,Ma,Gs,Va,Ys,Fa;const wd=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"',Pd='video/webm; codecs="vp09.00.10.08"',_d='video/webm; codecs="av01.0.00M.08"',mT='audio/mp4; codecs="mp4a.40.2"',vT='audio/webm; codecs="opus"',it={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Ia=(Da=window.SourceBuffer)===null||Da===void 0?void 0:Da.prototype)===null||Ia===void 0)&&Ia.appendBuffer)),hls:!!(!((Ra=Vt.canPlayType)===null||Ra===void 0)&&Ra.call(Vt,"application/x-mpegurl")||!((Ca=Vt.canPlayType)===null||Ca===void 0)&&Ca.call(Vt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ue={mp4:!!(!((xa=Vt.canPlayType)===null||xa===void 0)&&xa.call(Vt,"video/mp4")),webm:!!(!((La=Vt.canPlayType)===null||La===void 0)&&La.call(Vt,"video/webm")),cmaf:!0},pt={h264:!!(!((Na=(Fs=window.MediaSource)===null||Fs===void 0?void 0:Fs.isTypeSupported)===null||Na===void 0)&&Na.call(Fs,fT)),h265:!!(!((Oa=(Us=window.MediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||Oa===void 0)&&Oa.call(Us,pT)),vp9:!!(!((Ba=(js=window.MediaSource)===null||js===void 0?void 0:js.isTypeSupported)===null||Ba===void 0)&&Ba.call(js,Pd)),av1:!!(!((Ma=(Hs=window.MediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||Ma===void 0)&&Ma.call(Hs,_d)),aac:!!(!((Va=(Gs=window.MediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||Va===void 0)&&Va.call(Gs,mT)),opus:!!(!((Fa=(Ys=window.MediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||Fa===void 0)&&Fa.call(Ys,vT))},Ei=(pt.h264||pt.h265)&&pt.aac;var Mt;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Mt||(Mt={}));var It;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(It||(It={}));let ii;const bT=()=>H(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:_d})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Pd})}))]);ii={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{bT()}catch(i){console.error(i)}const ds=it.hls&&Ue.mp4,gT=()=>Object.keys(pt).filter(i=>pt[i]),ST=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.DASH_SEP:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.DASH_WEBM:return it.mse&&Ue.webm&&pt.vp9&&pt.opus;case exports.VideoFormat.DASH_WEBM_AV1:return it.mse&&Ue.webm&&pt.av1&&pt.opus;case exports.VideoFormat.DASH_LIVE:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.DASH_LIVE_CMAF:return it.mse&&Ue.mp4&&Ei&&Ue.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ds||e&&it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ds;case exports.VideoFormat.MPEG:return Ue.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return it.webrtc&&it.ws&&pt.h264&&(Ue.mp4||Ue.webm);default:return a.assertNever(t)}}),ts=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){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(i)}return[e,t]},yT=({webmCodec:i,androidPreferredFormat:e})=>{if(wd)switch(e){case It.MPEG:return[exports.VideoFormat.MPEG,...ts(i),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(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case It.DASH:return[...ts(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return ds?[...ts(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...ts(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},TT=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=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=[...s,...r],o=[...r,...s];let l;if(wd)switch(i){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]},Rl=i=>i?[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=i=>new a.Observable(e=>{const t=new a.Subscription,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(s.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const $T={cacheDuration:12e4},kT={chunkDuration:5e3,maxParallelRequests:5};class AT{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).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let n=[];s?n=[s]:r.length?n=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Il(n);const o=[...Rl(!0),...Rl(!1)];this.chromecastFormatsIterator=new Il(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new AS(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 dl(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 dl(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:s,source:l,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Rg({connection:l,meta:n,container:s,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?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 s=r=>{const n=new URL(r);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return ni(Object.entries(e).map(([r,n])=>[r,s(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,s=0;return e.add(a.merge(this.providerOutput.error$,ET({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(r=>({id:`ProviderHangup:${r}`,category:a.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const n=this.current$.getValue().destination;if(n===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=r.category===a.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:Ae.SCREEN)}})),e}}const wT=5e3,Cl="one_video_throughput",xl="one_video_rtt",Rt=window.navigator.connection,Ll=()=>{const i=Rt==null?void 0:Rt.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},Nl=()=>{const i=Rt==null?void 0:Rt.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},Ol=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class ns{constructor(e){var t,s;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ns.load(Cl)||(e.useBrowserEstimation?Ll():void 0)||wT,n=(s=(t=ns.load(xl))!==null&&t!==void 0?t:e.useBrowserEstimation?Nl():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Ol(r,n,e.rttPenaltyRequestSize)),this.throughput=pn.getSmoothedValue(r,-1,e),this.rtt=pn.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Ll();d&&this.throughput.next(d);const u=Nl();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(Cl,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})=>Ol(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=a.now();const r=new a.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,s=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=a.now()}));break}r.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-s;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,n=a.now(),o=0,l=a.now();const d=c=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=({done:c,value:h})=>H(this,void 0,void 0,function*(){c?(!t&&this.addRawSpeed(r,a.now()-n,1),this.concurrentDownloads.delete(e)):h&&(t?(a.now()-l<this.tuningConfig.lowLatency.continuesByteSequenceInterval&&a.now()-n<this.tuningConfig.lowLatency.separateByteSequenceInterval?o+=h.byteLength:(this.addRawSpeed(o,a.now()-n,this.concurrentDownloads.size,t),o=h.byteLength,n=a.now()),l=a.now()):(r+=h.byteLength,o+=h.byteLength,o>=this.tuningConfig.streamMinSampleSize&&a.now()-l>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(o,a.now()-l,this.concurrentDownloads.size),o=0,l=a.now())),yield s==null?void 0:s.read().then(u,d))});this.concurrentDownloads.add(e),s==null||s.read().then(u,d)}addRawSpeed(e,t,s=1,r=!1){if(r||ns.sanityCheck(e,t)){const n=e*8/t;this.throughput.next(n*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const s=e*8/t;return!(!s||!isFinite(s)||s>1e6||s<30||e<10*1024||t<=20)}static load(e){var t;const s=a.safeStorage.get(e);if(a.isNonNullable(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Bl={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:5,separateByteSequenceInterval:100}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,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,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!0,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Mt.VP9,androidPreferredFormat:It.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},PT=i=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(i,Bl)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Bl.configName]})};var Ml=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===Y.None))),_T=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const DT=(i,e,t,s)=>{i!==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(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};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,s,r)=>{const n=Reflect.get(t,s,r);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(s)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=_T(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new AT({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state: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(s=>s.length>0),a.once()).subscribe(s=>{this.setVideoTrackIdByQuality(s,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 s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return DT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),n=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return a.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===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:Ml({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(Ml({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>s.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,s).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||s.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(s=>s.length>0),a.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:n})=>n===r),s||this.setAutoQuality(!0)),s||(s=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(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.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),Zg(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Xg(s)),this.providerContainer.current$.subscribe(({type:s})=>Os("provider",s)),t.duration$.subscribe(s=>Os("duration",s)),t.availableVideoTracks$.pipe(a.filter(s=>!!s.length),a.once()).subscribe(s=>Os("tracks",s)),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(s=>s==null?void 0:s.quality)).subscribe(new ct("quality")),this.info.currentBuffer$.subscribe(new ct("buffer")),t.isBuffering$.subscribe(new ct("isBuffering"))].forEach(s=>this.subscription.add(s)),Os("codecs",gT())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>H(this,void 0,void 0,function*(){t(),e=yield window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(r)})})});this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);r&&n?o||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const RT=`@vkontakte/videoplayer-core@${Vl}`;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=Vl;
|
|
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,s){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=s,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new s0(this.params.fov,this.params.orientation),this.cameraRotationManager=new r0(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),s=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(s),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(s,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(s),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const s=this.gl.createShader(t);if(!s)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(s,e),this.gl.compileShader(s),!this.gl.getShaderParameter(s,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(s));return s}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(a0,this.gl.VERTEX_SHADER),s=this.createShader(n0,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,s),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,s=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:s=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-s,t,-s,t,s,-t,s]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,s=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,n=e-s,o=t-r,l=e+s,d=t-r,u=e+s,c=t+r,h=e-s,f=t+r;return[n,o,l,d,u,c,h,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let gd=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 rd,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==le.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==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),w(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),w(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&&w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var s,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=bt(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(_e(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new i0({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=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:s,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(le.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(le.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===le.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Ye.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(f.video).sort((v,y)=>y.bitrate-v.bitrate),g=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const v of p){const y=cy(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=dy(v);if(y){h.push({track:y,representation:v});const b=!this.params.tuning.isAudioDisabled&&hy(p,m,v);b&&this.audioRepresentations.set(v.id,b)}}this.videoTracks$.next(h);for(const v of g){const y=fy(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(h.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));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===Ye.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!==Ye.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(Se.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(Se.AUDIO,p.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,s,r,n,o,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=Le(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),g=Math.max(c&&!d&&(r=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.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:g,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=d?S!=null?S:c:c!=null?c:S;return v&&((l=this.videoTracks$.getValue().find(({track:y})=>y===v))===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),w(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),gt(this.video)}},o0=class extends gd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ye;(function(i){i.VIDEO="video",i.AUDIO="audio",i.TEXT="text"})(ye||(ye={}));var dt;(function(i){i[i.ActiveLowLatency=0]="ActiveLowLatency",i[i.LiveWithTargetOffset=1]="LiveWithTargetOffset",i[i.LiveForwardBuffering=2]="LiveForwardBuffering",i[i.None=3]="None"})(dt||(dt={}));var lr;(function(i){i.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",i.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(lr||(lr={}));var We;(function(i){i.BYTE_RANGE="byteRange",i.TEMPLATE="template"})(We||(We={}));var G;(function(i){i.NONE="none",i.DOWNLOADING="downloading",i.DOWNLOADED="downloaded",i.PARTIALLY_FED="partially_fed",i.PARTIALLY_EJECTED="partially_ejected",i.FED="fed"})(G||(G={}));var xi;(function(i){i.MP4="mp4",i.WEBM="webm"})(xi||(xi={}));var ur;(function(i){i[i.RECTANGULAR=0]="RECTANGULAR",i[i.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",i[i.CUBEMAP=2]="CUBEMAP",i[i.MESH=3]="MESH"})(ur||(ur={}));var ue;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(ue||(ue={}));var wa,Pa;let Sd=!1;try{Sd=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Pa=(wa=navigator.userAgent.match(/Version\/(\d+)/))===null||wa===void 0?void 0:wa[1])!==null&&Pa!==void 0?Pa:"",10)<16}catch(i){console.error(i)}class l0{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const s=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!s),this.currentTask=null}this.queue.length&&this.pull()}catch(s){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:s})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}append(e,t){return F(this,void 0,void 0,function*(){return t&&t.aborted?!1:new Promise(s=>{const r={operation:"append",data:e,signal:t,callback:s};this.queue.push(r),this.pull()})})}remove(e,t,s){return F(this,void 0,void 0,function*(){return s&&s.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:s,callback:r};this.queue.unshift(n),this.pull()})})}abort(e){return F(this,void 0,void 0,function*(){return new Promise(t=>{let s;Sd&&e?s={operation:"safariAbort",init:e,callback:t}:s={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);s&&(this.queue=[s]),this.pull()})})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:s}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&s==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${s}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}class Xe{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 yd extends Xe{}class u0 extends Xe{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const s=this.readString(4);this.compatibleBrands.push(s),t-=4}}}class d0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class c0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class h0 extends Xe{constructor(e){super(e),this.data=this.content}}class Ot extends Xe{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class f0 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 s=this.readUint32();const r=s>>>31,n=s<<1>>>1,o=this.readUint32();s=this.readUint32();const l=s>>>28,d=s<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class p0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class m0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}var ai;(function(i){i[i.MONOSCOPIC=0]="MONOSCOPIC",i[i.TOP_BOTTOM=1]="TOP_BOTTOM",i[i.LEFT_RIGHT=2]="LEFT_RIGHT",i[i.STEREO_CUSTOM=3]="STEREO_CUSTOM",i[i.RIGHT_LEFT=4]="RIGHT_LEFT"})(ai||(ai={}));class v0 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 b0 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 S0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class y0 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 T0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class E0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class $0 extends Ot{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class k0 extends Xe{parseChildrenBoxes(){return Gt(this.content)}}class A0 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 P0 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 _0={ftyp:u0,moov:d0,moof:c0,mdat:h0,sidx:f0,trak:p0,mdia:S0,mfhd:$0,tkhd:y0,traf:k0,tfhd:A0,tfdt:w0,trun:P0,minf:T0,sv3d:m0,st3d:v0,prhd:b0,proj:E0,equi:g0,unknown:yd};class D0{createBox(e,t){const s=_0[e];return s?new s(t):new yd(t)}createFromView(e){const s=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Pr.createBox(s,new DataView(e.buffer,e.byteOffset))}}const Pr=new D0;function ss(i,e){const t=new Uint8Array(i.buffer),s=e.split("").map(o=>o.charCodeAt(0));let r=i.byteOffset,n=[];for(;r<t.byteLength;){if(t[r]===s[n.length]?n.push(t[r]):n=[],n.length===4){const l=new DataView(i.buffer,r-7,4).getUint32(0);return r-7+l>i.buffer.byteLength?null:Pr.createBox(e,new DataView(i.buffer,r-7))}r++}return null}function cn(i,e){const t=[];let s=i.byteOffset;for(;s<i.buffer.byteLength;){const r=ss(new DataView(i.buffer,s,i.buffer.byteLength-s),e);if(r)t.push(r),s=r.source.byteOffset+r.size;else break}return t}function Gt(i){const e=[];let t=0;for(;t<i.byteLength;){const s=Pr.createFromView(new DataView(i.buffer,i.byteOffset+t));if(e.push(s),!s.size)break;t+=s.size}return e}const I0=new TextDecoder("ascii"),R0=i=>I0.decode(new DataView(i.buffer,i.byteOffset+4,4))==="ftyp",C0=i=>{const e=Pr.createFromView(i);let t=e.earliestPresentationTime/e.timescale*1e3,s=i.byteOffset+i.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:G.NONE,time:{from:t,to:t+o},byte:{from:s,to:s+n.referencedSize-1}};return t+=o,s+=n.referencedSize,l})},x0=i=>{const e=cn(i,"mdat"),t=cn(i,"moof");if(!(e.length&&t.length))return null;const s=t[0],r=e[e.length-1],n=s.source.byteOffset,l=r.source.byteOffset-s.source.byteOffset+r.size;return new DataView(i.buffer,n,l)},L0=(i,e)=>{const t=cn(i,"traf"),s=t[t.length-1].children.find(d=>d.type==="tfhd"),r=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,u)=>d+u,0):o=s.defaultSampleDuration*n.sampleCount,(Number(r.baseMediaDecodeTime)+o)/e*1e3},N0=i=>{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(i,"sv3d")){e.is3dVideo=!0;const s=ss(i,"st3d");s&&(e.stereoMode=s.stereoMode);const r=ss(i,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=ss(i,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},O0={validateData:R0,parseInit:N0,getIndexRange:()=>{},parseSegments:C0,parseFeedableSegmentChunk:x0,getSegmentEndTime:L0};var k;(function(i){i[i.EBML=440786851]="EBML",i[i.EBMLVersion=17030]="EBMLVersion",i[i.EBMLReadVersion=17143]="EBMLReadVersion",i[i.EBMLMaxIDLength=17138]="EBMLMaxIDLength",i[i.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",i[i.DocType=17026]="DocType",i[i.DocTypeVersion=17031]="DocTypeVersion",i[i.DocTypeReadVersion=17029]="DocTypeReadVersion",i[i.Void=236]="Void",i[i.Segment=408125543]="Segment",i[i.SeekHead=290298740]="SeekHead",i[i.Seek=19899]="Seek",i[i.SeekID=21419]="SeekID",i[i.SeekPosition=21420]="SeekPosition",i[i.Info=357149030]="Info",i[i.TimestampScale=2807729]="TimestampScale",i[i.Duration=17545]="Duration",i[i.Tracks=374648427]="Tracks",i[i.TrackEntry=174]="TrackEntry",i[i.Video=224]="Video",i[i.Projection=30320]="Projection",i[i.ProjectionType=30321]="ProjectionType",i[i.ProjectionPrivate=30322]="ProjectionPrivate",i[i.Chapters=272869232]="Chapters",i[i.Cluster=524531317]="Cluster",i[i.Timestamp=231]="Timestamp",i[i.SilentTracks=22612]="SilentTracks",i[i.SilentTrackNumber=22743]="SilentTrackNumber",i[i.Position=167]="Position",i[i.PrevSize=171]="PrevSize",i[i.SimpleBlock=163]="SimpleBlock",i[i.BlockGroup=160]="BlockGroup",i[i.EncryptedBlock=175]="EncryptedBlock",i[i.Attachments=423732329]="Attachments",i[i.Tags=307544935]="Tags",i[i.Cues=475249515]="Cues",i[i.CuePoint=187]="CuePoint",i[i.CueTime=179]="CueTime",i[i.CueTrackPositions=183]="CueTrackPositions",i[i.CueTrack=247]="CueTrack",i[i.CueClusterPosition=241]="CueClusterPosition",i[i.CueRelativePosition=240]="CueRelativePosition",i[i.CueDuration=178]="CueDuration",i[i.CueBlockNumber=21368]="CueBlockNumber",i[i.CueCodecState=234]="CueCodecState",i[i.CueReference=219]="CueReference",i[i.CueRefTime=150]="CueRefTime"})(k||(k={}));var x;(function(i){i.SignedInteger="int",i.UnsignedInteger="uint",i.Float="float",i.String="string",i.UTF8="utf8",i.Date="date",i.Master="master",i.Binary="binary"})(x||(x={}));const El={[k.EBML]:{type:x.Master},[k.EBMLVersion]:{type:x.UnsignedInteger},[k.EBMLReadVersion]:{type:x.UnsignedInteger},[k.EBMLMaxIDLength]:{type:x.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:x.UnsignedInteger},[k.DocType]:{type:x.String},[k.DocTypeVersion]:{type:x.UnsignedInteger},[k.DocTypeReadVersion]:{type:x.UnsignedInteger},[k.Void]:{type:x.Binary},[k.Segment]:{type:x.Master},[k.SeekHead]:{type:x.Master},[k.Seek]:{type:x.Master},[k.SeekID]:{type:x.Binary},[k.SeekPosition]:{type:x.UnsignedInteger},[k.Info]:{type:x.Master},[k.TimestampScale]:{type:x.UnsignedInteger},[k.Duration]:{type:x.Float},[k.Tracks]:{type:x.Master},[k.TrackEntry]:{type:x.Master},[k.Video]:{type:x.Master},[k.Projection]:{type:x.Master},[k.ProjectionType]:{type:x.UnsignedInteger},[k.ProjectionPrivate]:{type:x.Master},[k.Chapters]:{type:x.Master},[k.Cluster]:{type:x.Master},[k.Timestamp]:{type:x.UnsignedInteger},[k.SilentTracks]:{type:x.Master},[k.SilentTrackNumber]:{type:x.UnsignedInteger},[k.Position]:{type:x.UnsignedInteger},[k.PrevSize]:{type:x.UnsignedInteger},[k.SimpleBlock]:{type:x.Binary},[k.BlockGroup]:{type:x.Master},[k.EncryptedBlock]:{type:x.Binary},[k.Attachments]:{type:x.Master},[k.Tags]:{type:x.Master},[k.Cues]:{type:x.Master},[k.CuePoint]:{type:x.Master},[k.CueTime]:{type:x.UnsignedInteger},[k.CueTrackPositions]:{type:x.Master},[k.CueTrack]:{type:x.UnsignedInteger},[k.CueClusterPosition]:{type:x.UnsignedInteger},[k.CueRelativePosition]:{type:x.UnsignedInteger},[k.CueDuration]:{type:x.UnsignedInteger},[k.CueBlockNumber]:{type:x.UnsignedInteger},[k.CueCodecState]:{type:x.UnsignedInteger},[k.CueReference]:{type:x.Master},[k.CueRefTime]:{type:x.UnsignedInteger}},Td=i=>{const e=i.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const s=dr(i,t),r=s in El,n=r?El[s].type:x.Binary,o=i.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(i.buffer,i.byteOffset+t+1,l-1),u=o&255>>l,c=dr(d),h=u*Math.pow(2,(l-1)*8)+c,f=t+l;let p;return f+h>i.byteLength?p=new DataView(i.buffer,i.byteOffset+f):p=new DataView(i.buffer,i.byteOffset+f,h),{tag:r?s:"0x"+s.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},dr=(i,e=i.byteLength)=>{switch(e){case 1:return i.getUint8(0);case 2:return i.getUint16(0);case 3:return i.getUint8(0)*Math.pow(2,16)+i.getUint16(1);case 4:return i.getUint32(0);case 5:return i.getUint8(0)*Math.pow(2,32)+i.getUint32(1);case 6:return i.getUint16(0)*Math.pow(2,32)+i.getUint32(2);case 7:{const t=i.getUint8(0)*Math.pow(2,48)+i.getUint16(1)*Math.pow(2,32)+i.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},ft=(i,e)=>{switch(e){case x.SignedInteger:return i.getInt8(0);case x.UnsignedInteger:return dr(i);case x.Float:return i.byteLength===4?i.getFloat32(0):i.getFloat64(0);case x.String:return new TextDecoder("ascii").decode(i);case x.UTF8:return new TextDecoder("utf-8").decode(i);case x.Date:return new Date(Date.UTC(2001,0)+i.getInt8(0)).getTime();case x.Master:return i;case x.Binary:return i;default:a.assertNever(e)}},Li=(i,e)=>{let t=0;for(;t<i.byteLength;){const s=new DataView(i.buffer,i.byteOffset+t),r=Td(s);if(!e(r))return;r.type===x.Master&&Li(r.value,e),t=r.value.byteOffset-i.byteOffset+r.valueSize}},B0=i=>{if(i.getUint32(0)!==k.EBML)return!1;let e,t,s;const r=Td(i);return Li(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&&(s=ft(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(s===void 0||s<=2)},Ed=[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],M0=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],V0=i=>{let e,t,s,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Li(i,({tag:f,type:p,value:m,valueSize:g})=>{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+g):f===k.Info?n=!0:f===k.SeekHead?o=!0:f===k.TimestampScale?s=ft(m,p):f===k.Duration?r=ft(m,p):f===k.SeekPosition&&u===k.Cues?d=ft(m,p):f===k.Tracks?Li(m,({tag:S,type:v,value:y})=>S===k.ProjectionType?(c=ft(y,v)===1,!1):!0):n&&o&&Ed.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),s=s!=null?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(t/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:ur.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},F0=i=>{if(a.isNullable(i.cuesSeekPosition))return;const e=i.segmentStart+i.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},U0=(i,e)=>{let t=!1,s=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Li(i,({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&&Ed.includes(l)&&(s=!0)}return!(t&&s)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status: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}}})},j0=i=>{let e=0,t=!1;try{Li(i,s=>s.tag===k.Cluster?s.tagSize<=i.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):M0.includes(s.tag)?(e+s.tagSize<=i.byteLength&&(e+=s.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(s.tag))),!0):!1)}catch(s){}return e>0&&e<=i.byteLength&&t?new DataView(i.buffer,i.byteOffset,e):null},H0={validateData:B0,parseInit:V0,getIndexRange:F0,parseSegments:U0,parseFeedableSegmentChunk:j0},$l=i=>{if(!i.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},s=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(i),r=(s==null?void 0:s[1])==="-"?-1:1,n={days:e(s==null?void 0:s[5],r),hours:e(s==null?void 0:s[6],r),minutes:e(s==null?void 0:s[7],r),seconds:e(s==null?void 0:s[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},$i=(i,e)=>{let t=i;t=or(t,"$$","$");const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(s)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=or(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},G0=(i,e)=>{var t,s,r,n,o,l,d,u,c,h,f,p,m,g,S,v,y,b,T,E,P,N,V,L,B,M,D,I,U,R,_,O,z,te,ne,me,Ie,Ge,q;const Re=new DOMParser().parseFromString(i,"application/xml"),ve={video:[],audio:[],text:[]},ce=Re.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 $e;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)$e=$l(Fi);else if(Ui){const oe=$l(Ui);a.isNonNullable(oe)&&($e=oe)}else ji&&($e=parseInt(ji,10));let _r=0;const zt=(s=(t=ce.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&s!==void 0?s:[],Dr=zt.includes(lr.WEBM_AS_IN_FFMPEG)||zt.includes(lr.WEBM_AS_IN_SPEC)?xi.WEBM:xi.MP4;for(const oe of Et){const kt=oe.getAttribute("mimeType"),Ir=oe.getAttribute("codecs"),Hi=(r=oe.getAttribute("contentType"))!==null&&r!==void 0?r:kt==null?void 0:kt.split("/")[0],Rr=(o=(n=oe.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Gi=oe.querySelectorAll("Representation"),Cr=oe.querySelector("SegmentTemplate");if(Hi===ye.TEXT){for(const j of Gi){const be=j.getAttribute("id")||"",At=oe.getAttribute("lang"),Ne=(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(Ne,e).toString(),Wt=be.includes("_auto");ve[ye.TEXT].push({id:be,lang:At,isAuto:Wt,kind:ye.TEXT,url:qt})}continue}for(const j of Gi){const be=(c=j.getAttribute("mimeType"))!==null&&c!==void 0?c:kt,At=(f=(h=j.getAttribute("codecs"))!==null&&h!==void 0?h:Ir)!==null&&f!==void 0?f:"",Ne=(m=(p=j.getAttribute("contentType"))!==null&&p!==void 0?p:be==null?void 0:be.split("/")[0])!==null&&m!==void 0?m:Hi,qt=(S=(g=oe.getAttribute("profiles"))===null||g===void 0?void 0:g.split(","))!==null&&S!==void 0?S:[],Wt=parseInt((v=j.getAttribute("width"))!==null&&v!==void 0?v:"",10),Yi=parseInt((y=j.getAttribute("height"))!==null&&y!==void 0?y:"",10),zi=parseInt((b=j.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,qi=(T=j.getAttribute("frameRate"))!==null&&T!==void 0?T:"",xr=(E=j.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Lr=qi?kr(qi):void 0,Nr=(P=j.getAttribute("id"))!==null&&P!==void 0?P:(_r++).toString(10),Or=Ne==="video"?`${Yi}p`:Ne==="audio"?`${zi}Kbps`:At,Br=`${Nr}@${Or}`,Mr=(L=(V=(N=j.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||V===void 0?void 0:V.trim())!==null&&L!==void 0?L:"",Wi=new URL(Mr,e).toString(),Vr=[...zt,...Rr,...qt];let Qt;const Fr=j.querySelector("SegmentBase"),ke=(B=j.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Cr;if(Fr){const Oe=(D=(M=j.querySelector("SegmentBase Initialization"))===null||M===void 0?void 0:M.getAttribute("range"))!==null&&D!==void 0?D:"",[Be,Jt]=Oe.split("-").map(Me=>parseInt(Me,10)),Ce={from:Be,to:Jt},Ze=(I=j.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Xt,wt]=Ze?Ze.split("-").map(Me=>parseInt(Me,10)):[],et=Ze?{from:Xt,to:wt}:void 0;Qt={type:We.BYTE_RANGE,url:Wi,initRange:Ce,indexRange:et}}else if(ke){const Oe={representationId:(U=j.getAttribute("id"))!==null&&U!==void 0?U:void 0,bandwidth:(R=j.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Be=parseInt((_=ke.getAttribute("timescale"))!==null&&_!==void 0?_:"",10),Jt=(O=ke.getAttribute("initialization"))!==null&&O!==void 0?O:"",Ce=ke.getAttribute("media"),Ze=(te=parseInt((z=ke.getAttribute("startNumber"))!==null&&z!==void 0?z:"",10))!==null&&te!==void 0?te:1,Xt=$i(Jt,Oe);if(!Ce)throw new ReferenceError("No media attribute in SegmentTemplate");const wt=(ne=ke.querySelectorAll("SegmentTimeline S"))!==null&&ne!==void 0?ne:[],et=[];let Me=0,Zt="",Ve=0;if(wt.length){let Fe=Ze,he=0;for(const tt of wt){const xe=parseInt((me=tt.getAttribute("d"))!==null&&me!==void 0?me:"",10),ot=parseInt((Ie=tt.getAttribute("r"))!==null&&Ie!==void 0?Ie:"",10)||0,Pt=parseInt((Ge=tt.getAttribute("t"))!==null&&Ge!==void 0?Ge:"",10);he=Number.isFinite(Pt)?Pt:he;const Qi=xe/Be*1e3,pi=he/Be*1e3;for(let mi=0;mi<ot+1;mi++){const Dd=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:Fe.toString(10),segmentTime:(he+mi*xe).toString(10)})),Gn=(pi!=null?pi:0)+mi*Qi,Id=Gn+Qi;Fe++,et.push({time:{from:Gn,to:Id},url:Dd})}he+=(ot+1)*xe,Me+=(ot+1)*Qi}Ve=he/Be*1e3,Zt=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:Fe.toString(10),segmentTime:he.toString(10)}))}else if(a.isNonNullable($e)){const he=parseInt((q=ke.getAttribute("duration"))!==null&&q!==void 0?q:"",10)/Be*1e3,tt=Math.ceil($e/he);let xe=0;for(let ot=1;ot<tt;ot++){const Pt=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:ot.toString(10),segmentTime:xe.toString(10)}));et.push({time:{from:xe,to:xe+he},url:Pt}),xe+=he}Ve=xe,Zt=$i(Ce,Object.assign(Object.assign({},Oe),{segmentNumber:tt.toString(10),segmentTime:xe.toString(10)}))}const ei={time:{from:Ve,to:1/0},url:Zt};Qt={type:We.TEMPLATE,baseUrl:Wi,segmentTemplateUrl:Ce,initUrl:Xt,totalSegmentsDurationMs:Me,segments:et,nextSegmentBeyondManifest:ei,timescale:Be}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ne||!be)continue;const Kt={video:ye.VIDEO,audio:ye.AUDIO,text:ye.TEXT}[Ne];Kt&&ve[Kt].push({id:Br,kind:Kt,segmentReference:Qt,profiles:Vr,duration:$e,bitrate:zi,mime:be,codecs:At,width:Wt,height:Yi,fps:Lr,quality:xr})}}return{dynamic:Bt,liveAvailabilityStartTime:fi,duration:$e,container:Dr,representations:ve}},Y0=({id:i,width:e,height:t,bitrate:s,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:i,quality:l,bitrate:s,size:{width:e,height:t},fps:r}},z0=({id:i,bitrate:e})=>({id:i,bitrate:e}),q0=(i,e,t)=>{var s;const r=e.indexOf(t);return(s=ge(i,Math.round(i.length*r/e.length)))!==null&&s!==void 0?s:ge(i,-1)},W0=({id:i,lang:e,url:t,isAuto:s})=>({id:i,url:t,isAuto:s,type:"internal",language:e}),kl=i=>"size"in i,Ti=i=>i.type===We.TEMPLATE,hn=i=>i instanceof DOMException&&(i.name==="AbortError"||i.code===20);class Al{constructor(e,t,s,r,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:d,compatibilityMode:u=!1,manifest:c}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Qe,this.destroyAbortController=new Qe,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 l0(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 v=Math.min(this.bufferLimit,ar(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield yield A(this.loadInit(f,"high",!0));const p=this.initData.get(f.id),m=this.segments.get(f.id),g=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 A(void 0);this.searchGaps(m,f),yield yield A(this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(g)})}.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 A(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 A(this.loadInit(f,"high",!1)):m instanceof Promise&&(yield yield A(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 A(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield yield A(this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal));const g=this.getCurrentPosition();a.isNonNullable(g)&&(this.isLive||(p.forEach(S=>S.status=G.NONE),this.pruneBuffer(g,1/0,!0)),this.maintain(g))})}.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 A(void 0);for(const y of this.representations.keys()){const b=h.find(P=>P.id===y);b&&this.representations.set(y,b);const T=this.representations.get(y);if(!T||!Ti(T.segmentReference))return yield A(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 g=this.segments.get(p);a.assertNonNullable(g,"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 A(void 0);const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield yield A(this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal))),this.searchGaps(g,m),yield yield A(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=s,s){case xi.MP4:this.containerParser=O0;break;case xi.WEBM:this.containerParser=H0;break;default:a.assertNever(s)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Qe,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Le(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=Le(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(s,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=ge(l,0);c&&c.time.from-r.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}(!this.preloadOnly&&!this.allInitsLoaded&&r&&r.status===G.FED&&!l.length&&Le(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=ge(s,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let s=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-s)>0&&this.gaps.push({representation:t.id,from:s,to:n.time.from+r}),s=n.time.to;a.isNonNullable(t.duration)&&t.duration-s>0&&this.gaps.push({representation:t.id,from:s,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,s=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let n=0,o=t.length-1;do r.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<s&&o>=0);return this.liveInitialAdditionalOffset=n-s,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const s=this.segments.get(t.id);if(s!=null&&s.length)return{from:s[0].time.from,to:s[s.length-1].time.to}}updateLive(e){var t,s,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!Ti(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>Object.assign(Object.assign({},h),{status:G.NONE,size:void 0})),d=(s=this.segments.get(o.id))!==null&&s!==void 0?s:[],u=(n=(r=ge(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.floor(u)>=Math.floor(h.time.from)&&Math.floor(u)<=Math.floor(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const s of this.representations.values()){const r=s.segmentReference;if(!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(s.id))!==null&&t!==void 0?t:[],d=l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));d&&(d.time.to=e.segment.time.to),!!l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||l.push({status:G.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,s,r;const n=(s=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&s!==void 0?s:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,s){return this.isLive?this.selectForwardBufferSegmentsLive(e,s):this.selectForwardBufferSegmentsRecord(e,t,s)}selectForwardBufferSegmentsLive(e,t){const s=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=s),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,s){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const g=f<=s&&p>=s,S=f>s||g||m===0&&s===0,v=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=s+v||p<=s+v;return(h===G.NONE||h===G.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!Ri(this.sourceBuffer.buffered,s))&&S&&y});if(r===-1)return[];if(t!==We.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,s="auto"){return F(this,void 0,void 0,function*(){t.segmentReference.type===We.TEMPLATE?yield this.loadTemplateSegment(e[0],t,s):yield this.loadByteRangeSegments(e,t,s)})}loadTemplateSegment(e,t,s="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 A(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:s,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(!hn(c))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(c)}})}loadByteRangeSegments(e,t,s="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 A(new Promise(u=>setTimeout(u,d)))})}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{yield this.fetcher.fetch(n,{range:r,onProgress:l,signal:o,priority:s}),this.failedDownloads=0}catch(d){if(!hn(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 s=t.segmentReference.url,r={from:ge(e,0).byte.from,to:ge(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:s,range:r,signal:n,onProgress:(d,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!Ti(t.segmentReference))throw new Error("Representation is not template type");const s=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&s.searchParams.set("low-latency","yes");const r=s.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 s=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(s=Le((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,s||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:s,onSegmentAppendFailed:r,signal:n}){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=s,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u);c!=null&&c.byteLength&&(d.status=G.PARTIALLY_FED,l.feedingBytes+=c.byteLength,yield this.sourceBufferTaskQueue.append(c),l.fedBytes+=c.byteLength)}}}})}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:s,loaded:r,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const d=l.segmentReference.type,u=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===We.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=s&&h.byte.to<s+e.byteLength))continue;if(n.aborted){o();continue}const g=f?h.byte.from-s:0,S=f?h.byte.to-s:e.byteLength,v=g<r,y=S<=r;if(h.status===G.DOWNLOADING&&v&&y){h.status=G.DOWNLOADED;const b=new DataView(e.buffer,e.byteOffset+g,p);this.sourceBufferTaskQueue.append(b,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(c,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&v&&(c.loadedBytes=Math.min(p,r-g),c.loadedBytes>c.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+g+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===p?b:this.containerParser.parseFeedableSegmentChunk(b);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 s;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=G.FED,kl(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const n of(s=this.segments.get(r.id))!==null&&s!==void 0?s:[])n.status===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 s of this.activeSegments.values())if(s.segment===e){this.activeSegments.delete(s);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const s=this.representations.get(e);s&&(this.initLoadIdleCallback=rr(()=>Ss(this.loadInit(s,"low",!1),()=>this.initLoadIdleCallback=null)))}loadInit(e,t="auto",s=!1){return F(this,void 0,void 0,function*(){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!s&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,function(){return Z(this,arguments,function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield yield A(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),s&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o})}pruneBuffer(e,t,s=!1){return 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=kl(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&&s){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===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 s of t){let r={representation:e,from:s.time.from,to:s.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=s.time.from||o>=s.time.to)){if(o<=s.time.from&&l>=s.time.to){r=void 0;break}l>s.time.from&&l<s.time.to&&(r.from=l),o<s.time.to&&o>s.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=rr(()=>{try{this.detectGaps(e,t)}catch(s){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:s})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let s=0;s<this.sourceBuffer.buffered.length;s++){const r=Math.round(this.sourceBuffer.buffered.start(s)*1e3),n=Math.round(this.sourceBuffer.buffered.end(s)*1e3);e.push({from:r,to:n})}const t=1;for(const s of this.segments.values())for(const r of s){const{status:n}=r;if(n!==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(i){i[i.HEADER=0]="HEADER",i[i.PARAM=1]="PARAM"})(_i||(_i={}));class Q0{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:s=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Qe,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 A(li(n,{signal:this.abortAllController.signal}).catch(Zi));return o?(this.onHeadersReceived(o.headers),yield A(o.text())):yield A(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 g=new Headers;if(o)switch(n){case _i.HEADER:{g.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,v;if(u){const I=new Qe;if(v=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(),b=yield yield A(li(m,{priority:d,headers:g,signal:S}).catch(Zi)),T=a.now();if(!b)return v==null||v.unsubscribe(),yield A(null);if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!b.ok||!b.body)return v==null||v.unsubscribe(),yield A(Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`)));if(this.onHeadersReceived(b.headers),!l&&!c)return v==null||v.unsubscribe(),yield A(b.arrayBuffer());const[E,P]=b.body.tee(),N=E.getReader();c&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(P,h));let V=0,L=new Uint8Array(0),B=!1;const M=I=>{v==null||v.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 v==null||v.unsubscribe(),yield A(void 0);if(!I&&U){const R=new Uint8Array(L.length+U.length);R.set(L),R.set(U,L.length),L=R,V+=U.byteLength,l==null||l(new DataView(L.buffer),V),yield yield A(N==null?void 0:N.read().then(D,M))}})}.bind(this));return yield yield A(N==null?void 0:N.read().then(D,M)),v==null||v.unsubscribe(),yield A(B?null:L.buffer)})}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,function(r,n,o){var l;return Z(this,arguments,function*(){if(r.type!==We.BYTE_RANGE)return yield A(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 g=yield yield A(this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1}));if(!g)return yield A(null);const S=new DataView(g,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const v=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(v);if(!y)throw new ReferenceError("No way to load representation index");let b;if(f)b=new DataView(g,y.from-c,y.to-y.from+1);else{const E=yield yield A(this.fetch(r.url,{range:y,priority:o,measureThroughput:!1}));if(!E)return yield A(null);b=new DataView(E)}const T=n.parseSegments(b,v,y);return yield A({init:v,dataView:new DataView(g),segments:T})})}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,function(r,n){return Z(this,arguments,function*(){if(r.type!==We.TEMPLATE)return yield A(null);const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield yield A(this.fetch(o,{priority:n,measureThroughput:!1}));if(!l)return yield A(null);const d=r.segments.map(u=>Object.assign(Object.assign({},u),{status:G.NONE,size:void 0}));return yield A({init:null,segments:d,dataView:new DataView(l)})})}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=s}onHeadersReceived(e){const{type:t,reused:s}=Fn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(s)}fetchRepresentation(e,t,s="auto"){var r,n;return F(this,void 0,void 0,function*(){const{type:o}=e;switch(o){case We.BYTE_RANGE:return(r=yield this.fetchByteRangeRepresentation(e,t,s))!==null&&r!==void 0?r:null;case We.TEMPLATE:return(n=yield this.fetchTemplateRepresentation(e,s))!==null&&n!==void 0?n:null;default:a.assertNever(o)}})}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Zi=i=>{if(!hn(i))throw i},fn=1e3,cr=(i,e,t)=>t*e+(1-t)*i,$d=(i,e)=>i.reduce((t,s)=>t+s,0)/e,K0=(i,e,t,s)=>{let r=0,n=t;const o=$d(i,e),l=e<s?e:s;for(let d=0;d<l;d++)i[n]>o?r++:r--,n=(i.length+n-1)%i.length;return Math.abs(r)===l};class Hn{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const s=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new ct(`raw_${s}`),this.smoothedSeries$=new ct(`smoothed_${s}`),this.reportedSeries$=new ct(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,s=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=Math.pow(this.pastMeasures[l]-this.smoothed,2),s++);this.takenMeasures=s,t/=s;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class J0 extends Hn{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 X0 extends Hn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=$d(this.pastMeasures,this.takenMeasures);this.emaSmoothed=cr(this.emaSmoothed,e,this.params.emaAlpha);const s=K0(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=s?this.emaSmoothed:t}}class Z0 extends Hn{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 pn{static getSmoothedValue(e,t,s){return s.type==="TwoEma"?new J0({initial:e,emaAlphaSlow:s.emaAlphaSlow,emaAlphaFast:s.emaAlphaFast,changeThreshold:s.changeThreshold,fastDirection:t,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"}):new X0({initial:e,emaAlpha:s.emaAlpha,basisTrendChangeCount:s.basisTrendChangeCount,changeThreshold:s.changeThreshold,deviationDepth:s.deviationDepth,deviationFactor:s.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new Z0(Object.assign({initial:e,label:"liveEdgeDelay"},t))}}const eT=(i,e)=>{i&&i.playbackRate!==e&&(i.playbackRate=e)},wl=["timeupdate","progress","play","seeked","stalled","waiting"];var ze;(function(i){i.NONE="none",i.MANIFEST_READY="manifest_ready",i.REPRESENTATIOS_READY="representations_ready",i.RUNNING="running"})(ze||(ze={}));let tT=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(ze.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 Qe,this.initManifest=a.abortable(this.destroyController.signal,function(t,s,r){var n;return Z(this,arguments,function*(){this.element=t,this.manifestUrlString=Pe(s,r,ae.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(ze.MANIFEST_READY),this.manifest=yield yield A(this.updateManifest()),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(ze.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 s=yield yield A(this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})}));if(!s)return yield A(this.manifest);let r;try{r=G0(s!=null?s:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return yield A(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===ye.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 A(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,s){return Z(this,arguments,function*(){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(ze.REPRESENTATIOS_READY),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(ye.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(s)&&(this.audioBufferManager=new Al(ye.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(fn).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=Pe(this.manifestUrlString,u+fn,ae.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...wl.map(l=>a.fromEvent(this.element,l))).pipe(a.map(l=>this.element?Le(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(l=>!!l)).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(a.filter(d=>this.isActiveLowLatency&&!!d)).subscribe(d=>this.liveEstimatedDelay.next(d))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(d=>{if(!this.isActiveLowLatency)return;const u=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,f=d-u;let p=1+Math.sign(f)*h;Math.abs(f)<c?p=1:Math.abs(f)>c*2&&(p=1+Math.sign(f)*h*2),eT(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 g,S;return(S=(g=m.getLiveSegmentsToLoadState(this.manifest))===null||g===void 0?void 0:g.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.liveWaitingEventCallback.cancel(),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,g=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,S=this.isActiveLowLatency?u:d;let v=dt.None;if(this.isActiveLowLatency?v=dt.ActiveLowLatency:S<p+g&&S>=p?v=dt.LiveWithTargetOffset:h!==0&&S<p&&(v=dt.LiveForwardBuffering),isFinite(d)&&(l=d>l?d:l),v===dt.LiveForwardBuffering||v===dt.LiveWithTargetOffset){const y=l-(p+m),b=Math.trunc(h+y/c);let T;d?b>0?T=b:T=0:T=h,this.manifestUrlString=Pe(this.manifestUrlString,T,ae.DASH_CMAF_OFFSET_P)}v!==dt.None&&v!==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 A(new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)}))),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(s)?yield yield A(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(s)])):yield yield A(this.videoBufferManager.startWith(t)),this.state$.setState(ze.REPRESENTATIOS_READY)})}.bind(this)),this.tick=()=>{var t,s;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((s=this.audioBufferManager)===null||s===void 0)&&s.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Q0({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=pn.getLiveEstimatedDelaySmoothedValue(0,Object.assign({},e.tuning.dashCmafLive.lowLatency.delayEstimator)),this.liveWaitingEventCallback=Md.debounce(this._liveWaitingEventCallback,this.tuning.dashCmafLive.maxWaitingDuration)}seekLive(e){var t,s,r,n;return F(this,void 0,void 0,function*(){a.assertNonNullable(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.liveLastSeekOffset=e,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Pe(this.manifestUrlString,e,ae.DASH_CMAF_OFFSET_P),this.manifest=yield this.updateManifest(),yield(t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((s=this.manifest)===null||s===void 0?void 0:s.representations.video),yield(r=this.audioBufferManager)===null||r===void 0?void 0:r.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio)})}initBuffer(){a.assertNonNullable(this.element),this.state$.setState(ze.RUNNING),this.subscription.add(a.merge(...wl.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.isLive$.getValue()&&this.liveWaitingEventCallback()})),this.tick()}switchRepresentation(e,t){return F(this,void 0,void 0,function*(){const s={[ye.VIDEO]:this.videoBufferManager,[ye.AUDIO]:this.audioBufferManager,[ye.TEXT]:null}[e];return s==null?void 0:s.switchTo(t)})}seek(e,t){var s,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((s=this.videoBufferManager.findSegmentStartTime(e))!==null&&s!==void 0?s:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),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(ze.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}_liveWaitingEventCallback(){return F(this,void 0,void 0,function*(){yield this.seekLive(this.liveLastSeekOffset)})}updateLive(){var e;return F(this,void 0,void 0,function*(){this.isUpdatingLive=!0,this.manifest=yield this.updateManifest(),(e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest)),this.isUpdatingLive=!1})}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,s=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?s.push(1/0):s.push(n.to));if(s.length){const r=Math.max(...s);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class kd{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 rd,this.textTracks=[],this.syncPlayback=()=>{var t,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===Y.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ue.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(s=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&s!==void 0?s:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==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),w(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),w(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&&w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var s,r,n;if(this.scene3D)return;this.scene3D=new bd(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((s=t.projectionData)===null||s===void 0?void 0:s.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=bt(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(_e(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new tT({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,s=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:s,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:s,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:s.playing$,pause$:s.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(s.ended$,e.endedEvent$),n(s.looped$,e.loopedEvent$),n(s.error$,e.error$),n(s.isBuffering$,e.isBuffering$),n(s.currentBuffer$,e.currentBuffer$),n(s.playing$,e.firstFrameEvent$),n(s.canplay$,e.canplay$),n(s.inPiP$,e.inPiP$),n(s.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(Ht(this.video,t.isLooped,r)),this.subscription.add(vt(this.video,t.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Lt(this.video,t.playbackRate,s.playbackRateState$,r)),n(us(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe(()=>{this.videoState.setState(ue.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(s.pause$.subscribe(()=>{this.videoState.setState(ue.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(s.canplay$.subscribe(()=>{this.videoState.getState()===ue.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((v,y)=>y.bitrate-v.bitrate),m=Array.from(f.video).sort((v,y)=>y.bitrate-v.bitrate),g=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const v of p){const y=z0(v);y&&this.audioTracks.push({track:y,representation:v})}for(const v of m){const y=Y0(v);if(y){h.push({track:y,representation:v});const b=!this.params.tuning.isAudioDisabled&&q0(p,m,v);b&&this.audioRepresentations.set(v.id,b)}}this.videoTracks$.next(h);for(const v of g){const y=W0(v);y&&this.textTracks.push({track:y,representation:v})}this.params.output.availableVideoTracks$.next(h.map(({track:v})=>v)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:v})=>v)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:v})=>v));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(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!==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,s,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=Le(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),g=Math.max(c&&!d&&(r=(s=this.audioRepresentations.get(c.id))===null||s===void 0?void 0:s.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:g,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),v=d?S!=null?S:c:c!=null?c:S;return v&&((l=this.videoTracks$.getValue().find(({track:y})=>y===v))===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),w(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),gt(this.video)}}class iT extends kd{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();s(t.timeUpdate$,e.position$),s(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let sT=class extends gd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(dn),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(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===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 rT extends kd{constructor(e){super(e),this.liveOffset=new ys}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:s}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),s(t.timeUpdate$,e.liveBufferTime$),s(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(fn),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(),s=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&s===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(i){i.INITIALIZING="initializing",i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(X||(X={}));const es=(i,e)=>new a.Observable(t=>{const s=(r,n)=>t.next(n);return i.on(e,s),()=>i.off(e,s)});class aT{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(),s=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),s){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),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case X.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(s)}},this.video=bt(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(_e(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),gt(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},s=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);Ss(import("hls.js").then(r=>{e||(ut.Hls=r.default,ut.Events=r.default.Events,this.init())},t),()=>{window.clearTimeout(s),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,s=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,s));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(Ht(this.video,e.isLooped,s)),this.subscription.add(vt(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Lt(this.video,e.playbackRate,r.playbackRateState$,s)),this.subscription.add(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),w(e.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s)),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:g,height:S}=h,v=(p=Mi((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:g,height:S});if(!v)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,b={id:m.toString(),quality:v,bitrate:h.bitrate/1e3,size:{width:g,height:S},fps:y};return this.trackLevels.set(m,{track:b,level:h}),c.push(b),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,g="internal";c.push({id:f,url:p,language:m,type:g})}e.internalTextTracks.startTransitionTo(c)}}),n(es(this.hls,ut.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>_e(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:s}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=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$,s),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:s})),n(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(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),w(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),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Pl="X-Playback-Duration";var _l=i=>F(void 0,void 0,void 0,function*(){var e;const t=yield li(i),s=yield t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(s))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(Pl)?parseInt(t.headers.get(Pl),10):void 0});const nT=i=>{let e=null;if(i.QUALITY&&(e=Mi(i.QUALITY)),!e&&i.RESOLUTION){const[t,s]=i.RESOLUTION.split("x").map(r=>parseInt(r,10));e=a.videoSizeToQuality({width:t,height:s})}return e!=null?e:null},Ad=(i,e=i)=>F(void 0,void 0,void 0,function*(){var t,s;const o=(yield(yield li(i)).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}`,g=nT(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 v=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 b=new URL(o[++u],e).toString();g&&l.push({id:m,quality:g,url:b,bandwidth:S,size:y,fps:v})}if(f){const p=ni(f[1].split(",").map(v=>v.split("=")).map(([v,y])=>[v,y.replace(/^"|"$/g,"")])),m=(s=p.URI)===null||s===void 0?void 0:s.replace(/playlist$/,"subtitles.vtt"),g=p.LANGUAGE,S=p.NAME;m&&g&&d.push({type:"internal",id:g,label:S,language:g,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}}),hr=(i,e)=>{const t=a.isNullable(e)||a.isNonNullable(e.min)&&a.isNonNullable(e.max)&&a.isLower(e.max,e.min),s=a.isNonNullable(i)&&i!==a.VideoQuality.INVARIANT;return t||s&&(a.isNullable(e==null?void 0:e.min)||a.isHigherOrEqual(i,e==null?void 0:e.min))&&(a.isNullable(e==null?void 0:e.max)||a.isLowerOrEqual(i,e==null?void 0:e.max))};var ie;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(ie||(ie={}));class oT{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();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),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(r===ie.STOPPED){this.videoState.startTransitionTo(ie.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(ie.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.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&&c.state===Y.Requested){this.videoState.startTransitionTo(ie.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case ie.READY:n===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),w(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&&w(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 h=this.liveOffset.getTotalOffset();h>=this.maxSeekBackTime$.getValue()&&(h=0,this.liveOffset.resetTo(h)),this.liveOffset.resume(),this.params.output.position$.next(-h/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(w(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=bt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},Ad(Pe(this.params.source.url),this.params.source.url).then(({qualityManifests:s})=>{this.allManifests=[...s];const r=this.params.desiredState.autoVideoTrackLimits.getState();this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:n})=>hr(n,r))])},s=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:s})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(_e(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,n=s.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo(this.masterManifest),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,s));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(ie.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(ie.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.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(_e(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)},s)),this.subscription.add(r.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},s)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),s)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s)),this.subscription.add(t.autoVideoTrackLimits.stateChangeStarted$.subscribe(l=>{const d=l.to;this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:u})=>hr(u,d))]),this.params.output.autoVideoTrackLimits$.next(l.to)}));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){const e=this.selectManifest();if(a.isNullable(e))return;const t=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?ae.DASH_CMAF_OFFSET_P:ae.OFFSET_P,s=Pe(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",s),this.video.load(),_l(s).then(r=>{var n;if(!a.isNullable(r))this.maxSeekBackTime$.next(r);else{const o=(n=this.params.source.maxSeekBackTime)!==null&&n!==void 0?n:this.maxSeekBackTime$.getValue();if(a.isNullable(o)||!isFinite(o))try{li(s).then(l=>l.text()).then(l=>{var d;const u=(d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l))===null||d===void 0?void 0:d[1];if(u){const c=new URL(u,s).toString();_l(c).then(h=>{a.isNullable(h)||this.maxSeekBackTime$.next(h)})}})}catch(l){}}})}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(ie.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,s=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(s),this.params.output.position$.next(-s/1e3),this.params.output.seekedEvent$.next()}}var re;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.CHANGING_MANIFEST="changing_manifest",i.PAUSED="paused"})(re||(re={}));class lT{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 s=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(r===exports.PlaybackState.STOPPED){s!==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),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(s===re.STOPPED){this.videoState.startTransitionTo(re.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(re.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===Y.None&&this.params.desiredState.seekState.setState({state:Y.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===Y.Requested&&this.seek(u.position),s){case re.READY:r===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(re.PAUSED),w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case re.CHANGING_MANIFEST:break;default:return a.assertNever(s)}},this.params=e,this.video=bt(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(_e(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),Ad(this.params.source.url).then(({qualityManifests:t,textTracks:s})=>{this.allManifests=[...t];const r=this.params.desiredState.autoVideoTrackLimits.getState();this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:n})=>hr(n,r))]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(s)},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;const{autoVideoTrackSwitching:s,videoTrack:r}=this.params.desiredState,n=s.getState(),o=r.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:r.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&r.startTransitionTo(this.masterManifest),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=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,s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(re.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(re.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s).add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.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(_e(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)},s))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,s)),this.subscription.add(t.autoVideoTrackLimits.stateChangeStarted$.subscribe(l=>{const d=l.to;this.manifests$.next([this.masterManifest,...this.allManifests.filter(({quality:u})=>hr(u,d))]),this.params.output.autoVideoTrackLimits$.next(l.to)})),!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"},s))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),gt(this.video)}prepare(){const e=this.selectManifest();a.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(re.PAUSED),w(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(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(de||(de={}));class uT{constructor(e){this.subscription=new a.Subscription,this.videoState=new ee(de.STOPPED),this.trackUrls={},this.textTracksManager=new nt,this.syncPlayback=()=>{var t,s,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==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),w(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=(s=this.trackUrls[c.to.id])===null||s===void 0?void 0:s.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===Y.Requested&&this.seek(h.position),n){case de.READY:o===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(de.PAUSED),w(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&&w(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&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=bt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,s],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:s}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,s=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=St(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,s));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(Ht(this.video,t.isLooped,s)),this.subscription.add(vt(this.video,t.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(Lt(this.video,t.playbackRate,r.playbackRateState$,s)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(de.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(de.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},s)).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()},s)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),gt(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:s}=this.trackUrls[t];a.assertNonNullable(s,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(s=Ut(s)),this.video.setAttribute("src",s),this.video.load(),this.params.output.hostname$.next(_e(s))}playIfAllowed(){Nt(this.video).then(e=>{e||(this.videoState.setState(de.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,s,r,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const d=(s=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||s===void 0?void 0:s.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 Dl=["stun:videostun.mycdn.me:80"],dT=1e3,cT=3,_a=()=>null;class hT{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=_a,this.externalStopCallback=_a,this.externalErrorCallback=_a,this.options=this.normalizeOptions(t);const s=e.split("/");this.serverUrl=s.slice(0,s.length-1).join("/"),this.streamKey=s[s.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}handleUpdateMessage(e){return 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:Dl}]};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),s=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(s))throw new Error("No h264 codec support error");return t})}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),dT)}normalizeOptions(e={}){const t={stunServerList:Dl,maxRetryNumber:cT,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var se;(function(i){i.STOPPED="stopped",i.READY="ready",i.PLAYING="playing",i.PAUSED="paused"})(se||(se={}));class fT{constructor(e){this.videoState=new ee(se.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(s===exports.PlaybackState.STOPPED){t!==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),w(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:s===exports.PlaybackState.PAUSED?(this.videoState.setState(se.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed());return;case se.PLAYING:s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(se.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case se.PAUSED:s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(se.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&w(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=bt(e.container),this.liveStreamClient=new hT(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),gt(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,s=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const r=St(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,s));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===se.READY&&this.videoState.setState(se.READY)},s)).add(r.pause$.subscribe(()=>{this.videoState.setState(se.PAUSED)},s)).add(r.playing$.subscribe(()=>{this.videoState.setState(se.PLAYING)},s)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(vt(this.video,t.volume,r.volumeState$,s)).add(r.volumeState$.subscribe(e.volume$,s)).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)}},s)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),s)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),s)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),s))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(_e(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,w(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),w(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 Il{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 Da,Ia,Ra,Ca,xa,La,Fs,Na,Us,Oa,js,Ba,Hs,Ma,Gs,Va,Ys,Fa;const wd=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Vt=document.createElement("video"),pT='video/mp4; codecs="avc1.42000a,mp4a.40.2"',mT='video/mp4; codecs="hev1.1.6.L93.B0"',Pd='video/webm; codecs="vp09.00.10.08"',_d='video/webm; codecs="av01.0.00M.08"',vT='audio/mp4; codecs="mp4a.40.2"',bT='audio/webm; codecs="opus"',it={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Ia=(Da=window.SourceBuffer)===null||Da===void 0?void 0:Da.prototype)===null||Ia===void 0)&&Ia.appendBuffer)),hls:!!(!((Ra=Vt.canPlayType)===null||Ra===void 0)&&Ra.call(Vt,"application/x-mpegurl")||!((Ca=Vt.canPlayType)===null||Ca===void 0)&&Ca.call(Vt,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ue={mp4:!!(!((xa=Vt.canPlayType)===null||xa===void 0)&&xa.call(Vt,"video/mp4")),webm:!!(!((La=Vt.canPlayType)===null||La===void 0)&&La.call(Vt,"video/webm")),cmaf:!0},pt={h264:!!(!((Na=(Fs=window.MediaSource)===null||Fs===void 0?void 0:Fs.isTypeSupported)===null||Na===void 0)&&Na.call(Fs,pT)),h265:!!(!((Oa=(Us=window.MediaSource)===null||Us===void 0?void 0:Us.isTypeSupported)===null||Oa===void 0)&&Oa.call(Us,mT)),vp9:!!(!((Ba=(js=window.MediaSource)===null||js===void 0?void 0:js.isTypeSupported)===null||Ba===void 0)&&Ba.call(js,Pd)),av1:!!(!((Ma=(Hs=window.MediaSource)===null||Hs===void 0?void 0:Hs.isTypeSupported)===null||Ma===void 0)&&Ma.call(Hs,_d)),aac:!!(!((Va=(Gs=window.MediaSource)===null||Gs===void 0?void 0:Gs.isTypeSupported)===null||Va===void 0)&&Va.call(Gs,vT)),opus:!!(!((Fa=(Ys=window.MediaSource)===null||Ys===void 0?void 0:Ys.isTypeSupported)===null||Fa===void 0)&&Fa.call(Ys,bT))},Ei=(pt.h264||pt.h265)&&pt.aac;var Mt;(function(i){i.VP9="vp9",i.AV1="av1",i.NONE="none",i.SMOOTH="smooth",i.POWER_EFFICIENT="power_efficient"})(Mt||(Mt={}));var It;(function(i){i.DASH="dash",i.HLS="hls",i.MPEG="mpeg"})(It||(It={}));let ii;const gT=()=>F(void 0,void 0,void 0,function*(){if(!window.navigator.mediaCapabilities)return;const i={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=yield Promise.all([window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:_d})})),window.navigator.mediaCapabilities.decodingInfo(Object.assign(Object.assign({},i),{video:Object.assign(Object.assign({},i.video),{contentType:Pd})}))]);ii={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}});try{gT()}catch(i){console.error(i)}const ds=it.hls&&Ue.mp4,ST=()=>Object.keys(pt).filter(i=>pt[i]),yT=(i,e=!1)=>i.filter(t=>{switch(t){case exports.VideoFormat.DASH:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.DASH_SEP:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.DASH_WEBM:return it.mse&&Ue.webm&&pt.vp9&&pt.opus;case exports.VideoFormat.DASH_WEBM_AV1:return it.mse&&Ue.webm&&pt.av1&&pt.opus;case exports.VideoFormat.DASH_LIVE:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.DASH_LIVE_CMAF:return it.mse&&Ue.mp4&&Ei&&Ue.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return ds||e&&it.mse&&Ue.mp4&&Ei;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return ds;case exports.VideoFormat.MPEG:return Ue.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return it.webrtc&&it.ws&&pt.h264&&(Ue.mp4||Ue.webm);default:return a.assertNever(t)}}),ts=i=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(i){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(i)}return[e,t]},TT=({webmCodec:i,androidPreferredFormat:e})=>{if(wd)switch(e){case It.MPEG:return[exports.VideoFormat.MPEG,...ts(i),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(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case It.DASH:return[...ts(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return ds?[...ts(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...ts(i),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},ET=({androidPreferredFormat:i,preferCMAF:e,preferWebRTC:t})=>{const s=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=[...s,...r],o=[...r,...s];let l;if(wd)switch(i){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]},Rl=i=>i?[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 $T=i=>new a.Observable(e=>{const t=new a.Subscription,s=i.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=i.desiredPlaybackState$.stateChangeEnded$,n=i.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(s.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),i.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),i.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const kT={cacheDuration:12e4},AT={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=yT([...ET(this.params.tuning),...TT(this.params.tuning)],this.params.tuning.useHlsJs).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:s,formatsToAvoid:r}=this.params.tuning;let n=[];s?n=[s]:r.length?n=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Il(n);const o=[...Rl(!0),...Rl(!1)];this.chromecastFormatsIterator=new Il(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let s;try{s=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}s?this.current$.next({type:t,provider:s,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,s=this.params.desiredState.seekState.getState(),r=s.state!==Y.None;if(this.params.desiredState.seekState.setState({state:Y.Requested,position:r?s.position:t,forcePrecise:r?s.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Ae.SCREEN:return this.createScreenProvider(t);case Ae.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:s,desiredState:r}=this.params,n=this.providerOutput,o={container:s,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new wS(Object.assign(Object.assign({},o),{source:l,config:kT}))}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 dl(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new iT(Object.assign(Object.assign({},o),{source:l})):new o0(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 dl(Object.assign(Object.assign({},o),{source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}})):this.params.tuning.useNewDashVkProvider?new rT(Object.assign(Object.assign({},o),{source:l})):new sT(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 lT(Object.assign(Object.assign({},o),{source:l})):new aT(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 oT(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 uT(Object.assign(Object.assign({},o),{source:l}))}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new TS(Object.assign(Object.assign({},o),{source:l,config:Object.assign(Object.assign({},AT),{maxPausedTime:this.params.tuning.live.maxPausedTime})}))}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new fT({container:s,source:l,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:s,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new Cg({connection:l,meta:n,container:s,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?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 s=r=>{const n=new URL(r);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return Object.assign(Object.assign({},e),{url:s(e.url)})}return ni(Object.entries(e).map(([r,n])=>[r,s(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,s=0;return e.add(a.merge(this.providerOutput.error$,$T({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(r=>({id:`ProviderHangup:${r}`,category:a.ErrorCategory.WTF,message:`A ${r} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const r=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:n})=>n===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(r)})),e.add(this.providerError$.subscribe(r=>{const n=this.current$.getValue().destination;if(n===Ae.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Ae.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=r.category===a.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=s<this.params.tuning.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(s++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:Ae.SCREEN)}})),e}}const PT=5e3,Cl="one_video_throughput",xl="one_video_rtt",Rt=window.navigator.connection,Ll=()=>{const i=Rt==null?void 0:Rt.downlink;if(a.isNonNullable(i)&&i!==10)return i*1e3},Nl=()=>{const i=Rt==null?void 0:Rt.rtt;if(a.isNonNullable(i)&&i!==3e3)return i},Ol=(i,e,t)=>{const s=t*8,r=s/i;return s/(r+e)};class ns{constructor(e){var t,s;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=ns.load(Cl)||(e.useBrowserEstimation?Ll():void 0)||PT,n=(s=(t=ns.load(xl))!==null&&t!==void 0?t:e.useBrowserEstimation?Nl():void 0)!==null&&s!==void 0?s:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Ol(r,n,e.rttPenaltyRequestSize)),this.throughput=pn.getSmoothedValue(r,-1,e),this.rtt=pn.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Ll();d&&this.throughput.next(d);const u=Nl();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(Cl,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})=>Ol(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,s=a.now();const r=new a.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,s=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,s=a.now()}));break}r.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-s;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const s=e.getReader();if(!s){e.cancel("Could not get reader");return}let r=0,n=a.now(),o=0,l=a.now();const d=c=>{this.concurrentDownloads.delete(e),s.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=({done:c,value:h})=>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 s==null?void 0:s.read().then(u,d)}});this.concurrentDownloads.add(e),s==null||s.read().then(u,d)}addRawSpeed(e,t,s=1,r=!1){if(ns.sanityCheck(e,t,r)){const n=e*8/t;this.throughput.next(n*s)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,s=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||s&&e<1e4||!s&&e<10*1024||!s&&t<=20)}static load(e){var t;const s=a.safeStorage.get(e);if(a.isNonNullable(s))return(t=parseInt(s,10))!==null&&t!==void 0?t:void 0}}const Bl={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,maxWaitingDuration:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!0,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Mt.VP9,androidPreferredFormat:It.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},_T=i=>{var e;return Object.assign(Object.assign({},a.fillWithDefault(i,Bl)),{configName:[...(e=i.configName)!==null&&e!==void 0?e:[],...Bl.configName]})};var Ml=({seekState:i,position$:e})=>a.merge(i.stateChangeEnded$.pipe(a.map(({to:t})=>{var s;return t.state===Y.None?void 0:((s=t.position)!==null&&s!==void 0?s:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>i.getState().state===Y.None))),DT=i=>{const e=typeof i.container=="string"?document.getElementById(i.container):i.container;return a.assertNonNullable(e,`Wrong container or containerId {${i.container}}`),e};const IT=(i,e,t,s)=>{i!==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(s)&&e.startTransitionTo(i)}):(i===void 0||t!=null&&t.getValue().find(s))&&e.startTransitionTo(i)};class RT{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:tS},this.initLogs(),this.tuning=_T(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Fd({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,s,r)=>{const n=Reflect.get(t,s,r);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(s)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,s,r;return this.config=e,this.domContainer=DT(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new wT({sources:e.sources,meta:(s=e.meta)!==null&&s!==void 0?s:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,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 s=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=s&&!r&&(e=s-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state: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(s=>s.length>0),a.once()).subscribe(s=>{this.setVideoTrackIdByQuality(s,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 s=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return s&&(this.desiredState.playbackRate.setState(e),s.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>Object.assign({type:"external"},t))),this}selectTextTrack(e){var t;return IT(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,s=>s.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 s=this.getScene3D();return s&&s.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const s=this.getScene3D();if(s){const r=s.getCameraRotation(),n=s.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){a.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),s=t.state===Y.None?void 0:t.position;return a.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const s=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=s==null?void 0:s.provider)===null||t===void 0)&&t.scene3D)return s.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((s,{width:r})=>s||r||0,0),height:e.reduce((s,{height:r})=>s||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===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:Ml({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(Ml({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const s=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>s.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>s.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,s).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||s.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((s,r)=>s.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(s=>s.length>0),a.once()).subscribe(s=>{this.setStartingVideoTrack(s)}))}))}setStartingVideoTrack(e){var t;let s;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(s=e.find(({quality:n})=>n===r),s||this.setAutoQuality(!0)),s||(s=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(s),this.info.currentQuality$.next(s.quality),this.info.videoBitrate$.next(s.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),eS(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(s=>Zg(s)),this.providerContainer.current$.subscribe(({type:s})=>Os("provider",s)),t.duration$.subscribe(s=>Os("duration",s)),t.availableVideoTracks$.pipe(a.filter(s=>!!s.length),a.once()).subscribe(s=>Os("tracks",s)),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(s=>s==null?void 0:s.quality)).subscribe(new ct("quality")),this.info.currentBuffer$.subscribe(new ct("buffer")),t.isBuffering$.subscribe(new ct("isBuffering"))].forEach(s=>this.subscription.add(s)),Os("codecs",ST())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},s=()=>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||s():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const s=e.find(r=>r.quality===t);s?this.desiredState.videoTrack.startTransitionTo(s):this.setAutoQuality(!0)}}const CT=`@vkontakte/videoplayer-core@${Vl}`;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=RT;exports.SDK_VERSION=CT;exports.VERSION=Vl;
|