@vkontakte/videoplayer-core 2.0.98-dev.27a468df.0 → 2.0.98-dev.489417ae.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 +13 -13
- package/es2015.esm.js +9 -9
- package/es2018.cjs.js +12 -12
- package/es2018.esm.js +14 -14
- package/esnext.cjs.js +8 -8
- package/esnext.esm.js +10 -10
- package/evergreen.esm.js +9 -9
- package/index.d.ts +4 -1
- package/package.json +3 -4
package/es2018.cjs.js
CHANGED
|
@@ -1,19 +1,19 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.98-dev.
|
|
3
|
-
*
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.98-dev.489417ae.0
|
|
3
|
+
* Thu, 15 Feb 2024 17:01:30 GMT
|
|
4
4
|
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-98/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Tl=Object.create;var Ra=Object.defineProperty;var El=Object.getOwnPropertyDescriptor;var $l=Object.getOwnPropertyNames;var kl=Object.getPrototypeOf,Al=Object.prototype.hasOwnProperty;var wl=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of $l(e))!Al.call(s,r)&&r!==t&&Ra(s,r,{get:()=>e[r],enumerable:!(i=El(e,r))||i.enumerable});return s};var Ia=(s,e,t)=>(t=s!=null?Tl(kl(s)):{},wl(e||!s||!s.__esModule?Ra(t,"default",{value:s,enumerable:!0}):t,s));var a=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Pl=require("lodash/debounce.js"),_l=require("lodash");const to="2.0.98-dev.27a468df.0";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var ye;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(ye||(ye={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var H;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(H||(H={}));exports.Surface=void 0;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(exports.Surface||(exports.Surface={}));var Dl=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Rl{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Dl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,n;(n=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([i.getCastState()])).pipe(a.filterChanged(),a.map(Il),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Il=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(s)}};var ar=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ua(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var $t=function(s){try{return!!s()}catch(e){return!0}},Cl=$t,xs=!Cl(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),io=xs,so=Function.prototype,qr=so.call,Ll=io&&so.bind.bind(qr,qr),kt=io?Ll:function(s){return function(){return qr.apply(s,arguments)}},ro=kt,xl=ro({}.toString),Nl=ro("".slice),Ns=function(s){return Nl(xl(s),8,-1)},Bl=kt,Ol=$t,Ml=Ns,nr=Object,Vl=Bl("".split),Fl=Ol(function(){return!nr("z").propertyIsEnumerable(0)})?function(s){return Ml(s)=="String"?Vl(s,""):nr(s)}:nr,Bs=function(s){return s==null},Ul=Bs,jl=TypeError,da=function(s){if(Ul(s))throw jl("Can't call method on "+s);return s},Hl=Fl,Gl=da,Yi=function(s){return Hl(Gl(s))},yi={},Ji=function(s){return s&&s.Math==Math&&s},Ke=Ji(typeof globalThis=="object"&&globalThis)||Ji(typeof window=="object"&&window)||Ji(typeof self=="object"&&self)||Ji(typeof ar=="object"&&ar)||function(){return this}()||ar||Function("return this")(),Wr=typeof document=="object"&&document.all,Yl=typeof Wr=="undefined"&&Wr!==void 0,ao={all:Wr,IS_HTMLDDA:Yl},no=ao,zl=no.all,je=no.IS_HTMLDDA?function(s){return typeof s=="function"||s===zl}:function(s){return typeof s=="function"},ql=Ke,Wl=je,Ca=ql.WeakMap,Ql=Wl(Ca)&&/native code/.test(String(Ca)),La=je,oo=ao,Kl=oo.all,Xt=oo.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:La(s)||s===Kl}:function(s){return typeof s=="object"?s!==null:La(s)},Jl=$t,Zt=!Jl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ti={},Xl=Ke,xa=Xt,Qr=Xl.document,Zl=xa(Qr)&&xa(Qr.createElement),lo=function(s){return Zl?Qr.createElement(s):{}},eu=Zt,tu=$t,iu=lo,uo=!eu&&!tu(function(){return Object.defineProperty(iu("div"),"a",{get:function(){return 7}}).a!=7}),su=Zt,ru=$t,co=su&&ru(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),au=Xt,nu=String,ou=TypeError,ei=function(s){if(au(s))return s;throw ou(nu(s)+" is not an object")},lu=xs,Xi=Function.prototype.call,At=lu?Xi.bind(Xi):function(){return Xi.apply(Xi,arguments)},ca={},or=ca,lr=Ke,uu=je,Na=function(s){return uu(s)?s:void 0},ha=function(s,e){return arguments.length<2?Na(or[s])||Na(lr[s]):or[s]&&or[s][e]||lr[s]&&lr[s][e]},du=kt,fa=du({}.isPrototypeOf),cu=typeof navigator!="undefined"&&String(navigator.userAgent)||"",ho=Ke,ur=cu,Ba=ho.process,Oa=ho.Deno,Ma=Ba&&Ba.versions||Oa&&Oa.version,Va=Ma&&Ma.v8,We,Ss;Va&&(We=Va.split("."),Ss=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!Ss&&ur&&(We=ur.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=ur.match(/Chrome\/(\d+)/),We&&(Ss=+We[1])));var hu=Ss,Fa=hu,fu=$t,pu=Ke,mu=pu.String,fo=!!Object.getOwnPropertySymbols&&!fu(function(){var s=Symbol();return!mu(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Fa&&Fa<41}),bu=fo,po=bu&&!Symbol.sham&&typeof Symbol.iterator=="symbol",gu=ha,vu=je,Su=fa,yu=po,Tu=Object,mo=yu?function(s){return typeof s=="symbol"}:function(s){var e=gu("Symbol");return vu(e)&&Su(e.prototype,Tu(s))},Eu=String,pa=function(s){try{return Eu(s)}catch(e){return"Object"}},$u=je,ku=pa,Au=TypeError,ma=function(s){if($u(s))return s;throw Au(ku(s)+" is not a function")},wu=ma,Pu=Bs,Os=function(s,e){var t=s[e];return Pu(t)?void 0:wu(t)},dr=At,cr=je,hr=Xt,_u=TypeError,Du=function(s,e){var t,i;if(e==="string"&&cr(t=s.toString)&&!hr(i=dr(t,s))||cr(t=s.valueOf)&&!hr(i=dr(t,s))||e!=="string"&&cr(t=s.toString)&&!hr(i=dr(t,s)))return i;throw _u("Can't convert object to primitive value")},bo={exports:{}},Ua=Ke,Ru=Object.defineProperty,Iu=function(s,e){try{Ru(Ua,s,{value:e,configurable:!0,writable:!0})}catch(t){Ua[s]=e}return e},Cu=Ke,Lu=Iu,ja="__core-js_shared__",xu=Cu[ja]||Lu(ja,{}),go=xu,Ha=go;(bo.exports=function(s,e){return Ha[s]||(Ha[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var vo=bo.exports,Nu=da,Bu=Object,Ms=function(s){return Bu(Nu(s))},Ou=kt,Mu=Ms,Vu=Ou({}.hasOwnProperty),wt=Object.hasOwn||function(e,t){return Vu(Mu(e),t)},Fu=kt,Uu=0,ju=Math.random(),Hu=Fu(1 .toString),So=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Hu(++Uu+ju,36)},Gu=Ke,Yu=vo,Ga=wt,zu=So,qu=fo,Wu=po,hi=Gu.Symbol,fr=Yu("wks"),Qu=Wu?hi.for||hi:hi&&hi.withoutSetter||zu,Je=function(s){return Ga(fr,s)||(fr[s]=qu&&Ga(hi,s)?hi[s]:Qu("Symbol."+s)),fr[s]},Ku=At,Ya=Xt,za=mo,Ju=Os,Xu=Du,Zu=Je,ed=TypeError,td=Zu("toPrimitive"),id=function(s,e){if(!Ya(s)||za(s))return s;var t=Ju(s,td),i;if(t){if(e===void 0&&(e="default"),i=Ku(t,s,e),!Ya(i)||za(i))return i;throw ed("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xu(s,e)},sd=id,rd=mo,ba=function(s){var e=sd(s,"string");return rd(e)?e:e+""},ad=Zt,nd=uo,od=co,Zi=ei,qa=ba,ld=TypeError,pr=Object.defineProperty,ud=Object.getOwnPropertyDescriptor,mr="enumerable",br="configurable",gr="writable";Ti.f=ad?od?function(e,t,i){if(Zi(e),t=qa(t),Zi(i),typeof e=="function"&&t==="prototype"&&"value"in i&&gr in i&&!i[gr]){var r=ud(e,t);r&&r[gr]&&(e[t]=i.value,i={configurable:br in i?i[br]:r[br],enumerable:mr in i?i[mr]:r[mr],writable:!1})}return pr(e,t,i)}:pr:function(e,t,i){if(Zi(e),t=qa(t),Zi(i),nd)try{return pr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw ld("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Vs=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},dd=Zt,cd=Ti,hd=Vs,zi=dd?function(s,e,t){return cd.f(s,e,hd(1,t))}:function(s,e,t){return s[e]=t,s},fd=vo,pd=So,Wa=fd("keys"),ga=function(s){return Wa[s]||(Wa[s]=pd(s))},va={},md=Ql,yo=Ke,bd=Xt,gd=zi,vr=wt,Sr=go,vd=ga,Sd=va,Qa="Object already initialized",Kr=yo.TypeError,yd=yo.WeakMap,ys,ji,Ts,Td=function(s){return Ts(s)?ji(s):ys(s,{})},Ed=function(s){return function(e){var t;if(!bd(e)||(t=ji(e)).type!==s)throw Kr("Incompatible receiver, "+s+" required");return t}};if(md||Sr.state){var et=Sr.state||(Sr.state=new yd);et.get=et.get,et.has=et.has,et.set=et.set,ys=function(s,e){if(et.has(s))throw Kr(Qa);return e.facade=s,et.set(s,e),e},ji=function(s){return et.get(s)||{}},Ts=function(s){return et.has(s)}}else{var ai=vd("state");Sd[ai]=!0,ys=function(s,e){if(vr(s,ai))throw Kr(Qa);return e.facade=s,gd(s,ai,e),e},ji=function(s){return vr(s,ai)?s[ai]:{}},Ts=function(s){return vr(s,ai)}}var $d={set:ys,get:ji,has:Ts,enforce:Td,getterFor:Ed},kd=xs,To=Function.prototype,Ka=To.apply,Ja=To.call,Ad=typeof Reflect=="object"&&Reflect.apply||(kd?Ja.bind(Ka):function(){return Ja.apply(Ka,arguments)}),wd=Ns,Pd=kt,Eo=function(s){if(wd(s)==="Function")return Pd(s)},$o={},ko={},Ao={}.propertyIsEnumerable,wo=Object.getOwnPropertyDescriptor,_d=wo&&!Ao.call({1:2},1);ko.f=_d?function(e){var t=wo(this,e);return!!t&&t.enumerable}:Ao;var Dd=Zt,Rd=At,Id=ko,Cd=Vs,Ld=Yi,xd=ba,Nd=wt,Bd=uo,Xa=Object.getOwnPropertyDescriptor;$o.f=Dd?Xa:function(e,t){if(e=Ld(e),t=xd(t),Bd)try{return Xa(e,t)}catch(i){}if(Nd(e,t))return Cd(!Rd(Id.f,e,t),e[t])};var Od=$t,Md=je,Vd=/#|\.prototype\./,qi=function(s,e){var t=Ud[Fd(s)];return t==Hd?!0:t==jd?!1:Md(e)?Od(e):!!e},Fd=qi.normalize=function(s){return String(s).replace(Vd,".").toLowerCase()},Ud=qi.data={},jd=qi.NATIVE="N",Hd=qi.POLYFILL="P",Gd=qi,Za=Eo,Yd=ma,zd=xs,qd=Za(Za.bind),Po=function(s,e){return Yd(s),e===void 0?s:zd?qd(s,e):function(){return s.apply(e,arguments)}},es=Ke,Wd=Ad,Qd=Eo,Kd=je,Jd=$o.f,Xd=Gd,ni=ca,Zd=Po,oi=zi,en=wt,ec=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Wd(s,this,arguments)};return e.prototype=s.prototype,e},Fs=function(s,e){var t=s.target,i=s.global,r=s.stat,n=s.proto,o=i?es:r?es[t]:(es[t]||{}).prototype,l=i?ni:ni[t]||oi(ni,t,{})[t],d=l.prototype,u,c,h,f,p,m,v,S,b;for(f in e)u=Xd(i?f:t+(r?".":"#")+f,s.forced),c=!u&&o&&en(o,f),m=l[f],c&&(s.dontCallGetSet?(b=Jd(o,f),v=b&&b.value):v=o[f]),p=c&&v?v:e[f],!(c&&typeof m==typeof p)&&(s.bind&&c?S=Zd(p,es):s.wrap&&c?S=ec(p):n&&Kd(p)?S=Qd(p):S=p,(s.sham||p&&p.sham||m&&m.sham)&&oi(S,"sham",!0),oi(l,f,S),n&&(h=t+"Prototype",en(ni,h)||oi(ni,h,{}),oi(ni[h],f,p),s.real&&d&&(u||!d[f])&&oi(d,f,p)))},Jr=Zt,tc=wt,_o=Function.prototype,ic=Jr&&Object.getOwnPropertyDescriptor,Sa=tc(_o,"name"),sc=Sa&&function(){}.name==="something",rc=Sa&&(!Jr||Jr&&ic(_o,"name").configurable),ac={EXISTS:Sa,PROPER:sc,CONFIGURABLE:rc},Do={},nc=Math.ceil,oc=Math.floor,lc=Math.trunc||function(e){var t=+e;return(t>0?oc:nc)(t)},uc=lc,ya=function(s){var e=+s;return e!==e||e===0?0:uc(e)},dc=ya,cc=Math.max,hc=Math.min,fc=function(s,e){var t=dc(s);return t<0?cc(t+e,0):hc(t,e)},pc=ya,mc=Math.min,bc=function(s){return s>0?mc(pc(s),9007199254740991):0},gc=bc,Ta=function(s){return gc(s.length)},vc=Yi,Sc=fc,yc=Ta,tn=function(s){return function(e,t,i){var r=vc(e),n=yc(r),o=Sc(i,n),l;if(s&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in r)&&r[o]===t)return s||o||0;return!s&&-1}},Tc={includes:tn(!0),indexOf:tn(!1)},Ec=kt,yr=wt,$c=Yi,kc=Tc.indexOf,Ac=va,sn=Ec([].push),wc=function(s,e){var t=$c(s),i=0,r=[],n;for(n in t)!yr(Ac,n)&&yr(t,n)&&sn(r,n);for(;e.length>i;)yr(t,n=e[i++])&&(~kc(r,n)||sn(r,n));return r},Ro=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Pc=wc,_c=Ro,Dc=Object.keys||function(e){return Pc(e,_c)},Rc=Zt,Ic=co,Cc=Ti,Lc=ei,xc=Yi,Nc=Dc;Do.f=Rc&&!Ic?Object.defineProperties:function(e,t){Lc(e);for(var i=xc(t),r=Nc(t),n=r.length,o=0,l;n>o;)Cc.f(e,l=r[o++],i[l]);return e};var Bc=ha,Oc=Bc("document","documentElement"),Mc=ei,Vc=Do,rn=Ro,Fc=va,Uc=Oc,jc=lo,Hc=ga,an=">",nn="<",Xr="prototype",Zr="script",Io=Hc("IE_PROTO"),Tr=function(){},Co=function(s){return nn+Zr+an+s+nn+"/"+Zr+an},on=function(s){s.write(Co("")),s.close();var e=s.parentWindow.Object;return s=null,e},Gc=function(){var s=jc("iframe"),e="java"+Zr+":",t;return s.style.display="none",Uc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Co("document.F=Object")),t.close(),t.F},ts,ms=function(){try{ts=new ActiveXObject("htmlfile")}catch(e){}ms=typeof document!="undefined"?document.domain&&ts?on(ts):Gc():on(ts);for(var s=rn.length;s--;)delete ms[Xr][rn[s]];return ms()};Fc[Io]=!0;var Lo=Object.create||function(e,t){var i;return e!==null?(Tr[Xr]=Mc(e),i=new Tr,Tr[Xr]=null,i[Io]=e):i=ms(),t===void 0?i:Vc.f(i,t)},Yc=$t,zc=!Yc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),qc=wt,Wc=je,Qc=Ms,Kc=ga,Jc=zc,ln=Kc("IE_PROTO"),ea=Object,Xc=ea.prototype,xo=Jc?ea.getPrototypeOf:function(s){var e=Qc(s);if(qc(e,ln))return e[ln];var t=e.constructor;return Wc(t)&&e instanceof t?t.prototype:e instanceof ea?Xc:null},Zc=zi,No=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Zc(s,e,t),s},eh=$t,th=je,ih=Xt,sh=Lo,un=xo,rh=No,ah=Je,ta=ah("iterator"),Bo=!1,yt,Er,$r;[].keys&&($r=[].keys(),"next"in $r?(Er=un(un($r)),Er!==Object.prototype&&(yt=Er)):Bo=!0);var nh=!ih(yt)||eh(function(){var s={};return yt[ta].call(s)!==s});nh?yt={}:yt=sh(yt);th(yt[ta])||rh(yt,ta,function(){return this});var Oo={IteratorPrototype:yt,BUGGY_SAFARI_ITERATORS:Bo},oh=Je,lh=oh("toStringTag"),Mo={};Mo[lh]="z";var Ea=String(Mo)==="[object z]",uh=Ea,dh=je,bs=Ns,ch=Je,hh=ch("toStringTag"),fh=Object,ph=bs(function(){return arguments}())=="Arguments",mh=function(s,e){try{return s[e]}catch(t){}},Us=uh?bs:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=mh(e=fh(s),hh))=="string"?t:ph?bs(e):(i=bs(e))=="Object"&&dh(e.callee)?"Arguments":i},bh=Ea,gh=Us,vh=bh?{}.toString:function(){return"[object "+gh(this)+"]"},Sh=Ea,yh=Ti.f,Th=zi,Eh=wt,$h=vh,kh=Je,dn=kh("toStringTag"),Vo=function(s,e,t,i){if(s){var r=t?s:s.prototype;Eh(r,dn)||yh(r,dn,{configurable:!0,value:e}),i&&!Sh&&Th(r,"toString",$h)}},Ah=Oo.IteratorPrototype,wh=Lo,Ph=Vs,_h=Vo,Dh=yi,Rh=function(){return this},Ih=function(s,e,t,i){var r=e+" Iterator";return s.prototype=wh(Ah,{next:Ph(+!i,t)}),_h(s,r,!1,!0),Dh[r]=Rh,s},Ch=Fs,Lh=At,Fo=ac,xh=Ih,Nh=xo,Bh=Vo,cn=No,Oh=Je,hn=yi,Uo=Oo,Mh=Fo.PROPER;Fo.CONFIGURABLE;Uo.IteratorPrototype;var is=Uo.BUGGY_SAFARI_ITERATORS,kr=Oh("iterator"),fn="keys",ss="values",pn="entries",Vh=function(){return this},Fh=function(s,e,t,i,r,n,o){xh(t,e,i);var l=function(b){if(b===r&&f)return f;if(!is&&b in c)return c[b];switch(b){case fn:return function(){return new t(this,b)};case ss:return function(){return new t(this,b)};case pn:return function(){return new t(this,b)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[kr]||c["@@iterator"]||r&&c[r],f=!is&&h||l(r),p=e=="Array"&&c.entries||h,m,v,S;if(p&&(m=Nh(p.call(new s)),m!==Object.prototype&&m.next&&(Bh(m,d,!0,!0),hn[d]=Vh)),Mh&&r==ss&&h&&h.name!==ss&&(u=!0,f=function(){return Lh(h,this)}),r)if(v={values:l(ss),keys:n?f:l(fn),entries:l(pn)},o)for(S in v)(is||u||!(S in c))&&cn(c,S,v[S]);else Ch({target:e,proto:!0,forced:is||u},v);return o&&c[kr]!==f&&cn(c,kr,f,{name:r}),hn[e]=f,v},Uh=function(s,e){return{value:s,done:e}},jh=Yi,mn=yi,jo=$d;Ti.f;var Hh=Fh,rs=Uh,Ho="Array Iterator",Gh=jo.set,Yh=jo.getterFor(Ho);Hh(Array,"Array",function(s,e){Gh(this,{type:Ho,target:jh(s),index:0,kind:e})},function(){var s=Yh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,rs(void 0,!0)):t=="keys"?rs(i,!1):t=="values"?rs(e[i],!1):rs([i,e[i]],!1)},"values");mn.Arguments=mn.Array;var zh=Je,qh=yi,Wh=zh("iterator"),Qh=Array.prototype,Kh=function(s){return s!==void 0&&(qh.Array===s||Qh[Wh]===s)},Jh=Us,bn=Os,Xh=Bs,Zh=yi,ef=Je,tf=ef("iterator"),Go=function(s){if(!Xh(s))return bn(s,tf)||bn(s,"@@iterator")||Zh[Jh(s)]},sf=At,rf=ma,af=ei,nf=pa,of=Go,lf=TypeError,uf=function(s,e){var t=arguments.length<2?of(s):e;if(rf(t))return af(sf(t,s));throw lf(nf(s)+" is not iterable")},df=At,gn=ei,cf=Os,hf=function(s,e,t){var i,r;gn(s);try{if(i=cf(s,"return"),!i){if(e==="throw")throw t;return t}i=df(i,s)}catch(n){r=!0,i=n}if(e==="throw")throw t;if(r)throw i;return gn(i),t},ff=Po,pf=At,mf=ei,bf=pa,gf=Kh,vf=Ta,vn=fa,Sf=uf,yf=Go,Sn=hf,Tf=TypeError,gs=function(s,e){this.stopped=s,this.result=e},yn=gs.prototype,Ef=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=ff(e,i),u,c,h,f,p,m,v,S=function(y){return u&&Sn(u,"normal",y),new gs(!0,y)},b=function(y){return r?(mf(y),l?d(y[0],y[1],S):d(y[0],y[1])):l?d(y,S):d(y)};if(n)u=s.iterator;else if(o)u=s;else{if(c=yf(s),!c)throw Tf(bf(s)+" is not iterable");if(gf(c)){for(h=0,f=vf(s);f>h;h++)if(p=b(s[h]),p&&vn(yn,p))return p;return new gs(!1)}u=Sf(s,c)}for(m=n?s.next:u.next;!(v=pf(m,u)).done;){try{p=b(v.value)}catch(y){Sn(u,"throw",y)}if(typeof p=="object"&&p&&vn(yn,p))return p}return new gs(!1)},$f=ba,kf=Ti,Af=Vs,wf=function(s,e,t){var i=$f(e);i in s?kf.f(s,i,Af(0,t)):s[i]=t},Pf=Fs,_f=Ef,Df=wf;Pf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _f(e,function(i,r){Df(t,i,r)},{AS_ENTRIES:!0}),t}});var Rf=ca,If=Rf.Object.fromEntries,Cf={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},Lf=Cf,xf=Ke,Nf=Us,Bf=zi,Tn=yi,Of=Je,En=Of("toStringTag");for(var Ar in Lf){var $n=xf[Ar],wr=$n&&$n.prototype;wr&&Nf(wr)!==En&&Bf(wr,En,Ar),Tn[Ar]=Tn.Array}var Mf=If,Vf=Mf,Ff=Vf,Uf=Ff,Kt=ua(Uf),ie;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ie||(ie={}));var Ee=(s,e=0,t=ie.OFFSET_P)=>{switch(t){case ie.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ie.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case ie.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:a.assertNever(t)}return s};const Es=(s,e)=>{var t;switch(e){case ie.OFFSET_P:return NaN;case ie.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case ie.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var A=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class J{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||a.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const jf=s=>{switch(s){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(s)}};var U;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(U||(U={}));const Hf=5,Gf=5,Yf=500,kn=7e3;class zf{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(U.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===H.Requested&&i!==U.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case U.PLAYING:case U.PAUSED:case U.READY:break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case U.PLAYING:break;case U.PAUSED:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.READY:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case U.PLAYING:this.videoState.startTransitionTo(U.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case U.PAUSED:break;case U.READY:this.videoState.startTransitionTo(U.PAUSED),this.videoState.setState(U.PAUSED);break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(i)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jf(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(Yf)).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===H.Applying||Math.abs(l-n)>Hf)&&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<Gf&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:a.assertNever(o)}}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({volume:r.value})}),t(a.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),r=>{this.logRemoteEvent(r),this.handleRemoteVolumeChange({muted:r.value})});const i=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(U.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(U.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:H.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PAUSED||e===U.PLAYING)&&(this.videoState.setState(U.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PLAYING||e===U.PAUSED)&&(this.videoState.setState(U.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===U.READY&&this.videoState.setState(U.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==U.STOPPED&&this.videoState.setState(U.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=i[e];a.assertNonNullable(c),r=Ee(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===H.Applying||i.state===H.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(kn).subscribe(()=>n(`timeout(${kn})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.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})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var qf=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Wf=s=>{const e=new a.ValueSubject(1/0),t=new a.Subject,i=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,v;const S=Kt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(g=>g.split(": ")));if("x-playback-duration"in S||"x-playback-duration-millis"in S){const g=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:g*1e3)!==null&&p!==void 0?p:NaN;a.isNonNullable(E)&&!isNaN(E)&&e.next(E)}const b=(m=S["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(v={1:!0,0:!1}[S["x-reused"]])!==null&&v!==void 0?v:void 0;i.next(b),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...v){return d(this),p(...v)},f.progress=function(...v){return u(this),m(...v)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Lt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Qf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Lt}),!0),Kf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Qe=(s,e,t,{equal:i=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=s.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},xt=(s,e,t)=>Qe(e,()=>s.loop,i=>{a.isNonNullable(i)&&(s.loop=i)},{onError:t}),ot=(s,e,t,i)=>Qe(e,()=>({muted:s.muted,volume:s.volume}),r=>{a.isNonNullable(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),Pt=(s,e,t,i)=>Qe(e,()=>s.playbackRate,r=>{a.isNonNullable(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Jf=s=>["__",s.language,s.label].join("|"),Xf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Xe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Qe(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(Qe(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(Qe(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(Qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),a.filterChanged((i,r)=>i.length===r.length&&i.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),a.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),a.filterChanged()).subscribe(this.current$));const t=i=>{var r,n;return this.applyCueSettings((n=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(i=>{var r,n;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Xe.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:n}=e,o=e.id?e.id:Jf(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(i=this.internalTracks.get(o))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!Xf(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const $a=s=>{s.removeAttribute("src"),s.load()},Zf=s=>{try{s.pause(),s.playbackRate=0,$a(s),s.remove()}catch(e){console.error(e)}};class ep{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 ia=window.WeakMap?new WeakMap:new ep,lt=s=>{let e=s.querySelector("video");const t=!!e;return e?$a(e):(e=document.createElement("video"),s.appendChild(e)),ia.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ut=s=>{const e=ia.get(s);ia.delete(s),e?$a(s):Zf(s)};class Wi{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 Yo=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},An=s=>{const e=Yo(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},tp=s=>{const e=Yo(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},sa=3;class ip{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<sa&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||sa))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(r,e):r<e&&n>t?(i(t,n),i(r,e)):i(r,n))})}destroy(){this._buffer=[]}}var zo=(s,e,t=sa)=>{let i=0,r=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,r=l,!t)return{from:i,to:r};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=r&&(r=s.end(d))}}return{from:i,to:r}};const dt=s=>{const e=g=>a.fromEvent(s,g).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=a.merge(...t.map(g=>a.fromEvent(s,g))).pipe(a.map(g=>g.type==="ended"?s.readyState<2:s.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(s,"progress"),a.fromEvent(s,"timeupdate")).pipe(a.map(()=>zo(s.buffered,s.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(s,"volumechange").pipe(a.map(()=>({muted:s.muted,volume:s.volume}))),d=a.fromEvent(s,"ratechange").pipe(a.map(()=>s.playbackRate)),u=a.fromEvent(s,"error").pipe(a.filter(()=>!!(s.error||s.played.length)),a.map(()=>{var g;const T=s.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(g=s.error)!==null&&g!==void 0?g:void 0}})),c=a.fromEvent(s,"timeupdate").pipe(a.map(()=>s.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(g=>{s.loop&&a.isNonNullable(p)&&a.isNonNullable(g)&&p>=s.duration-f&&g<=f&&h.next(p),p=g});const m=a.fromEvent(s,"enterpictureinpicture"),v=a.fromEvent(s,"leavepictureinpicture"),S=new a.ValueSubject(tp(s));m.subscribe(()=>S.next(!0)),v.subscribe(()=>S.next(!1));const b=new a.ValueSubject(An(s));return a.fromEvent(s,"fullscreenchange").pipe(a.map(()=>An(s))).subscribe(b),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:a.fromEvent(s,"durationchange").pipe(a.map(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:S,inFullscreen$:b}},js=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var sp=Fs,rp=Ms,ap=Ta,np=ya;sp({target:"Array",proto:!0},{at:function(e){var t=rp(this),i=ap(t),r=np(e),n=r>=0?r:i+r;return n<0||n>=i?void 0:t[n]}});var op=ha,qo=op,lp=qo,up=lp("Array","at"),dp=up,cp=dp,hp=cp,fp=hp,pe=ua(fp);let ka=!1,St={};const pp=s=>{ka=s},mp=()=>{St={}},bp=s=>{s(St)},as=(s,e)=>{var t;ka&&(St.meta=(t=St.meta)!==null&&t!==void 0?t:{},St.meta[s]=e)};class st{constructor(e){this.name=e}next(e){var t,i;if(!ka)return;St.series=(t=St.series)!==null&&t!==void 0?t:{};const r=(i=St.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),St.series[this.name]=r}}var qt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(qt||(qt={}));const gp=new st("best_bitrate"),vp=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Wo{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Sp='Assertion "ABR Tracks is empty array" failed',ti=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,v,S;a.assertNotEmptyArray(s,Sp);const b=i.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*i.containerSizeFactor,height:e.height*b*i.containerSizeFactor},g=y&&a.videoSizeToQuality(y),T=i.considerPlaybackRate&&a.isNonNullable(l)?l:1,E=s.filter(R=>!a.isInvariantQuality(R.quality)).sort((R,P)=>a.isHigher(R.quality,P.quality)?-1:1),w=(p=pe(E,-1))===null||p===void 0?void 0:p.quality,x=(m=pe(E,0))===null||m===void 0?void 0:m.quality,M=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&a.isLower(r.max,r.min)||a.isNonNullable(r.min)&&x&&a.isHigher(r.min,x)||a.isNonNullable(r.max)&&w&&a.isLower(r.max,w),L=T*vp(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},_=E.filter(R=>(g?a.isLower(R.quality,g):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(R.bitrate)?t-n>=R.bitrate*L:!0)?i.lazyQualitySwitch&&a.isNonNullable(i.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&a.isHigher(R.quality,d.quality)?(B[R.quality]=qt.Buffer,!1):!!c&&a.isHigherOrEqual(R.quality,c)?(B[R.quality]=qt.DroppedFramesLimit,!1):M||(a.isNullable(r.max)||a.isLowerOrEqual(R.quality,r.max))&&(a.isNullable(r.min)||a.isHigherOrEqual(R.quality,r.min))?!0:(B[R.quality]=qt.FitsQualityLimits,!1):(B[R.quality]=qt.FitsThroughput,!1):(B[R.quality]=qt.FitsContainer,!1))[0];_&&_.bitrate&&gp.next(_.bitrate);const D=(v=_!=null?_:E[Math.ceil((E.length-1)/2)])!==null&&v!==void 0?v:s[0];D.quality!==((S=u==null?void 0:u.last)===null||S===void 0?void 0:S.quality)&&h({message:`
|
|
6
|
+
"use strict";var $l=Object.create;var Ca=Object.defineProperty;var kl=Object.getOwnPropertyDescriptor;var wl=Object.getOwnPropertyNames;var Al=Object.getPrototypeOf,Pl=Object.prototype.hasOwnProperty;var _l=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of wl(e))!Pl.call(s,r)&&r!==t&&Ca(s,r,{get:()=>e[r],enumerable:!(i=kl(e,r))||i.enumerable});return s};var La=(s,e,t)=>(t=s!=null?$l(Al(s)):{},_l(e||!s||!s.__esModule?Ca(t,"default",{value:s,enumerable:!0}):t,s));var a=require("@vkontakte/videoplayer-shared/es2018.cjs.js");const so="2.0.98-dev.489417ae.0";exports.PlaybackState=void 0;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(exports.PlaybackState||(exports.PlaybackState={}));exports.VideoFormat=void 0;(function(s){s.MPEG="MPEG",s.DASH="DASH",s.DASH_SEP="DASH_SEP",s.DASH_SEP_VK="DASH_SEP",s.DASH_WEBM="DASH_WEBM",s.DASH_WEBM_AV1="DASH_WEBM_AV1",s.DASH_WEBM_VK="DASH_WEBM",s.DASH_ONDEMAND="DASH_ONDEMAND",s.DASH_ONDEMAND_VK="DASH_ONDEMAND",s.DASH_LIVE="DASH_LIVE",s.DASH_LIVE_CMAF="DASH_LIVE_CMAF",s.DASH_LIVE_WEBM="DASH_LIVE_WEBM",s.HLS="HLS",s.HLS_ONDEMAND="HLS_ONDEMAND",s.HLS_JS="HLS",s.HLS_LIVE="HLS_LIVE",s.HLS_LIVE_CMAF="HLS_LIVE_CMAF",s.WEB_RTC_LIVE="WEB_RTC_LIVE"})(exports.VideoFormat||(exports.VideoFormat={}));var Te;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(Te||(Te={}));exports.ChromecastState=void 0;(function(s){s.NOT_AVAILABLE="NOT_AVAILABLE",s.AVAILABLE="AVAILABLE",s.CONNECTING="CONNECTING",s.CONNECTED="CONNECTED"})(exports.ChromecastState||(exports.ChromecastState={}));exports.HttpConnectionType=void 0;(function(s){s.HTTP1="http1",s.HTTP2="http2",s.QUIC="quic"})(exports.HttpConnectionType||(exports.HttpConnectionType={}));var H;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(H||(H={}));exports.Surface=void 0;(function(s){s.NONE="none",s.INLINE="inline",s.FULLSCREEN="fullscreen",s.SECOND_SCREEN="second_screen",s.PIP="pip"})(exports.Surface||(exports.Surface={}));var Dl=s=>new Promise((e,t)=>{const i=document.createElement("script");i.setAttribute("src",s),i.onload=()=>e,i.onerror=()=>t,document.body.appendChild(i)});class Il{constructor(e){var t;this.connection$=new a.ValueSubject(void 0),this.castState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new a.Subject,this.realCastState$=new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastInitializer");const i="chrome"in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${i}`}),e.isDisabled||!i)return;const r=a.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;r?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Dl("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:a.ErrorCategory.NETWORK,message:"Script loading failed!"})))}connect(){var e;(e=cast.framework.CastContext.getInstance())===null||e===void 0||e.requestSession()}disconnect(){var e,t;(t=(e=cast.framework.CastContext.getInstance())===null||e===void 0?void 0:e.getCurrentSession())===null||t===void 0||t.endSession(!0)}stopMedia(){return new Promise((e,t)=>{var i,r,n;(n=(r=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||r===void 0?void 0:r.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){a.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();a.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();a.isNullable(t)||e!==t.remotePlayer.isMuted&&t.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,t=new cast.framework.RemotePlayerController(e),i=cast.framework.CastContext.getInstance();this.subscription.add(a.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(r=>{var n,o;switch(r.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=(o=(n=i.getCurrentSession())===null||n===void 0?void 0:n.getMediaSession())===null||o===void 0?void 0:o.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return a.assertNever(r.sessionState)}})).add(a.merge(a.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(a.tap(r=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(r)}`})}),a.map(r=>r.castState)),a.observableFrom([i.getCastState()])).pipe(a.filterChanged(),a.map(Rl),a.tap(r=>{this.log({message:`realCastState$: ${r}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(r=>{var n;const o=r===exports.ChromecastState.CONNECTED,l=a.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();a.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(a.isNullable(c)||c===this.contentId)&&(this.log({message:"connection created"}),this.connection$.next({remotePlayer:e,remotePlayerController:t,session:d,castDevice:u}))}else!o&&l&&(this.log({message:"connection destroyed"}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?a.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)}))}initializeCastApi(){var e;let t,i,r;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,r=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:r}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:a.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Rl=s=>{switch(s){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return a.assertNever(s)}};var ar=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ca(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var $t=function(s){try{return!!s()}catch(e){return!0}},Cl=$t,xs=!Cl(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),ro=xs,ao=Function.prototype,Qr=ao.call,Ll=ro&&ao.bind.bind(Qr,Qr),kt=ro?Ll:function(s){return function(){return Qr.apply(s,arguments)}},no=kt,xl=no({}.toString),Nl=no("".slice),Ns=function(s){return Nl(xl(s),8,-1)},Bl=kt,Ol=$t,Ml=Ns,nr=Object,Vl=Bl("".split),Fl=Ol(function(){return!nr("z").propertyIsEnumerable(0)})?function(s){return Ml(s)=="String"?Vl(s,""):nr(s)}:nr,Bs=function(s){return s==null},Ul=Bs,jl=TypeError,ha=function(s){if(Ul(s))throw jl("Can't call method on "+s);return s},Hl=Fl,Gl=ha,Yi=function(s){return Hl(Gl(s))},yi={},Ji=function(s){return s&&s.Math==Math&&s},Ke=Ji(typeof globalThis=="object"&&globalThis)||Ji(typeof window=="object"&&window)||Ji(typeof self=="object"&&self)||Ji(typeof ar=="object"&&ar)||function(){return this}()||ar||Function("return this")(),Kr=typeof document=="object"&&document.all,Yl=typeof Kr=="undefined"&&Kr!==void 0,oo={all:Kr,IS_HTMLDDA:Yl},lo=oo,zl=lo.all,He=lo.IS_HTMLDDA?function(s){return typeof s=="function"||s===zl}:function(s){return typeof s=="function"},ql=Ke,Wl=He,xa=ql.WeakMap,Ql=Wl(xa)&&/native code/.test(String(xa)),Na=He,uo=oo,Kl=uo.all,Xt=uo.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Na(s)||s===Kl}:function(s){return typeof s=="object"?s!==null:Na(s)},Jl=$t,Zt=!Jl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Ti={},Xl=Ke,Ba=Xt,Jr=Xl.document,Zl=Ba(Jr)&&Ba(Jr.createElement),co=function(s){return Zl?Jr.createElement(s):{}},eu=Zt,tu=$t,iu=co,ho=!eu&&!tu(function(){return Object.defineProperty(iu("div"),"a",{get:function(){return 7}}).a!=7}),su=Zt,ru=$t,fo=su&&ru(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),au=Xt,nu=String,ou=TypeError,ei=function(s){if(au(s))return s;throw ou(nu(s)+" is not an object")},lu=xs,Xi=Function.prototype.call,wt=lu?Xi.bind(Xi):function(){return Xi.apply(Xi,arguments)},fa={},or=fa,lr=Ke,uu=He,Oa=function(s){return uu(s)?s:void 0},pa=function(s,e){return arguments.length<2?Oa(or[s])||Oa(lr[s]):or[s]&&or[s][e]||lr[s]&&lr[s][e]},du=kt,ma=du({}.isPrototypeOf),cu=typeof navigator!="undefined"&&String(navigator.userAgent)||"",po=Ke,ur=cu,Ma=po.process,Va=po.Deno,Fa=Ma&&Ma.versions||Va&&Va.version,Ua=Fa&&Fa.v8,We,Ss;Ua&&(We=Ua.split("."),Ss=We[0]>0&&We[0]<4?1:+(We[0]+We[1]));!Ss&&ur&&(We=ur.match(/Edge\/(\d+)/),(!We||We[1]>=74)&&(We=ur.match(/Chrome\/(\d+)/),We&&(Ss=+We[1])));var hu=Ss,ja=hu,fu=$t,pu=Ke,mu=pu.String,mo=!!Object.getOwnPropertySymbols&&!fu(function(){var s=Symbol();return!mu(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&ja&&ja<41}),bu=mo,bo=bu&&!Symbol.sham&&typeof Symbol.iterator=="symbol",gu=pa,vu=He,Su=ma,yu=bo,Tu=Object,go=yu?function(s){return typeof s=="symbol"}:function(s){var e=gu("Symbol");return vu(e)&&Su(e.prototype,Tu(s))},Eu=String,ba=function(s){try{return Eu(s)}catch(e){return"Object"}},$u=He,ku=ba,wu=TypeError,ga=function(s){if($u(s))return s;throw wu(ku(s)+" is not a function")},Au=ga,Pu=Bs,Os=function(s,e){var t=s[e];return Pu(t)?void 0:Au(t)},dr=wt,cr=He,hr=Xt,_u=TypeError,Du=function(s,e){var t,i;if(e==="string"&&cr(t=s.toString)&&!hr(i=dr(t,s))||cr(t=s.valueOf)&&!hr(i=dr(t,s))||e!=="string"&&cr(t=s.toString)&&!hr(i=dr(t,s)))return i;throw _u("Can't convert object to primitive value")},vo={exports:{}},Ha=Ke,Iu=Object.defineProperty,Ru=function(s,e){try{Iu(Ha,s,{value:e,configurable:!0,writable:!0})}catch(t){Ha[s]=e}return e},Cu=Ke,Lu=Ru,Ga="__core-js_shared__",xu=Cu[Ga]||Lu(Ga,{}),So=xu,Ya=So;(vo.exports=function(s,e){return Ya[s]||(Ya[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.31.0",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.31.0/LICENSE",source:"https://github.com/zloirock/core-js"});var yo=vo.exports,Nu=ha,Bu=Object,Ms=function(s){return Bu(Nu(s))},Ou=kt,Mu=Ms,Vu=Ou({}.hasOwnProperty),At=Object.hasOwn||function(e,t){return Vu(Mu(e),t)},Fu=kt,Uu=0,ju=Math.random(),Hu=Fu(1 .toString),To=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Hu(++Uu+ju,36)},Gu=Ke,Yu=yo,za=At,zu=To,qu=mo,Wu=bo,hi=Gu.Symbol,fr=Yu("wks"),Qu=Wu?hi.for||hi:hi&&hi.withoutSetter||zu,Je=function(s){return za(fr,s)||(fr[s]=qu&&za(hi,s)?hi[s]:Qu("Symbol."+s)),fr[s]},Ku=wt,qa=Xt,Wa=go,Ju=Os,Xu=Du,Zu=Je,ed=TypeError,td=Zu("toPrimitive"),id=function(s,e){if(!qa(s)||Wa(s))return s;var t=Ju(s,td),i;if(t){if(e===void 0&&(e="default"),i=Ku(t,s,e),!qa(i)||Wa(i))return i;throw ed("Can't convert object to primitive value")}return e===void 0&&(e="number"),Xu(s,e)},sd=id,rd=go,va=function(s){var e=sd(s,"string");return rd(e)?e:e+""},ad=Zt,nd=ho,od=fo,Zi=ei,Qa=va,ld=TypeError,pr=Object.defineProperty,ud=Object.getOwnPropertyDescriptor,mr="enumerable",br="configurable",gr="writable";Ti.f=ad?od?function(e,t,i){if(Zi(e),t=Qa(t),Zi(i),typeof e=="function"&&t==="prototype"&&"value"in i&&gr in i&&!i[gr]){var r=ud(e,t);r&&r[gr]&&(e[t]=i.value,i={configurable:br in i?i[br]:r[br],enumerable:mr in i?i[mr]:r[mr],writable:!1})}return pr(e,t,i)}:pr:function(e,t,i){if(Zi(e),t=Qa(t),Zi(i),nd)try{return pr(e,t,i)}catch(r){}if("get"in i||"set"in i)throw ld("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Vs=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},dd=Zt,cd=Ti,hd=Vs,zi=dd?function(s,e,t){return cd.f(s,e,hd(1,t))}:function(s,e,t){return s[e]=t,s},fd=yo,pd=To,Ka=fd("keys"),Sa=function(s){return Ka[s]||(Ka[s]=pd(s))},ya={},md=Ql,Eo=Ke,bd=Xt,gd=zi,vr=At,Sr=So,vd=Sa,Sd=ya,Ja="Object already initialized",Xr=Eo.TypeError,yd=Eo.WeakMap,ys,ji,Ts,Td=function(s){return Ts(s)?ji(s):ys(s,{})},Ed=function(s){return function(e){var t;if(!bd(e)||(t=ji(e)).type!==s)throw Xr("Incompatible receiver, "+s+" required");return t}};if(md||Sr.state){var et=Sr.state||(Sr.state=new yd);et.get=et.get,et.has=et.has,et.set=et.set,ys=function(s,e){if(et.has(s))throw Xr(Ja);return e.facade=s,et.set(s,e),e},ji=function(s){return et.get(s)||{}},Ts=function(s){return et.has(s)}}else{var ai=vd("state");Sd[ai]=!0,ys=function(s,e){if(vr(s,ai))throw Xr(Ja);return e.facade=s,gd(s,ai,e),e},ji=function(s){return vr(s,ai)?s[ai]:{}},Ts=function(s){return vr(s,ai)}}var $d={set:ys,get:ji,has:Ts,enforce:Td,getterFor:Ed},kd=xs,$o=Function.prototype,Xa=$o.apply,Za=$o.call,wd=typeof Reflect=="object"&&Reflect.apply||(kd?Za.bind(Xa):function(){return Za.apply(Xa,arguments)}),Ad=Ns,Pd=kt,ko=function(s){if(Ad(s)==="Function")return Pd(s)},wo={},Ao={},Po={}.propertyIsEnumerable,_o=Object.getOwnPropertyDescriptor,_d=_o&&!Po.call({1:2},1);Ao.f=_d?function(e){var t=_o(this,e);return!!t&&t.enumerable}:Po;var Dd=Zt,Id=wt,Rd=Ao,Cd=Vs,Ld=Yi,xd=va,Nd=At,Bd=ho,en=Object.getOwnPropertyDescriptor;wo.f=Dd?en:function(e,t){if(e=Ld(e),t=xd(t),Bd)try{return en(e,t)}catch(i){}if(Nd(e,t))return Cd(!Id(Rd.f,e,t),e[t])};var Od=$t,Md=He,Vd=/#|\.prototype\./,qi=function(s,e){var t=Ud[Fd(s)];return t==Hd?!0:t==jd?!1:Md(e)?Od(e):!!e},Fd=qi.normalize=function(s){return String(s).replace(Vd,".").toLowerCase()},Ud=qi.data={},jd=qi.NATIVE="N",Hd=qi.POLYFILL="P",Gd=qi,tn=ko,Yd=ga,zd=xs,qd=tn(tn.bind),Do=function(s,e){return Yd(s),e===void 0?s:zd?qd(s,e):function(){return s.apply(e,arguments)}},es=Ke,Wd=wd,Qd=ko,Kd=He,Jd=wo.f,Xd=Gd,ni=fa,Zd=Do,oi=zi,sn=At,ec=function(s){var e=function(t,i,r){if(this instanceof e){switch(arguments.length){case 0:return new s;case 1:return new s(t);case 2:return new s(t,i)}return new s(t,i,r)}return Wd(s,this,arguments)};return e.prototype=s.prototype,e},Fs=function(s,e){var t=s.target,i=s.global,r=s.stat,n=s.proto,o=i?es:r?es[t]:(es[t]||{}).prototype,l=i?ni:ni[t]||oi(ni,t,{})[t],d=l.prototype,u,c,h,f,p,m,v,S,g;for(f in e)u=Xd(i?f:t+(r?".":"#")+f,s.forced),c=!u&&o&&sn(o,f),m=l[f],c&&(s.dontCallGetSet?(g=Jd(o,f),v=g&&g.value):v=o[f]),p=c&&v?v:e[f],!(c&&typeof m==typeof p)&&(s.bind&&c?S=Zd(p,es):s.wrap&&c?S=ec(p):n&&Kd(p)?S=Qd(p):S=p,(s.sham||p&&p.sham||m&&m.sham)&&oi(S,"sham",!0),oi(l,f,S),n&&(h=t+"Prototype",sn(ni,h)||oi(ni,h,{}),oi(ni[h],f,p),s.real&&d&&(u||!d[f])&&oi(d,f,p)))},Zr=Zt,tc=At,Io=Function.prototype,ic=Zr&&Object.getOwnPropertyDescriptor,Ta=tc(Io,"name"),sc=Ta&&function(){}.name==="something",rc=Ta&&(!Zr||Zr&&ic(Io,"name").configurable),ac={EXISTS:Ta,PROPER:sc,CONFIGURABLE:rc},Ro={},nc=Math.ceil,oc=Math.floor,lc=Math.trunc||function(e){var t=+e;return(t>0?oc:nc)(t)},uc=lc,Ea=function(s){var e=+s;return e!==e||e===0?0:uc(e)},dc=Ea,cc=Math.max,hc=Math.min,fc=function(s,e){var t=dc(s);return t<0?cc(t+e,0):hc(t,e)},pc=Ea,mc=Math.min,bc=function(s){return s>0?mc(pc(s),9007199254740991):0},gc=bc,$a=function(s){return gc(s.length)},vc=Yi,Sc=fc,yc=$a,rn=function(s){return function(e,t,i){var r=vc(e),n=yc(r),o=Sc(i,n),l;if(s&&t!=t){for(;n>o;)if(l=r[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in r)&&r[o]===t)return s||o||0;return!s&&-1}},Tc={includes:rn(!0),indexOf:rn(!1)},Ec=kt,yr=At,$c=Yi,kc=Tc.indexOf,wc=ya,an=Ec([].push),Ac=function(s,e){var t=$c(s),i=0,r=[],n;for(n in t)!yr(wc,n)&&yr(t,n)&&an(r,n);for(;e.length>i;)yr(t,n=e[i++])&&(~kc(r,n)||an(r,n));return r},Co=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Pc=Ac,_c=Co,Dc=Object.keys||function(e){return Pc(e,_c)},Ic=Zt,Rc=fo,Cc=Ti,Lc=ei,xc=Yi,Nc=Dc;Ro.f=Ic&&!Rc?Object.defineProperties:function(e,t){Lc(e);for(var i=xc(t),r=Nc(t),n=r.length,o=0,l;n>o;)Cc.f(e,l=r[o++],i[l]);return e};var Bc=pa,Oc=Bc("document","documentElement"),Mc=ei,Vc=Ro,nn=Co,Fc=ya,Uc=Oc,jc=co,Hc=Sa,on=">",ln="<",ea="prototype",ta="script",Lo=Hc("IE_PROTO"),Tr=function(){},xo=function(s){return ln+ta+on+s+ln+"/"+ta+on},un=function(s){s.write(xo("")),s.close();var e=s.parentWindow.Object;return s=null,e},Gc=function(){var s=jc("iframe"),e="java"+ta+":",t;return s.style.display="none",Uc.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(xo("document.F=Object")),t.close(),t.F},ts,ms=function(){try{ts=new ActiveXObject("htmlfile")}catch(e){}ms=typeof document!="undefined"?document.domain&&ts?un(ts):Gc():un(ts);for(var s=nn.length;s--;)delete ms[ea][nn[s]];return ms()};Fc[Lo]=!0;var No=Object.create||function(e,t){var i;return e!==null?(Tr[ea]=Mc(e),i=new Tr,Tr[ea]=null,i[Lo]=e):i=ms(),t===void 0?i:Vc.f(i,t)},Yc=$t,zc=!Yc(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),qc=At,Wc=He,Qc=Ms,Kc=Sa,Jc=zc,dn=Kc("IE_PROTO"),ia=Object,Xc=ia.prototype,Bo=Jc?ia.getPrototypeOf:function(s){var e=Qc(s);if(qc(e,dn))return e[dn];var t=e.constructor;return Wc(t)&&e instanceof t?t.prototype:e instanceof ia?Xc:null},Zc=zi,Oo=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Zc(s,e,t),s},eh=$t,th=He,ih=Xt,sh=No,cn=Bo,rh=Oo,ah=Je,sa=ah("iterator"),Mo=!1,yt,Er,$r;[].keys&&($r=[].keys(),"next"in $r?(Er=cn(cn($r)),Er!==Object.prototype&&(yt=Er)):Mo=!0);var nh=!ih(yt)||eh(function(){var s={};return yt[sa].call(s)!==s});nh?yt={}:yt=sh(yt);th(yt[sa])||rh(yt,sa,function(){return this});var Vo={IteratorPrototype:yt,BUGGY_SAFARI_ITERATORS:Mo},oh=Je,lh=oh("toStringTag"),Fo={};Fo[lh]="z";var ka=String(Fo)==="[object z]",uh=ka,dh=He,bs=Ns,ch=Je,hh=ch("toStringTag"),fh=Object,ph=bs(function(){return arguments}())=="Arguments",mh=function(s,e){try{return s[e]}catch(t){}},Us=uh?bs:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=mh(e=fh(s),hh))=="string"?t:ph?bs(e):(i=bs(e))=="Object"&&dh(e.callee)?"Arguments":i},bh=ka,gh=Us,vh=bh?{}.toString:function(){return"[object "+gh(this)+"]"},Sh=ka,yh=Ti.f,Th=zi,Eh=At,$h=vh,kh=Je,hn=kh("toStringTag"),Uo=function(s,e,t,i){if(s){var r=t?s:s.prototype;Eh(r,hn)||yh(r,hn,{configurable:!0,value:e}),i&&!Sh&&Th(r,"toString",$h)}},wh=Vo.IteratorPrototype,Ah=No,Ph=Vs,_h=Uo,Dh=yi,Ih=function(){return this},Rh=function(s,e,t,i){var r=e+" Iterator";return s.prototype=Ah(wh,{next:Ph(+!i,t)}),_h(s,r,!1,!0),Dh[r]=Ih,s},Ch=Fs,Lh=wt,jo=ac,xh=Rh,Nh=Bo,Bh=Uo,fn=Oo,Oh=Je,pn=yi,Ho=Vo,Mh=jo.PROPER;jo.CONFIGURABLE;Ho.IteratorPrototype;var is=Ho.BUGGY_SAFARI_ITERATORS,kr=Oh("iterator"),mn="keys",ss="values",bn="entries",Vh=function(){return this},Fh=function(s,e,t,i,r,n,o){xh(t,e,i);var l=function(g){if(g===r&&f)return f;if(!is&&g in c)return c[g];switch(g){case mn:return function(){return new t(this,g)};case ss:return function(){return new t(this,g)};case bn:return function(){return new t(this,g)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[kr]||c["@@iterator"]||r&&c[r],f=!is&&h||l(r),p=e=="Array"&&c.entries||h,m,v,S;if(p&&(m=Nh(p.call(new s)),m!==Object.prototype&&m.next&&(Bh(m,d,!0,!0),pn[d]=Vh)),Mh&&r==ss&&h&&h.name!==ss&&(u=!0,f=function(){return Lh(h,this)}),r)if(v={values:l(ss),keys:n?f:l(mn),entries:l(bn)},o)for(S in v)(is||u||!(S in c))&&fn(c,S,v[S]);else Ch({target:e,proto:!0,forced:is||u},v);return o&&c[kr]!==f&&fn(c,kr,f,{name:r}),pn[e]=f,v},Uh=function(s,e){return{value:s,done:e}},jh=Yi,gn=yi,Go=$d;Ti.f;var Hh=Fh,rs=Uh,Yo="Array Iterator",Gh=Go.set,Yh=Go.getterFor(Yo);Hh(Array,"Array",function(s,e){Gh(this,{type:Yo,target:jh(s),index:0,kind:e})},function(){var s=Yh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,rs(void 0,!0)):t=="keys"?rs(i,!1):t=="values"?rs(e[i],!1):rs([i,e[i]],!1)},"values");gn.Arguments=gn.Array;var zh=Je,qh=yi,Wh=zh("iterator"),Qh=Array.prototype,Kh=function(s){return s!==void 0&&(qh.Array===s||Qh[Wh]===s)},Jh=Us,vn=Os,Xh=Bs,Zh=yi,ef=Je,tf=ef("iterator"),zo=function(s){if(!Xh(s))return vn(s,tf)||vn(s,"@@iterator")||Zh[Jh(s)]},sf=wt,rf=ga,af=ei,nf=ba,of=zo,lf=TypeError,uf=function(s,e){var t=arguments.length<2?of(s):e;if(rf(t))return af(sf(t,s));throw lf(nf(s)+" is not iterable")},df=wt,Sn=ei,cf=Os,hf=function(s,e,t){var i,r;Sn(s);try{if(i=cf(s,"return"),!i){if(e==="throw")throw t;return t}i=df(i,s)}catch(n){r=!0,i=n}if(e==="throw")throw t;if(r)throw i;return Sn(i),t},ff=Do,pf=wt,mf=ei,bf=ba,gf=Kh,vf=$a,yn=ma,Sf=uf,yf=zo,Tn=hf,Tf=TypeError,gs=function(s,e){this.stopped=s,this.result=e},En=gs.prototype,Ef=function(s,e,t){var i=t&&t.that,r=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=ff(e,i),u,c,h,f,p,m,v,S=function(y){return u&&Tn(u,"normal",y),new gs(!0,y)},g=function(y){return r?(mf(y),l?d(y[0],y[1],S):d(y[0],y[1])):l?d(y,S):d(y)};if(n)u=s.iterator;else if(o)u=s;else{if(c=yf(s),!c)throw Tf(bf(s)+" is not iterable");if(gf(c)){for(h=0,f=vf(s);f>h;h++)if(p=g(s[h]),p&&yn(En,p))return p;return new gs(!1)}u=Sf(s,c)}for(m=n?s.next:u.next;!(v=pf(m,u)).done;){try{p=g(v.value)}catch(y){Tn(u,"throw",y)}if(typeof p=="object"&&p&&yn(En,p))return p}return new gs(!1)},$f=va,kf=Ti,wf=Vs,Af=function(s,e,t){var i=$f(e);i in s?kf.f(s,i,wf(0,t)):s[i]=t},Pf=Fs,_f=Ef,Df=Af;Pf({target:"Object",stat:!0},{fromEntries:function(e){var t={};return _f(e,function(i,r){Df(t,i,r)},{AS_ENTRIES:!0}),t}});var If=fa,Rf=If.Object.fromEntries,Cf={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},Lf=Cf,xf=Ke,Nf=Us,Bf=zi,$n=yi,Of=Je,kn=Of("toStringTag");for(var wr in Lf){var wn=xf[wr],Ar=wn&&wn.prototype;Ar&&Nf(Ar)!==kn&&Bf(Ar,kn,wr),$n[wr]=$n.Array}var Mf=Rf,Vf=Mf,Ff=Vf,Uf=Ff,Kt=ca(Uf),ie;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT",s[s.DASH_CMAF_OFFSET_P=2]="DASH_CMAF_OFFSET_P"})(ie||(ie={}));var $e=(s,e=0,t=ie.OFFSET_P)=>{switch(t){case ie.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case ie.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case ie.DASH_CMAF_OFFSET_P:{const i=new URL(s);return!i.searchParams.get("offset_p")&&e===0?s:(i.searchParams.set("offset_p",e.toFixed(0)),i.toString())}default:a.assertNever(t)}return s};const Es=(s,e)=>{var t;switch(e){case ie.OFFSET_P:return NaN;case ie.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case ie.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:a.assertNever(e)}};var w=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class J{constructor(e){this.transitionStarted$=new a.Subject,this.transitionEnded$=new a.Subject,this.transitionUpdated$=new a.Subject,this.forceChanged$=new a.Subject,this.stateChangeStarted$=a.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=a.merge(this.transitionEnded$,this.forceChanged$),this.state=e,this.prevState=void 0}setState(e){const t=this.transition,i=this.state;this.transition=void 0,this.prevState=i,this.state=e,t?t.to===e?this.transitionEnded$.next(t):this.forceChanged$.next({from:t.from,to:e,canceledTransition:t}):this.forceChanged$.next({from:i,to:e,canceledTransition:t})}startTransitionTo(e){const t=this.transition,i=this.state;i===e||a.isNonNullable(t)&&t.to===e||(this.prevState=i,this.state=e,t?(this.transition={from:t.from,to:e,canceledTransition:t},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}getPrevState(){return this.prevState}}const jf=s=>{switch(s){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_CMAF:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.DASH_LIVE_WEBM:case exports.VideoFormat.WEB_RTC_LIVE:return!0;default:return a.assertNever(s)}};var U;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(U||(U={}));const Hf=5,Gf=5,Yf=500,An=7e3;class zf{constructor(e){this.subscription=new a.Subscription,this.loadMediaTimeoutSubscription=new a.Subscription,this.videoState=new J(U.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),r=this.videoState.getTransition(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(r)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==U.STOPPED&&(this.videoState.startTransitionTo(U.STOPPED),this.stop());return}if(!r){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===H.Requested&&i!==U.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case U.PLAYING:case U.PAUSED:case U.READY:break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case U.PLAYING:break;case U.PAUSED:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.READY:this.videoState.startTransitionTo(U.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case U.PLAYING:this.videoState.startTransitionTo(U.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case U.PAUSED:break;case U.READY:this.videoState.startTransitionTo(U.PAUSED),this.videoState.setState(U.PAUSED);break;case U.STOPPED:this.videoState.startTransitionTo(U.READY),this.prepare();break;default:a.assertNever(i)}break}default:a.assertNever(n)}}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ChromecastProvider"),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next(jf(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(Yf)).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===H.Applying||Math.abs(l-n)>Hf)&&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<Gf&&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 i=a.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));t(i,this.syncPlayback)}restoreSession(e){this.log({message:"restoreSession"});const{remotePlayer:t}=this.params.connection;if(e.playerState!==chrome.cast.media.PlayerState.IDLE){t.isPaused?(this.videoState.setState(U.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(U.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:H.None})}}prepare(){const e=this.params.format;this.log({message:`[prepare] format: ${e}`});const t=this.createMediaInfo(e),i=this.createLoadRequest(t);this.loadMedia(i)}handleRemotePause(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===U.PAUSED||e===U.PLAYING)&&(this.videoState.setState(U.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)===U.PLAYING||e===U.PAUSED)&&(this.videoState.setState(U.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===U.READY&&this.videoState.setState(U.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()!==U.STOPPED&&this.videoState.setState(U.STOPPED)}handleRemoteVolumeChange(e){var t,i;const r=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:r.volume,muted:(i=e.muted)!==null&&i!==void 0?i:r.muted};(n.volume!==r.volume||n.muted!==n.muted)&&this.params.output.volume$.next(n)}seek(e){this.params.output.willSeekEvent$.next();const{remotePlayer:t,remotePlayerController:i}=this.params.connection;t.currentTime=e,i.seek()}stop(){const{remotePlayerController:e}=this.params.connection;e.stop()}createMediaInfo(e){var t;const i=this.params.source;let r,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];a.assertNonNullable(c);const h=a.getHighestQuality(Object.keys(c));a.assertNonNullable(h);const f=c[h];a.assertNonNullable(f),r=f,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/x-mpegurl",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];a.assertNonNullable(c),r=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const c=i[e];a.assertNonNullable(c),r=$e(c.url),n="application/x-mpegurl",o=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.WEB_RTC_LIVE:{const c="Unsupported format for Chromecast",h=new Error(c);throw this.params.output.error$.next({id:"ChromecastProvider.createMediaInfo()",category:a.ErrorCategory.VIDEO_PIPELINE,message:c,thrown:h}),h}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:r,n);l.contentUrl=r,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return a.isNonNullable(d)&&(l.metadata.title=d),a.isNonNullable(u)&&(l.metadata.subtitle=u),l}createLoadRequest(e){const t=new chrome.cast.media.LoadRequest(e);t.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===H.Applying||i.state===H.Requested?t.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:t.currentTime=0,t}loadMedia(e){const t=this.params.connection.session.loadMedia(e),i=new Promise((r,n)=>{this.loadMediaTimeoutSubscription.add(a.timeout(An).subscribe(()=>n(`timeout(${An})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===H.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})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var qf=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:r})=>{i=r<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:r}=this,n=r.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},Wf=s=>{const e=new a.ValueSubject(1/0),t=new a.Subject,i=new a.ValueSubject(void 0),r=new a.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,f,p,m,v;const S=Kt(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 g=(m=S["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(v={1:!0,0:!1}[S["x-reused"]])!==null&&v!==void 0?v:void 0;i.next(g),r.next(y)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const p=f.onload,m=f.progress;f.onload=function(...v){return d(this),p(...v)},f.progress=function(...v){return u(this),m(...v)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:r,connectionType$:i}},Lt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Qf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Lt}),!0),Kf=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[r,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${r}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Qe=(s,e,t,{equal:i=(o,l)=>o===l,changed$:r,onError:n}={})=>{const o=s.getState(),l=e(),d=a.isNullable(r),u=new a.Subscription;return r&&u.add(r.subscribe(c=>{const h=s.getState();i(c,h)&&s.setState(c)},n)),i(l,o)||(t(o),d&&s.setState(o)),u.add(s.stateChangeStarted$.subscribe(c=>{t(c.to),d&&s.setState(c.to)},n)),u},xt=(s,e,t)=>Qe(e,()=>s.loop,i=>{a.isNonNullable(i)&&(s.loop=i)},{onError:t}),ot=(s,e,t,i)=>Qe(e,()=>({muted:s.muted,volume:s.volume}),r=>{a.isNonNullable(r)&&(s.muted=r.muted,s.volume=r.volume)},{equal:(r,n)=>r===n||(r==null?void 0:r.muted)===(n==null?void 0:n.muted)&&(r==null?void 0:r.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),Pt=(s,e,t,i)=>Qe(e,()=>s.playbackRate,r=>{a.isNonNullable(r)&&(s.playbackRate=r)},{changed$:t,onError:i}),Jf=s=>["__",s.language,s.label].join("|"),Xf=(s,e)=>{if(s.id===e)return!0;const[t,i,r]=e.split("|");return s.language===i&&s.label===r};class Xe{constructor(){this.available$=new a.Subject,this.current$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.subscription=new a.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const r=n=>{this.error$.next({id:"TextTracksManager",category:a.ErrorCategory.WTF,message:"Generic HtmlVideoTextTrackManager error",thrown:n})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(Qe(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(Qe(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(Qe(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(Qe(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){a.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(a.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(a.merge(a.fromEvent(e,"addtrack"),a.fromEvent(e,"removetrack"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),a.filterChanged((i,r)=>i.length===r.length&&i.every(({id:n},o)=>n===r[o].id))).subscribe(this.available$)),this.subscription.add(a.merge(a.fromEvent(e,"change"),a.observableFrom(["init"])).pipe(a.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),a.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),a.filterChanged()).subscribe(this.current$));const t=i=>{var r,n;return this.applyCueSettings((n=(r=i.target)===null||r===void 0?void 0:r.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(a.fromEvent(e,"addtrack").subscribe(i=>{var r,n;(r=i.track)===null||r===void 0||r.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,f;const p=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;p&&p.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(a.fromEvent(e,"removetrack").subscribe(i=>{var r;(r=i.track)===null||r===void 0||r.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const r=i;a.isNonNullable(t.align)&&(r.align=t.align),a.isNonNullable(t.position)&&(r.position=t.position),a.isNonNullable(t.size)&&(r.size=t.size),a.isNonNullable(t.line)&&(r.line=t.line)}}htmlTextTracksAsArray(e=!1){a.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Xe.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:r,label:n}=e,o=e.id?e.id:Jf(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:r,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:r,label:n,url:(i=this.internalTracks.get(o))===null||i===void 0?void 0:i.url}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.groupId||e.id===""&&e.label===""&&e.language==="")}setExternal(e){this.internalTracks.size>0&&Array.from(this.internalTracks).forEach(([,t])=>this.detach(t)),e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks).filter(([t])=>!e.find(i=>i.id===t)).forEach(([,t])=>this.detach(t))}setInternal(e){const t=[...this.externalTracks];e.filter(({id:i,language:r,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===r&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(r=>r.id===i)).forEach(([,i])=>this.detach(i))}select(e){a.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(a.isNullable(e)||!Xf(t,e))&&(t.mode="disabled")}destroy(){if(this.subscription.unsubscribe(),this.video)for(const e of Array.from(this.video.getElementsByTagName("track"))){const t=e.getAttribute("id");t&&this.externalTracks.has(t)&&this.video.removeChild(e)}this.externalTracks.clear()}attach(e){a.assertNonNullable(this.video);const t=document.createElement("track");t.setAttribute("src",e.url),t.setAttribute("id",e.id),e.label&&t.setAttribute("label",e.label),e.language&&t.setAttribute("srclang",e.language),e.type==="external"?this.externalTracks.set(e.id,e):e.type==="internal"&&this.internalTracks.set(e.id,e),this.video.appendChild(t)}detach(e){a.assertNonNullable(this.video);const t=Array.prototype.find.call(this.video.getElementsByTagName("track"),i=>i.getAttribute("id")===e.id);t&&this.video.removeChild(t),e.type==="external"?this.externalTracks.delete(e.id):e.type==="internal"&&this.internalTracks.delete(e.id)}}const wa=s=>{s.removeAttribute("src"),s.load()},Zf=s=>{try{s.pause(),s.playbackRate=0,wa(s),s.remove()}catch(e){console.error(e)}};class ep{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 ra=window.WeakMap?new WeakMap:new ep,lt=s=>{let e=s.querySelector("video");const t=!!e;return e?wa(e):(e=document.createElement("video"),s.appendChild(e)),ra.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},ut=s=>{const e=ra.get(s);ra.delete(s),e?wa(s):Zf(s)};class Wi{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 qo=s=>{var e;let t=s;for(;!(t instanceof Document)&&!(t instanceof ShadowRoot)&&t!==null;)t=t==null?void 0:t.parentNode;return(e=t)!==null&&e!==void 0?e:void 0},Pn=s=>{const e=qo(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},tp=s=>{const e=qo(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},aa=3;class ip{constructor(e){this._buffer=[],this._source=e}fill(){this._buffer=[];const e=this._source.currentTime;for(let t=0,i=this._source.buffered.length;t<i;t++){let r=this._source.buffered.start(t);const n=this._source.buffered.end(t);r>e&&r-e<aa&&(r=e),this._buffer.push({from:r,to:n,i:t})}return this._buffer.sort(function(t,i){return t.from-i.from}),this._buffer}getByTime(e){return this._buffer.find(t=>e>=t.from&&e<t.to)}getNextWithGap(e,t){const i=this.getNext(e);if(i&&i.from-e.to<(t||aa))return i}getNext(e){let t=this._buffer.indexOf(e);if(~t&&this._buffer.length-1>t)return this._buffer[++t]}smartRemove(e,t,i){this._buffer.forEach(({from:r,to:n})=>{const o=r>=e&&r<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(r,e):r<e&&n>t?(i(t,n),i(r,e)):i(r,n))})}destroy(){this._buffer=[]}}var Wo=(s,e,t=aa)=>{let i=0,r=0;for(let n=0;n<s.length;n++){const o=s.start(n),l=s.end(n);if(o<=e&&e<=l){if(i=o,r=l,!t)return{from:i,to:r};for(let d=n-1;d>=0;d--)s.end(d)+t>=i&&(i=s.start(d));for(let d=n+1;d<s.length;d++)s.start(d)-t<=r&&(r=s.end(d))}}return{from:i,to:r}};const dt=s=>{const e=b=>a.fromEvent(s,b).pipe(a.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=a.merge(...t.map(b=>a.fromEvent(s,b))).pipe(a.map(b=>b.type==="ended"?s.readyState<2:s.readyState<3),a.filterChanged()),r=a.merge(a.fromEvent(s,"progress"),a.fromEvent(s,"timeupdate")).pipe(a.map(()=>Wo(s.buffered,s.currentTime))),o=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari?a.combine({play:e("play").pipe(a.once()),playing:e("playing")}).pipe(a.mapTo(void 0)):e("playing"),l=a.fromEvent(s,"volumechange").pipe(a.map(()=>({muted:s.muted,volume:s.volume}))),d=a.fromEvent(s,"ratechange").pipe(a.map(()=>s.playbackRate)),u=a.fromEvent(s,"error").pipe(a.filter(()=>!!(s.error||s.played.length)),a.map(()=>{var b;const T=s.error;return{id:T?`MediaError#${T.code}`:"HtmlVideoError",category:a.ErrorCategory.VIDEO_PIPELINE,message:T?T.message:"Error event from HTML video element",thrown:(b=s.error)!==null&&b!==void 0?b:void 0}})),c=a.fromEvent(s,"timeupdate").pipe(a.map(()=>s.currentTime)),h=new a.Subject,f=.3;let p;c.subscribe(b=>{s.loop&&a.isNonNullable(p)&&a.isNonNullable(b)&&p>=s.duration-f&&b<=f&&h.next(p),p=b});const m=a.fromEvent(s,"enterpictureinpicture"),v=a.fromEvent(s,"leavepictureinpicture"),S=new a.ValueSubject(tp(s));m.subscribe(()=>S.next(!0)),v.subscribe(()=>S.next(!1));const g=new a.ValueSubject(Pn(s));return a.fromEvent(s,"fullscreenchange").pipe(a.map(()=>Pn(s))).subscribe(g),{playing$:o,pause$:e("pause").pipe(a.filter(()=>!s.error)),canplay$:e("canplay"),ended$:e("ended"),looped$:h,error$:u,seeked$:e("seeked"),seeking$:e("seeking"),progress$:e("progress"),loadStart$:e("loadstart"),loadedMetadata$:e("loadedmetadata"),loadedData$:e("loadeddata"),timeUpdate$:c,durationChange$:a.fromEvent(s,"durationchange").pipe(a.map(()=>s.duration)),isBuffering$:i,currentBuffer$:r,volumeState$:l,playbackRateState$:d,inPiP$:S,inFullscreen$:g}},js=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var sp=Fs,rp=Ms,ap=$a,np=Ea;sp({target:"Array",proto:!0},{at:function(e){var t=rp(this),i=ap(t),r=np(e),n=r>=0?r:i+r;return n<0||n>=i?void 0:t[n]}});var op=pa,Qo=op,lp=Qo,up=lp("Array","at"),dp=up,cp=dp,hp=cp,fp=hp,pe=ca(fp);let Aa=!1,St={};const pp=s=>{Aa=s},mp=()=>{St={}},bp=s=>{s(St)},as=(s,e)=>{var t;Aa&&(St.meta=(t=St.meta)!==null&&t!==void 0?t:{},St.meta[s]=e)};class st{constructor(e){this.name=e}next(e){var t,i;if(!Aa)return;St.series=(t=St.series)!==null&&t!==void 0?t:{};const r=(i=St.series[this.name])!==null&&i!==void 0?i:[];r.push([Date.now(),e]),St.series[this.name]=r}}var qt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(qt||(qt={}));const gp=new st("best_bitrate"),vp=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Ko{constructor(){this.history={}}recordSelection(e){this.history[e.id]=a.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Sp='Assertion "ABR Tracks is empty array" failed',ti=(s,{container:e,throughput:t,tuning:i,limits:r,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var f,p,m,v,S;a.assertNotEmptyArray(s,Sp);const g=i.usePixelRatio&&(f=window.devicePixelRatio)!==null&&f!==void 0?f:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*g*i.containerSizeFactor,height:e.height*g*i.containerSizeFactor},b=y&&a.videoSizeToQuality(y),T=i.considerPlaybackRate&&a.isNonNullable(l)?l:1,E=s.filter(I=>!a.isInvariantQuality(I.quality)).sort((I,P)=>a.isHigher(I.quality,P.quality)?-1:1),A=(p=pe(E,-1))===null||p===void 0?void 0:p.quality,x=(m=pe(E,0))===null||m===void 0?void 0:m.quality,M=a.isNullable(r)||a.isNonNullable(r.min)&&a.isNonNullable(r.max)&&a.isLower(r.max,r.min)||a.isNonNullable(r.min)&&x&&a.isHigher(r.min,x)||a.isNonNullable(r.max)&&A&&a.isLower(r.max,A),L=T*vp(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),B={},_=E.filter(I=>(b?a.isLower(I.quality,b):!0)?(a.isNonNullable(t)&&isFinite(t)&&a.isNonNullable(I.bitrate)?t-n>=I.bitrate*L:!0)?i.lazyQualitySwitch&&a.isNonNullable(i.minBufferToSwitchUp)&&d&&!a.isInvariantQuality(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&a.isHigher(I.quality,d.quality)?(B[I.quality]=qt.Buffer,!1):!!c&&a.isHigherOrEqual(I.quality,c)?(B[I.quality]=qt.DroppedFramesLimit,!1):M||(a.isNullable(r.max)||a.isLowerOrEqual(I.quality,r.max))&&(a.isNullable(r.min)||a.isHigherOrEqual(I.quality,r.min))?!0:(B[I.quality]=qt.FitsQualityLimits,!1):(B[I.quality]=qt.FitsThroughput,!1):(B[I.quality]=qt.FitsContainer,!1))[0];_&&_.bitrate&&gp.next(_.bitrate);const D=(v=_!=null?_:E[Math.ceil((E.length-1)/2)])!==null&&v!==void 0?v:s[0];D.quality!==((S=u==null?void 0:u.last)===null||S===void 0?void 0:S.quality)&&h({message:`
|
|
7
7
|
[available tracks]
|
|
8
|
-
${s.map(
|
|
8
|
+
${s.map(I=>`{ id: ${I.id}, quality: ${I.quality}, bitrate: ${I.bitrate} }`).join(`
|
|
9
9
|
`)}
|
|
10
10
|
|
|
11
11
|
[tuning]
|
|
12
|
-
${Object.entries(i!=null?i:{}).map(([
|
|
12
|
+
${Object.entries(i!=null?i:{}).map(([I,P])=>`${I}: ${P}`).join(`
|
|
13
13
|
`)}
|
|
14
14
|
|
|
15
15
|
[limit params]
|
|
16
|
-
containerQualityLimit: ${
|
|
16
|
+
containerQualityLimit: ${b},
|
|
17
17
|
throughput: ${t},
|
|
18
18
|
reserve: ${n},
|
|
19
19
|
playbackRate: ${l},
|
|
@@ -27,14 +27,14 @@
|
|
|
27
27
|
minQualityLimit: ${r==null?void 0:r.min},
|
|
28
28
|
|
|
29
29
|
[limited tracks]
|
|
30
|
-
${Object.entries(B).map(([
|
|
30
|
+
${Object.entries(B).map(([I,P])=>`${I}: ${P}`).join(`
|
|
31
31
|
`)||"All tracks are available"}
|
|
32
32
|
|
|
33
33
|
[best track] ${_==null?void 0:_.quality}
|
|
34
34
|
[selected track] ${D==null?void 0:D.quality}
|
|
35
|
-
`});const V=D&&u&&u.history[D.id]&&a.now()-u.history[D.id]<=i.trackCooldown&&(!u.last||D.id!==u.last.id);if(D!=null&&D.id&&u&&!V&&u.recordSelection(D),V&&(u!=null&&u.last)){const
|
|
36
|
-
[last selected] ${
|
|
37
|
-
`}),R}return u==null||u.recordSwitch(D),D};var $e=s=>new URL(s).hostname;const yp=300,Hi=(s,e=yp)=>new a.Observable(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(Pl(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(s),()=>n.disconnect()});class Qi{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:i}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,n=i-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,i)}}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)),i=a.merge(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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,i;const r=(i=(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||i===void 0?void 0:i[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 xi={};var q;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const de=(s,e)=>new a.Observable(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class wn{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(q.DOWNLOADING_LIB),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,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 Wi,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),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===H.Requested&&t!==q.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){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),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case q.STOPPED:this.prepare();break;default:a.assertNever(t)}break}default:a.assertNever(i)}},this.video=lt(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},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(xi.MediaPlayer=r.MediaPlayer,xi.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(xi.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(xi.Debug,"dashjs not loaded"),this.player=xi.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?js(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Kf(this.player),qf(this.player),this.params.tuning.requestQuick&&Qf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(q.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=g=>{e.error$.next({id:"DashIFProvider",category:a.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:g})},r=(g,T)=>this.subscription.add(g.subscribe(T,i));r(Hi(this.video),this.elementSize$),r(de(this.player,"error").pipe(a.map(g=>{const T=typeof g.error=="object"?g.error.code:g.error,E=typeof g.error=="object"?g.error.message:void 0;return{id:`DashJS#${T}`,message:E}})),e.error$),r(de(this.player,"playbackError").pipe(a.map(g=>({id:"DashJSPlayback",message:g.error}))),e.error$);const n=de(this.player,"qualityChangeRendered").pipe(a.filter(({mediaType:g})=>g==="video"),a.map(({newQuality:g})=>{var T;return(T=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===g))===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:g})=>g===q.STREAM_INITIALIZED),a.once()).subscribe(()=>{this.subscription.add(Qe(t.videoTrack,()=>{var g;const T=this.player.getQualityFor("video");return(g=this.videoTracks$.getValue().find(({bitrateInfo:E})=>E.qualityIndex===T))===null||g===void 0?void 0:g.track},g=>{var T;if(a.isNullable(g))return;const E=(T=this.videoTracks$.getValue().find(({track:w})=>w.id===g.id))===null||T===void 0?void 0:T.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n,onError:i}))},i)),this.subscription.add(Qe(t.autoVideoTrackSwitching,()=>{var g,T,E;return(E=(T=(g=this.player.getSettings().streaming)===null||g===void 0?void 0:g.abr)===null||T===void 0?void 0:T.autoSwitchBitrate)===null||E===void 0?void 0:E.video},g=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:g}}}}),{onError:i})),r(de(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:g})=>g==="video"),a.map(({state:g})=>g==="bufferStalled")),e.isBuffering$),r(de(this.player,"fragmentLoadingStarted"),({mediaType:g,request:{url:T}})=>{var E,w;const x=this.player.getDashMetrics(),M=x.getLatestFragmentRequestHeaderValueByID(g,"X-Reused"),L=(E=x.getLatestFragmentRequestHeaderValueByID(g,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,B=(w={1:!0,0:!1}[M])!==null&&w!==void 0?w:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(B),e.hostname$.next($e(T))}),r(de(this.player,"streamInitialized"),({streamInfo:{duration:g,manifestInfo:{isDynamic:T,availableFrom:E}}})=>{this.isLive$.next(T),this.availableFrom$.next(E.getTime()),T||e.duration$.next(g);const w=[],x=this.player.getQualityFor("video");let M;for(const L of this.player.getBitrateInfoListFor("video")){const B=L.qualityIndex.toString(10),O=a.videoSizeToQuality(L),_=L.bitrate/1e3,D={width:L.width,height:L.height},V=this.frameRatesByFrameHeight[L.height];if(O){const R={id:B,quality:O,bitrate:_,size:D,fps:V};w.push({track:R,bitrateInfo:L}),L.qualityIndex===x&&(M=R)}}this.videoTracks$.next(w),e.availableVideoTracks$.next(w.map(({track:L})=>L)),M&&e.currentVideoTrack$.next(M),this.videoState.setState(q.STREAM_INITIALIZED),this.videoState.startTransitionTo(q.READY)}),r(de(this.player,"fragmentLoadingCompleted"),({request:g})=>{if(!g.requestEndDate||!g.firstByteDate||!g.bytesLoaded)return;const T=g.requestEndDate.getTime()-g.firstByteDate.getTime(),E=g.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 g=this.params.dependencies.throughputEstimator.throughput$.getValue(),T=ti(this.videoTracks$.getValue().map(({track:x})=>x),{container:this.elementSize$.getValue(),throughput:g,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 w=this.videoTracks$.getValue().find(({track:x})=>x===T);w!=null&&w.bitrateInfo&&this.player.setQualityFor("video",w==null?void 0:w.bitrateInfo.qualityIndex,!1)}),r(a.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(a.filter(a.isNonNullable))}).pipe(a.filter(({isLive:g})=>g),a.map(({maxSeekBackTime:g})=>-g/1e3)),this.params.output.duration$);const o=de(this.player,"playbackTimeUpdated").pipe(a.map(({time:g})=>g!=null?g:0));r(a.combine({availableFrom:this.availableFrom$.pipe(a.filter(a.isNonNullable)),currentTime:o}),({availableFrom:g,currentTime:T})=>this.params.output.liveTime$.next(g+T*1e3)),r(o.pipe(a.filter(()=>this.isLive$.getValue()===!1)),e.position$),r(de(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(de(this.player,"playbackEnded"),e.endedEvent$),r(de(this.player,"playbackProgress").pipe(a.map(()=>zo(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(de(this.player,"playbackPlaying"),()=>{this.videoState.setState(q.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)}),r(de(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(q.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),r(de(this.player,"playbackPaused"),()=>{this.videoState.setState(q.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)}),r(de(this.player,"canPlay"),()=>{var g;((g=this.videoState.getTransition())===null||g===void 0?void 0:g.to)===q.READY&&this.videoState.setState(q.READY)}),r(this.isLive$,e.isLive$),r(Hi(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}=Wf(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(de(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&r(a.combine({isLive:this.isLive$,isShort:e.duration$.pipe(a.map(g=>g<60))}),({isLive:g,isShort:T})=>{const E=!g&&T;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:E}}})}),r(o.pipe(a.filter(g=>g>this.params.tuning.insufficientBufferRuleMargin),a.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(de(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(de(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(de(this.player,"manifestLoaded"),g=>{var T,E,w,x,M,L,B;if(!((E=(T=g.data)===null||T===void 0?void 0:T.Period)===null||E===void 0)&&E.AdaptationSet){const O=[];for(const _ of(x=(w=g.data)===null||w===void 0?void 0:w.Period)===null||x===void 0?void 0:x.AdaptationSet)if(_.contentType==="text"){const D=(M=_.Representation)===null||M===void 0?void 0:M.id,V=new URL((L=_.Representation)===null||L===void 0?void 0:L.BaseURL,(B=g.data)===null||B===void 0?void 0:B.baseUri).toString(),R="internal",P=_.lang;O.push({id:D,url:V,type:R,language:P})}t.internalTextTracks.startTransitionTo(O)}}),this.subscription.add(xt(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:v,inFullscreen$:S,pause$:b,playing$:y}=dt(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$:b,tracks$:this.videoTracks$.pipe(a.map(g=>g.map(({track:T})=>T)))}),this.subscription.add(ot(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Pt(this.video,t.playbackRate,m,i)),this.subscription.add(v.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),A(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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=Ee(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ie.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){}ut(this.video),this.params.output.element$.next(void 0)}}var Ei=s=>{switch(s){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 Pn=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var _t=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!Pn(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return Pn(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function Te(){return a.now()}function Qo(s){return Te()-s}function _n(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=o=>i.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 Tp(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function vs(s,e,t,i){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,v=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const _=Qo(c);let D;if(_<v){D=v-_,setTimeout(S,D);return}v*=2,v>m&&(v=m),o&&o.abort(),o=new r,w()};const b=_=>(n=_,O),y=_=>(h=_,O),g=()=>(p="json",O),T=()=>{if(!d){if(--u>=0){S(),i&&i();return}d=!0,h&&h(),t&&t()}},E=_=>(f=_,O),w=()=>{c=Te(),o=new r,o.open("get",s);let _=0,D,V=0;const R=()=>(a.assertNonNullable(c),Math.max(c,Math.max(D||0,V||0)));if(n&&o.addEventListener("progress",P=>{const N=Te();n.updateChunk&&P.loaded>_&&(n.updateChunk(R(),P.loaded-_),_=P.loaded,D=N)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const P=o.status;if(P>=200&&P<300){if(o.response.byteLength&&n){const N=o.response.byteLength-_;N&&n.updateChunk&&n.updateChunk(R(),N)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const P=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(V=Te(),o.removeEventListener("readystatechange",P))};o.addEventListener("readystatechange",P)}return o.responseType=p,o.send(),O},O={withBitrateReporting:b,withParallel:E,withJSONResponse:g,withRetryCount:_=>(u=_,O),withRetryInterval:(_,D)=>(a.isNonNullable(_)&&(v=_),a.isNonNullable(D)&&(m=D),O),withTimeout:_=>(l=_,O),withFinally:y,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return O}const Ep=100,$p=2e3,kp=500;let Ap=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,i){return{start:e,end:t,bytes:i}}_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-kp;if(t-e>$p){let i=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=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;i+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&i>0){const n=r*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>Ep&&(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 wp{constructor(e,t,i,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=i,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 i=Te(),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=Te()-i,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=vs(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=Te()}_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=Te();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,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}`),i(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=i,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 ns=1e4,os=3,Pp=300,_p=2e3,Dp=6e4,Rp=10,Ip=1,Cp=500;class Lp{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 Ap(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=_n(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=_n(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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,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):(!i||i.bitrate>n.bitrate)&&(i=n));return r||i}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:i,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{Tp(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 wp(os,ns,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,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,w)=>{d&&d.abort(),d=vs(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withTimeout(ns).withBitrateReporting(this.bitrateSwitcher).withRetryCount(os).withFinally(()=>{d=null}).send()},p=(T,E,w)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=T=>{const E=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),i.playbackRate=T)},v=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 w=Te()-1e4;let x=0;for(let L=0;L<this.bufferStates.length;L++){const B=this.bufferStates[L];T=Math.min(T,B.buf),B.ts<w&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${T} drop=${x} jitter=${this.sourceJitter}`);let M=T-Ip;this.sourceJitter>=0?M-=this.sourceJitter/2:this.sourceJitter-=1,M>3?m(1.15):M>1?m(1.1):M>.3?m(1.05):m(1)}},b=T=>{let E;const w=()=>E&&E.start?E.start.length:0,x=P=>E.start[P]/1e3,M=P=>E.dur[P]/1e3,L=P=>E.fragIndex+P,B=(P,N)=>({chunkIdx:L(P),startTS:x(P),dur:M(P),discontinuity:N}),O=()=>{let P=0;if(E&&E.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=N;this.sourceJitter>1&&(X+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(X-=E.dur[se],!(X<=0));--se);P=Math.min(se,E.dur.length-1-G),P=Math.max(P,0)}return B(P,!0)},_=P=>{const N=w();if(!(N<=0)){if(a.isNonNullable(P)){for(let G=0;G<N;G++)if(x(G)>P)return B(G)}return O()}},D=P=>{const N=w(),G=P?P.chunkIdx+1:0,X=G-E.fragIndex;if(!(N<=0)){if(!P||X<0||X-N>Rp)return t(`Resync: offset=${X} bChunks=${N} chunk=`+JSON.stringify(P)),O();if(!(X>=N))return B(G-E.fragIndex,!1)}},V=(P,N,G)=>{u&&u.abort(),u=vs(this.urlResolver.resolve(P,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(ns).withRetryCount(os).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,N)=>{V(T,G=>{if(!h())return;E=G;const X=!!E.lowLatency;X!==this.lowLatency&&v(X);let se=0;for(let ce=0;ce<E.dur.length;++ce)se+=E.dur[ce];se>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,P(_(N))},()=>this._handleNetworkError())},nextChunk:D}},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:w}=this.params;let x=b(e.jidxUrl),M,L,B,O,_=0,D,V,R;const P=()=>{D&&(clearTimeout(D),D=void 0);const Y=Math.max(Cp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ge=_+Y,Ae=Te(),he=Math.min(1e4,ge-Ae);_=Ae;const le=()=>{u||h()&&x.seek(()=>{h()&&(_=Te(),N(),P())})};he>0?D=window.setTimeout(()=>{this.paused?P():le()},he):le()},N=()=>{let Y;for(;Y=x.nextChunk(O);)O=Y,ke(Y);const ge=x.nextChunk(B);if(ge){if(B&&ge.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?P():(y(),this._initPlayerWith(e));return}ce(ge)}else P()},G=(Y,ge)=>{if(!h()||!this.sourceBuffer)return;let Ae,he,le;const ht=ft=>{window.setTimeout(()=>{h()&&G(Y,ge)},ft)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),ht(100);else{const ft=Te(),Rt=E.currentTime;!this.paused&&E.buffered.length>1&&V===Rt&&ft-R>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),V!==Rt&&(V=Rt,R=ft);const pt=this._getBufferSizeSec();if(pt>30)w(`Buffered ${pt} seconds; delaying appendBuffer`),ht(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:ft,buf:pt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ge&&ge()}catch(ii){if(ii.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),le=this.sourceBuffer.buffered.length,le!==0&&(Ae=this.sourceBuffer.buffered.start(0),he=Rt,he-Ae>4&&this.sourceBuffer.remove(Ae,he-3)),ht(1e3);else throw ii}}},X=()=>{L&&M&&(w([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(B)]),G(L,function(){L=null,N()}))},se=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),ce=Y=>{h()&&p(se(Y),(ge,Ae)=>{if(h()){if(Ae/=1e3,L=ge,B=Y,o=Y.startTS,Ae){const he=Math.min(10,Y.dur/Ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}X()}},()=>this._handleNetworkError())},ke=Y=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(Y),!1)))},Be=Y=>{h()&&(e.cachedHeader=Y,G(Y,()=>{M=!0,X()}))};n=!0,x.seek(Y=>{if(h()){if(_=Te(),!Y){P();return}O=Y,!a.isNullable(T)||Y.startTS>T?ce(Y):(B=Y,N())}},T),e.cachedHeader?Be(e.cachedHeader):f(e.headerUrl,Be,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=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),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=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=Te();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&&Qo(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=Te();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=vs(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ns).withRetryCount(os).withRetryInterval(Pp,_p).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;_t(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,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}`),i({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))},Dp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const xp=[z.PAUSED,z.PLAYING,z.READY],Np=[z.PAUSED,z.PLAYING,z.READY];class Bp{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(z.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new Wi,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Ei(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,v={...h.video};if(!p)continue;const S={id:f,quality:p,bitrate:m,size:v};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)===z.MANIFEST_READY&&this.videoState.setState(z.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!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Np.includes(r)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===H.Requested&&xp.includes(r)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(r){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource(Ee(this.params.source.url));return;case z.MANIFEST_READY:this.videoState.startTransitionTo(z.READY),this.prepare();break;case z.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(z.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(z.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(z.PAUSED)})}return;case z.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case z.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(z.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(z.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(Ee(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=lt(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 i=dt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(a.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(i.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:i.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(xt(this.video,this.params.desiredState.isLooped,t)).add(ot(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.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 z.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case z.MANIFEST_READY:case z.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 z.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case z.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),ut(this.video)}createLiveDashPlayer(){const e=new Lp({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,i,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=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:ti(l.map(({track:v})=>v),{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 v=(o=l.find(({track:S})=>S.id===h))===null||o===void 0?void 0:o.representation;a.assertNonNullable(v,"Representations missing"),this.dash.startPlay(v,u)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;a.assertNonNullable(i,`No such representation ${e.id}`),this.dash.switchByName(i.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(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===z.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(Ee(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}}var Aa=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==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}},_e=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,n=s.end(i)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Op=s=>{const e=document.createElement("a");return e.href=s,e.origin},Mp=s=>{const e=document.createElement("a");return e.href=s,e.host};class Ko{constructor(e,t=[],i,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,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,i,r,n,o,l,d,u;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.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=Kt(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 i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.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(Mp(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 $s{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(i){if(i.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",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=v=>{r($s._str2ua(v.substr(d))),d=v.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=Lt(m)),this._lastXhr=new Ko(m,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const S=Date.now()-u;this._params.onBandwidthChange({size:v.length,duration:S,speed:8*v.length/(S/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),n==null||n()},v=>{if(v.length-d>l&&p(v),h===0){h=Date.now();return}f=v.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=v.length,h=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},o,(v,S,b)=>this._params.onError(v,S,b))})}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(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};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=$s._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 i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);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 Vp{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)?)?$/,i=(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:i(r==null?void 0:r[2],n),months:i(r==null?void 0:r[3],n),weeks:i(r==null?void 0:r[4],n),days:i(r==null?void 0:r[5],n),hours:i(r==null?void 0:r[6],n),minutes:i(r==null?void 0:r[7],n),seconds:i(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Lt(i)),new Ko(i,t,r=>{this.attachManifest(r,t,Op(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,m,v,S,b,y,g,T,E,w,x,M,L,B,O,_;const D=u.getElementsByTagName("SegmentBase")[0],V=D&&o(D,"indexRange").split("-"),R=D&&D.getElementsByTagName("Initialization")[0],P=R&&o(R,"range").split("-");if(!P||!V){const ke=u.parentElement;if((ke==null?void 0:ke.getAttribute("contentType"))==="text"){const Be=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,Y=(i?i+"/":"")+((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),ge=(v=ke.getAttribute("lang"))!==null&&v!==void 0?v:void 0;Y&&d.push({id:Be,url:Y,language:ge})}return}const N=.1,G=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),X=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let se;const ce=(y=(b=u.attributes.getNamedItem("frameRate"))===null||b===void 0?void 0:b.value)!==null&&y!==void 0?y:void 0;se=ce?js(ce):void 0,l.push({width:Number((g=u.attributes.getNamedItem("width"))===null||g===void 0?void 0:g.value),height:Number((T=u.attributes.getNamedItem("height"))===null||T===void 0?void 0:T.value),bandwidth:G,baseURL:X,failoverHosts:t,indexFrom:Number(V[0]),indexTo:Number(V[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(w=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&w!==void 0?w:void 0,mimeType:(M=(x=u.attributes.getNamedItem("mimeType"))===null||x===void 0?void 0:x.value)!==null&&M!==void 0?M:void 0,fps:se,bufferSize:N*G/8,bufferLength:N,name:(B=(L=u.attributes.getNamedItem("okQuality"))===null||L===void 0?void 0:L.value)!==null&&B!==void 0?B:void 0,id:(_=(O=u.attributes.getNamedItem("id"))===null||O===void 0?void 0:O.value)!==null&&_!==void 0?_:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=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()-i)},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 i=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=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new $s({mediaSource:i,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),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),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,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){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 i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<i.to+n){const o=this._findRef(r.toTime);o&&o.toTime<i.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 i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=i[i.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var W;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));const Fp=[W.PAUSED,W.PLAYING];class Up{constructor(e){this.videoState=new J(W.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,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:i})=>{var r,n,o;const l=[];for(const d of t){const u=(n=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Ei(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(i==null?void 0:i.length)>0){const d=[];for(const u of i){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(W.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.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(),i=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(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===H.Requested&&Fp.includes(t)&&this.seek(o.position,o.forcePrecise),t){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_LOADED),this.prepare();return;case W.MANIFEST_LOADED:this.videoState.startTransitionTo(W.INITIAL_REPRESENTATION_SELECTED);return;case W.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(W.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case W.METADATA_LOADED:this.videoState.startTransitionTo(W.READY),this.dash.updateRefsForCurrentTime();return;case W.READY:r===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(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:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=lt(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 ip(this.video),this.dash=new Vp({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:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,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,i=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=dt(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,i));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!==H.Applying)&&(this.videoState.getState()===W.PLAYING||this.videoState.getState()===W.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(xt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pt(this.video,t.playbackRate,n.playbackRateState$,i)),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(Hi(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(W.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).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,v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),b=r();p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to);let y;if(!b&&a.isNonNullable(m))y=m;else{const g=_e(this.video.buffered,this.video.currentTime*1e3),T=b?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/T,1);y=(u=ti(f.map(({track:x})=>x),{container:S,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(d=f.find(({representation:x})=>x===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 w=t.autoVideoTrackLimits.getTransition();w&&e.autoVideoTrackLimits$.next(w.to)}return a.isNonNullable(y)?(c=f.find(({track:g})=>g.id===y))===null||c===void 0?void 0:c.representation:void 0}),a.filterChanged()).subscribe(this.currentRepresentation$,i)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===W.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(W.INITIAL_REPRESENTATION_SELECTED),i)).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=_e(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)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Aa(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,i)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ut(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(){_t(this.video).then(e=>{e||(this.videoState.setState(W.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}}var me;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(me||(me={}));var ks;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ks||(ks={}));var Ve;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Ve||(Ve={}));var Q;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Q||(Q={}));var mi;(function(s){s.MP4="mp4",s.WEBM="webm"})(mi||(mi={}));var As;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(As||(As={}));var ae;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ae||(ae={}));class Dn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[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 Jo extends Dn{constructor(){super(),this.listeners||Dn.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 Xo=class{constructor(){Object.defineProperty(this,"signal",{value:new Jo,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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(Xo.prototype[Symbol.toStringTag]="AbortController",Jo.prototype[Symbol.toStringTag]="AbortSignal");function Zo(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function jp(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!Zo({fetch:e,Request:t,AbortController:i,__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 Hs=Zo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),el=Hs?jp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Jt=Hs?el.fetch:window.fetch;Hs?el.Request:window.Request;const Ue=Hs?Xo:window.AbortController;var bi=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const Hp=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Gp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ws=Gp?Hp:window.requestIdleCallback;var Pr,_r;const Yp=16;let tl=!1;try{tl=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((_r=(Pr=navigator.userAgent.match(/Version\/(\d+)/))===null||Pr===void 0?void 0:Pr[1])!==null&&_r!==void 0?_r:"",10)<=Yp}catch(s){console.error(s)}let zp=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 i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;tl&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}};var Ps=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};let ct=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}},il=class extends ct{},qp=class extends ct{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}},Wp=class extends ct{parseChildrenBoxes(){return $i(this.content)}},Qp=class extends ct{constructor(e){super(e),this.data=this.content}},Ki=class extends ct{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},Kp=class extends Ki{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}},Jp=class extends ct{parseChildrenBoxes(){return $i(this.content)}},Xp=class extends ct{parseChildrenBoxes(){return $i(this.content)}};var Wt;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Wt||(Wt={}));let Zp=class extends Ki{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Wt.MONOSCOPIC;break;case 1:this.stereoMode=Wt.TOP_BOTTOM;break;case 2:this.stereoMode=Wt.LEFT_RIGHT;break;case 3:this.stereoMode=Wt.STEREO_CUSTOM;break;case 4:this.stereoMode=Wt.RIGHT_LEFT;break}this.cursor+=1}},em=class extends Ki{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},tm=class extends Ki{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},im=class extends ct{parseChildrenBoxes(){return $i(this.content)}},sm=class extends Ki{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()}},rm=class extends ct{parseChildrenBoxes(){return $i(this.content)}},am=class extends ct{parseChildrenBoxes(){return $i(this.content)}};const nm={ftyp:qp,moov:Wp,mdat:Qp,sidx:Kp,trak:Jp,mdia:im,tkhd:sm,minf:rm,sv3d:Xp,st3d:Zp,prhd:em,proj:am,equi:tm,unknown:il};let om=class{createBox(e,t){const i=nm[e];return i?new i(t):new il(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Gs.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Gs=new om;function Vi(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,r=[];for(;i<s.byteLength;){const n=t.decode(new DataView(s.buffer,i,1));if(n===e[r.length]?r.push(n):r=[],r.length===4&&r.join("")===e){const l=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+l>s.byteLength?null:Gs.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function lm(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=Vi(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(r)t.push(r),i+=r.size+r.source.byteOffset;else break}return t}function $i(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Gs.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const um=new TextDecoder("ascii"),dm=s=>um.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",cm=s=>{const e=Gs.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:Q.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},hm=s=>{const e=lm(s,"mdat");if(e.length){const t=e.reduce((i,r)=>i+r.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},fm=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:As.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Vi(s,"sv3d")){e.is3dVideo=!0;const i=Vi(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Vi(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=Vi(s,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},pm={validateData:dm,parseInit:fm,getIndexRange:()=>{},parseSegments:cm,parseFeedableSegmentChunk:hm};var $;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})($||($={}));var I;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(I||(I={}));const Rn={[$.EBML]:{type:I.Master},[$.EBMLVersion]:{type:I.UnsignedInteger},[$.EBMLReadVersion]:{type:I.UnsignedInteger},[$.EBMLMaxIDLength]:{type:I.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:I.UnsignedInteger},[$.DocType]:{type:I.String},[$.DocTypeVersion]:{type:I.UnsignedInteger},[$.DocTypeReadVersion]:{type:I.UnsignedInteger},[$.Void]:{type:I.Binary},[$.Segment]:{type:I.Master},[$.SeekHead]:{type:I.Master},[$.Seek]:{type:I.Master},[$.SeekID]:{type:I.Binary},[$.SeekPosition]:{type:I.UnsignedInteger},[$.Info]:{type:I.Master},[$.TimestampScale]:{type:I.UnsignedInteger},[$.Duration]:{type:I.Float},[$.Tracks]:{type:I.Master},[$.TrackEntry]:{type:I.Master},[$.Video]:{type:I.Master},[$.Projection]:{type:I.Master},[$.ProjectionType]:{type:I.UnsignedInteger},[$.ProjectionPrivate]:{type:I.Master},[$.Chapters]:{type:I.Master},[$.Cluster]:{type:I.Master},[$.Timestamp]:{type:I.UnsignedInteger},[$.SilentTracks]:{type:I.Master},[$.SilentTrackNumber]:{type:I.UnsignedInteger},[$.Position]:{type:I.UnsignedInteger},[$.PrevSize]:{type:I.UnsignedInteger},[$.SimpleBlock]:{type:I.Binary},[$.BlockGroup]:{type:I.Master},[$.EncryptedBlock]:{type:I.Binary},[$.Attachments]:{type:I.Master},[$.Tags]:{type:I.Master},[$.Cues]:{type:I.Master},[$.CuePoint]:{type:I.Master},[$.CueTime]:{type:I.UnsignedInteger},[$.CueTrackPositions]:{type:I.Master},[$.CueTrack]:{type:I.UnsignedInteger},[$.CueClusterPosition]:{type:I.UnsignedInteger},[$.CueRelativePosition]:{type:I.UnsignedInteger},[$.CueDuration]:{type:I.UnsignedInteger},[$.CueBlockNumber]:{type:I.UnsignedInteger},[$.CueCodecState]:{type:I.UnsignedInteger},[$.CueReference]:{type:I.Master},[$.CueRefTime]:{type:I.UnsignedInteger}},sl=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=_s(s,t),r=i in Rn,n=r?Rn[i].type:I.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=_s(d),h=u*2**((l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},_s=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},rt=(s,e)=>{switch(e){case I.SignedInteger:return s.getInt8(0);case I.UnsignedInteger:return _s(s);case I.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case I.String:return new TextDecoder("ascii").decode(s);case I.UTF8:return new TextDecoder("utf-8").decode(s);case I.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case I.Master:return s;case I.Binary:return s;default:a.assertNever(e)}},gi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=sl(i);if(!e(r))return;r.type===I.Master&&gi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},mm=s=>{if(s.getUint32(0)!==$.EBML)return!1;let e,t,i;const r=sl(s);return gi(r.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=rt(l,o):n===$.DocType?t=rt(l,o):n===$.DocTypeReadVersion&&(i=rt(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},rl=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],bm=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],gm=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return gi(s,({tag:f,type:p,value:m,valueSize:v})=>{if(f===$.SeekID){const S=rt(m,p);u=_s(S)}else f!==$.SeekPosition&&(u=void 0);return f===$.Segment?(e=m.byteOffset,t=m.byteOffset+v):f===$.Info?n=!0:f===$.SeekHead?o=!0:f===$.TimestampScale?i=rt(m,p):f===$.Duration?r=rt(m,p):f===$.SeekPosition&&u===$.Cues?d=rt(m,p):f===$.Tracks?gi(m,({tag:S,type:b,value:y})=>S===$.ProjectionType?(c=rt(y,b)===1,!1):!0):n&&o&&rl.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:As.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},vm=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Sm=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return gi(s,({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=rt(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=rt(u,d));break;default:t&&rl.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:Q.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}}})},ym=s=>{let e=0,t=!1;try{gi(s,i=>i.tag===$.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):bm.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Tm={validateData:mm,parseInit:gm,getIndexRange:vm,parseSegments:Sm,parseFeedableSegmentChunk:ym},al=1e4,Em=3e4,$m=5e3,km=al,Am=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Ei(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},wm=({id:s,bitrate:e})=>({id:s,bitrate:e}),Pm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=pe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:pe(s,-1)},_m=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),ls=s=>{const e=[];let t=0,i=s.length-1;for(;t<al&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};let In=class{constructor(e,t,i,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 Ue,this.destroyAbortController=new Ue,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=a.abortable(this.destroyAbortController.signal,async function*(c){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 zp(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),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(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Ps(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),p=this.segments.get(h.id),m=this.parsedInitData.get(h.id);a.assertNonNullable(f,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(p,h),yield 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,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;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 this.loadInit(h,"high",!1):p instanceof Promise&&(yield 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;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield 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,async function*(c){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const S of this.representations.keys()){const b=c.find(T=>T.id===S);b&&this.representations.set(S,b);const y=this.representations.get(S);if(!y)return;const g=ls(y.segmentReference.segments);this.segments.set(y.id,g)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,f=this.representations.get(h);a.assertNonNullable(f);const p=ls(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;const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal)),this.searchGaps(p,f),yield 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=i,i){case mi.MP4:this.containerParser=pm;break;case mi.WEBM:this.containerParser=Tm;break;default:a.assertNever(i)}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 Ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=_e(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)&&Ps(this.sourceBuffer.buffered)>=this.bufferLimit){const u=_e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=pe(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===Q.FED&&!l.length&&_e(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=pe(i,-1);d&&d.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const r of e)r.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from}),i=r.time.to;a.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,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 i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o)return;const l=o.segmentReference.segments.map(h=>({...h,status:Q.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(r=pe(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=ls(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,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const v=f<=i&&p>=i,S=f>i||v||m===0&&i===0,b=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=i+b||p<=i+b;return(h===Q.NONE||h===Q.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!bi(this.sourceBuffer.buffered,i))&&S&&y});if(r===-1)return[];if(t!==Ve.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===Q.NONE||f.status===Q.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case Ve.BYTE_RANGE:{r=t.segmentReference.url,n={from:pe(e,0).byte.from,to:pe(e,-1).byte.to};break}case Ve.TEMPLATE:{const u=pe(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=Q.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await a.abortable(d,async function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield 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:i}).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 i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=_e((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,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=Q.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===Q.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=Q.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===Ve.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const S=p?f.byte.from-i:0,b=p?f.byte.to-i:e.byteLength,y=S<r,g=b<=r;if(f.status===Q.DOWNLOADING&&y&&g){f.status=Q.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=Q.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=E.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=ws(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,async function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async l=>{if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,this.isLive?ls(c):c),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){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===Q.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===Q.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===Q.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===Q.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ws(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==Q.FED&&n!==Q.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=Q.PARTIALLY_EJECTED:r.status=Q.NONE)}}};var fi;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(fi||(fi={}));let Dm=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Ue,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,async function*(r){let n=r;this.requestQuic&&(n=Lt(n));const o=yield Jt(n,{signal:this.abortAllController.signal}).catch(Ni);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,async function*(r,{rangeMethod:n=this.compatibilityMode?fi.HEADER:fi.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;let v=r;const S=new Headers;if(o)switch(n){case fi.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case fi.PARAM:{const N=new URL(v,location.href);N.searchParams.append("bytes",`${o.from}-${o.to}`),v=N.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=Lt(v));let b=this.abortAllController.signal,y;if(u){const N=new Ue;if(y=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{N.abort()}catch(G){Ni(G)}}),this.abortAllController.signal.aborted||u.aborted)try{N.abort()}catch(G){Ni(G)}b=N.signal}const g=a.now(),T=yield Jt(v,{priority:d,headers:S,signal:b}).catch(Ni),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!T)return y==null||y.unsubscribe(),null;if(!T.ok||!T.body)return y==null||y.unsubscribe(),Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`));this.onHeadersReceived(T.headers);const w=parseInt((f=T.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!w){const N=yield T.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(N.byteLength,a.now()-E),l==null||l(new DataView(N),N.byteLength),y==null||y.unsubscribe(),N}if(!l&&!c)return y==null||y.unsubscribe(),T.arrayBuffer();const[x,M]=T.body.tee(),L=x.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(M));let B=0;const O=new ArrayBuffer(w),_=new Uint8Array(O),D=new DataView(O);let V=!1;const R=N=>{y==null||y.unsubscribe(),V=!0,Ni(N)},P=a.abortable(b,async function*({done:N,value:G}){if(B===0&&this.lastRequestFirstBytes$.next(a.now()-g),b.aborted){y==null||y.unsubscribe();return}!N&&G&&(_.set(G,B),B+=G.byteLength,l==null||l(D,B),yield L==null?void 0:L.read().then(P,R))}.bind(this));return yield L==null?void 0:L.read().then(P,R),y==null||y.unsubscribe(),V?null:O}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n,o){var l;if(r.type!==Ve.BYTE_RANGE)return 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 v=yield this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!v)return null;const S=new DataView(v,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const b=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(b);if(!y)throw new ReferenceError("No way to load representation index");let g;if(f)g=new DataView(v,y.from-c,y.to-y.from+1);else{const E=yield this.fetch(r.url,{range:y,priority:o,measureThroughput:!1});if(!E)return null;g=new DataView(E)}const T=n.parseSegments(g,b,y);return{init:b,dataView:new DataView(v),segments:T}}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n){if(r.type!==Ve.TEMPLATE)return null;const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:r.segments.map(u=>({...u,status:Q.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Aa(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,n;const{type:o}=e;switch(o){case Ve.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Ve.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const Ni=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Rm=Xt,Im=Ns,Cm=Je,Lm=Cm("match"),xm=function(s){var e;return Rm(s)&&((e=s[Lm])!==void 0?!!e:Im(s)=="RegExp")},Nm=Us,Bm=String,Om=function(s){if(Nm(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Bm(s)},Mm=ei,Vm=function(){var s=Mm(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},Fm=At,Um=wt,jm=fa,Hm=Vm,Cn=RegExp.prototype,Gm=function(s){var e=s.flags;return e===void 0&&!("flags"in Cn)&&!Um(s,"flags")&&jm(Cn,s)?Fm(Hm,s):e},wa=kt,Ym=Ms,zm=Math.floor,Dr=wa("".charAt),qm=wa("".replace),Rr=wa("".slice),Wm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Qm=/\$([$&'`]|\d{1,2})/g,Km=function(s,e,t,i,r,n){var o=t+s.length,l=i.length,d=Qm;return r!==void 0&&(r=Ym(r),d=Wm),qm(n,d,function(u,c){var h;switch(Dr(c,0)){case"$":return"$";case"&":return s;case"`":return Rr(e,0,t);case"'":return Rr(e,o);case"<":h=r[Rr(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=zm(f/10);return p===0?u:p<=l?i[p-1]===void 0?Dr(c,1):i[p-1]+Dr(c,1):u}h=i[f-1]}return h===void 0?"":h})},Jm=Fs,Xm=At,Pa=kt,Ln=da,Zm=je,eb=Bs,tb=xm,li=Om,ib=Os,sb=Gm,rb=Km,ab=Je,nb=ab("replace"),ob=TypeError,nl=Pa("".indexOf),lb=Pa("".replace),xn=Pa("".slice),ub=Math.max,Nn=function(s,e,t){return t>s.length?-1:e===""?t:nl(s,e,t)};Jm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Ln(this),r,n,o,l,d,u,c,h,f,p=0,m=0,v="";if(!eb(e)){if(r=tb(e),r&&(n=li(Ln(sb(e))),!~nl(n,"g")))throw ob("`.replaceAll` does not allow non-global regexes");if(o=ib(e,nb),o)return Xm(o,e,i,t);if(r)return lb(li(i),e,t)}for(l=li(i),d=li(e),u=Zm(t),u||(t=li(t)),c=d.length,h=ub(1,c),p=Nn(l,d,0);p!==-1;)f=u?li(t(d,p,l)):rb(d,l,p,[],void 0,t),v+=xn(l,m,p)+f,m=p+c,p=Nn(l,d,p+h);return m<l.length&&(v+=xn(l,m)),v}});var db=qo,cb=db("String","replaceAll"),hb=cb,fb=hb,pb=fb,mb=pb,Ds=ua(mb);const Bn=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Ir=(s,e)=>{let t=s;t=Ds(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Ds(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},bb=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,m,v,S,b,y,g,T,E,w,x,M,L,B,O,_,D,V,R,P,N,G,X,se,ce,ke,Be,Y;const Ae=new DOMParser().parseFromString(s,"application/xml"),he={video:[],audio:[],text:[]},le=Ae.children[0],ht=le.getElementsByTagName("Period")[0],ft=ht.children,Rt=le.getAttribute("type")==="dynamic",pt=le.getAttribute("availabilityStartTime"),ii=pt?new Date(pt).getTime():void 0;let ve;const ki=le.getAttribute("mediaPresentationDuration"),Ai=ht.getAttribute("duration"),Bt=le.getElementsByTagName("vk:Attrs")[0],wi=Bt==null?void 0:Bt.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ki)ve=Bn(ki);else if(Ai){const re=Bn(Ai);a.isNonNullable(re)&&(ve=re)}else wi&&(ve=parseInt(wi,10));let zs=0;const Ot=(i=(t=le.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],qs=Ot.includes(ks.WEBM_AS_IN_FFMPEG)||Ot.includes(ks.WEBM_AS_IN_SPEC)?mi.WEBM:mi.MP4;for(const re of ft){const mt=re.getAttribute("mimeType"),Ws=re.getAttribute("codecs"),Pi=(r=re.getAttribute("contentType"))!==null&&r!==void 0?r:mt==null?void 0:mt.split("/")[0],Qs=(o=(n=re.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],_i=re.querySelectorAll("Representation"),Ks=re.querySelector("SegmentTemplate");if(Pi===me.TEXT){for(const F of _i){const fe=F.getAttribute("id")||"",bt=re.getAttribute("lang"),De=(u=(d=(l=F.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Mt=new URL(De,e).toString(),Vt=fe.includes("_auto");he[me.TEXT].push({id:fe,lang:bt,isAuto:Vt,kind:me.TEXT,url:Mt})}continue}for(const F of _i){const fe=(c=F.getAttribute("mimeType"))!==null&&c!==void 0?c:mt,bt=(f=(h=F.getAttribute("codecs"))!==null&&h!==void 0?h:Ws)!==null&&f!==void 0?f:"",De=(m=(p=F.getAttribute("contentType"))!==null&&p!==void 0?p:fe==null?void 0:fe.split("/")[0])!==null&&m!==void 0?m:Pi,Mt=(S=(v=re.getAttribute("profiles"))===null||v===void 0?void 0:v.split(","))!==null&&S!==void 0?S:[],Vt=parseInt((b=F.getAttribute("width"))!==null&&b!==void 0?b:"",10),Di=parseInt((y=F.getAttribute("height"))!==null&&y!==void 0?y:"",10),Ri=parseInt((g=F.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,Ii=(T=F.getAttribute("frameRate"))!==null&&T!==void 0?T:"",Js=(E=F.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Xs=Ii?js(Ii):void 0,Zs=(w=F.getAttribute("id"))!==null&&w!==void 0?w:(zs++).toString(10),er=De==="video"?`${Di}p`:De==="audio"?`${Ri}Kbps`:bt,tr=`${Zs}@${er}`,ir=(L=(M=(x=F.querySelector("BaseURL"))===null||x===void 0?void 0:x.textContent)===null||M===void 0?void 0:M.trim())!==null&&L!==void 0?L:"",Ci=new URL(ir,e).toString(),sr=[...Ot,...Qs,...Mt];let Ft;const rr=F.querySelector("SegmentBase"),Se=(B=F.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Ks;if(rr){const Re=(_=(O=F.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&_!==void 0?_:"",[Ie,jt]=Re.split("-").map(Ce=>parseInt(Ce,10)),we={from:Ie,to:jt},Ge=(D=F.querySelector("SegmentBase"))===null||D===void 0?void 0:D.getAttribute("indexRange"),[Ht,gt]=Ge?Ge.split("-").map(Ce=>parseInt(Ce,10)):[],Ye=Ge?{from:Ht,to:gt}:void 0;Ft={type:Ve.BYTE_RANGE,url:Ci,initRange:we,indexRange:Ye}}else if(Se){const Re={representationId:(V=F.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(R=F.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Ie=parseInt((P=Se.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),jt=(N=Se.getAttribute("initialization"))!==null&&N!==void 0?N:"",we=Se.getAttribute("media"),Ge=(X=parseInt((G=Se.getAttribute("startNumber"))!==null&&G!==void 0?G:"",10))!==null&&X!==void 0?X:1,Ht=Ir(jt,Re);if(!we)throw new ReferenceError("No media attribute in SegmentTemplate");const gt=(se=Se.querySelectorAll("SegmentTimeline S"))!==null&&se!==void 0?se:[],Ye=[];let Ce=0;if(gt.length){let Gt=Ge,Le=0;for(const Yt of gt){const xe=parseInt((ce=Yt.getAttribute("d"))!==null&&ce!==void 0?ce:"",10),ue=parseInt((ke=Yt.getAttribute("r"))!==null&&ke!==void 0?ke:"",10)||0,ze=parseInt((Be=Yt.getAttribute("t"))!==null&&Be!==void 0?Be:"",10);Le=Number.isFinite(ze)?ze:Le;const Pe=xe/Ie*1e3,Ze=Le/Ie*1e3;for(let vt=0;vt<ue+1;vt++){const Li=Ir(we,{...Re,segmentNumber:Gt.toString(10),segmentTime:(Le+vt*xe).toString(10)}),si=(Ze||0)+vt*Pe,ri=si+Pe;Gt++,Ye.push({time:{from:si,to:ri},url:Li})}Le+=(ue+1)*xe,Ce+=(ue+1)*Pe}}else if(a.isNonNullable(ve)){const Le=parseInt((Y=Se.getAttribute("duration"))!==null&&Y!==void 0?Y:"",10)/Ie*1e3,Yt=Math.ceil(ve/Le);let xe=0;for(let ue=1;ue<Yt;ue++){const ze=Ir(we,{...Re,segmentNumber:ue.toString(10),segmentTime:xe.toString(10)});Ye.push({time:{from:xe,to:xe+Le},url:ze}),xe+=Le}}Ft={type:Ve.TEMPLATE,baseUrl:Ci,initUrl:Ht,totalSegmentsDurationMs:Ce,segments:Ye}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!De||!fe)continue;const Ut={video:me.VIDEO,audio:me.AUDIO,text:me.TEXT}[De];Ut&&he[Ut].push({id:tr,kind:Ut,segmentReference:Ft,profiles:sr,duration:ve,bitrate:Ri,mime:fe,codecs:bt,width:Vt,height:Di,fps:Xs,quality:Js})}}return{dynamic:Rt,liveAvailabilityStartTime:ii,duration:ve,container:qs,representations:he}},ra=1e3,On=["timeupdate","progress","play","seeked","stalled","waiting"];var Oe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Oe||(Oe={}));let gb=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new J(Oe.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 Ue,this.initManifest=a.abortable(this.destroyController.signal,async function*(t,i,r){var n;this.element=t,this.manifestUrlString=Ee(i,r,ie.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Oe.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Oe.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,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!i)return this.manifest;let r;try{r=bb(i!=null?i:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return 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===me.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)),{...r,representations:Kt(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,async function*(t,i){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Oe.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 In(me.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new In(me.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(ra).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=Es(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ee(this.manifestUrlString,u+1e3,ie.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...On.map(l=>a.fromEvent(this.element,l))).pipe(a.throttle(ra),a.map(l=>this.element?_e(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 v,S;return(S=(v=m.getLiveSegmentsToLoadState(this.manifest))===null||v===void 0?void 0:v.to)!==null&&S!==void 0?S:0}))-f}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async d=>{a.assertNonNullable(this.element);const u=this.element.playbackRate,c=Es(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P),h=Em*u,f=km*u,p=$m*u;l=d>l?d:l;const m=c===0&&d<p,v=c!==0&&d<h+p&&d>=h,S=c!==0&&d<h;if(S||v){const b=l-(h+f),y=Math.trunc(c+b/u);let g;d?y>0?g=y:g=0:g=c,this.manifestUrlString=Ee(this.manifestUrlString,g,ie.DASH_CMAF_OFFSET_P)}(m||S||v)&&(await 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 new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Oe.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Dm({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async seekLive(e){var t,i,r,n;a.assertNonNullable(this.element),this.manifestUrlString=Ee(this.manifestUrlString,e,ie.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((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(Oe.RUNNING),this.subscription.add(a.merge(...On.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&&bi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[me.VIDEO]:this.videoBufferManager,[me.AUDIO]:this.audioBufferManager,[me.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),bi(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(Oe.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}async updateLive(){var e;this.manifest=await 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,i=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class vb{constructor(e,t){this.fov=e,this.orientation=t}}class Sb{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/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...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,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var yb=`#define GLSLIFY 1
|
|
35
|
+
`});const V=D&&u&&u.history[D.id]&&a.now()-u.history[D.id]<=i.trackCooldown&&(!u.last||D.id!==u.last.id);if(D!=null&&D.id&&u&&!V&&u.recordSelection(D),V&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),h({message:`
|
|
36
|
+
[last selected] ${I==null?void 0:I.quality}
|
|
37
|
+
`}),I}return u==null||u.recordSwitch(D),D};var ke=s=>new URL(s).hostname;const yp=300,Hi=(s,e=yp)=>new a.Observable(t=>{const{width:i,height:r}=s.getBoundingClientRect();if(t.next({width:i,height:r}),!window.ResizeObserver)return;const n=new ResizeObserver(a.debounceFn(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(s),()=>n.disconnect()});class Qi{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:i}=this.video.getVideoPlaybackQuality(),r=t-this.prevTotalVideoFrames,n=i-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,i)}}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)),i=a.merge(e,t);this.subscription.add(i.subscribe(this.checkDroppedFrames))}onChangeQuality(e){this.currentQuality=e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality();this.savePrevFrameCounts(t,i),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,i;const r=(i=(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||i===void 0?void 0:i[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 xi={};var q;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(q||(q={}));const de=(s,e)=>new a.Observable(t=>{const i=r=>t.next(r);return s.on(e,i),()=>s.off(e,i)});class _n{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(q.DOWNLOADING_LIB),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,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 Wi,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),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===H.Requested&&t!==q.STOPPED&&i!==exports.PlaybackState.STOPPED&&(o?this.seek(n.position-this.liveOffset.getTotalPausedTime()):this.seek(n.position)),i){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(i)}},this.video=lt(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(ke(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},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(r=>{e||(xi.MediaPlayer=r.MediaPlayer,xi.Debug=r.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(xi.MediaPlayer,"dashjs not loaded"),a.assertNonNullable(xi.Debug,"dashjs not loaded"),this.player=xi.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?js(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&Kf(this.player),qf(this.player),this.params.tuning.requestQuick&&Qf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(q.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=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,i));r(Hi(this.video),this.elementSize$),r(de(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(de(this.player,"playbackError").pipe(a.map(b=>({id:"DashJSPlayback",message:b.error}))),e.error$);const n=de(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(Qe(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:A})=>A.id===b.id))===null||T===void 0?void 0:T.bitrateInfo;E&&this.player.setQualityFor("video",E.qualityIndex)},{changed$:n,onError:i}))},i)),this.subscription.add(Qe(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:i})),r(de(this.player,"bufferStateChanged").pipe(a.filter(({mediaType:b})=>b==="video"),a.map(({state:b})=>b==="bufferStalled")),e.isBuffering$),r(de(this.player,"fragmentLoadingStarted"),({mediaType:b,request:{url:T}})=>{var E,A;const x=this.player.getDashMetrics(),M=x.getLatestFragmentRequestHeaderValueByID(b,"X-Reused"),L=(E=x.getLatestFragmentRequestHeaderValueByID(b,"X-Delivery-Type"))!==null&&E!==void 0?E:exports.HttpConnectionType.HTTP1,B=(A={1:!0,0:!1}[M])!==null&&A!==void 0?A:void 0;this.params.output.httpConnectionType$.next(L),this.params.output.httpConnectionReused$.next(B),e.hostname$.next(ke(T))}),r(de(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 A=[],x=this.player.getQualityFor("video");let M;for(const L of this.player.getBitrateInfoListFor("video")){const B=L.qualityIndex.toString(10),O=a.videoSizeToQuality(L),_=L.bitrate/1e3,D={width:L.width,height:L.height},V=this.frameRatesByFrameHeight[L.height];if(O){const I={id:B,quality:O,bitrate:_,size:D,fps:V};A.push({track:I,bitrateInfo:L}),L.qualityIndex===x&&(M=I)}}this.videoTracks$.next(A),e.availableVideoTracks$.next(A.map(({track:L})=>L)),M&&e.currentVideoTrack$.next(M),this.videoState.setState(q.STREAM_INITIALIZED),this.videoState.startTransitionTo(q.READY)}),r(de(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=ti(this.videoTracks$.getValue().map(({track:x})=>x),{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 A=this.videoTracks$.getValue().find(({track:x})=>x===T);A!=null&&A.bitrateInfo&&this.player.setQualityFor("video",A==null?void 0:A.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=de(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(de(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),r(de(this.player,"playbackEnded"),e.endedEvent$),r(de(this.player,"playbackProgress").pipe(a.map(()=>Wo(this.video.buffered,this.video.currentTime))),e.currentBuffer$),r(de(this.player,"playbackPlaying"),()=>{this.videoState.setState(q.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)}),r(de(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(de(this.player,"playbackPaused"),()=>{this.videoState.setState(q.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)}),r(de(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(Hi(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}=Wf(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(de(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(de(this.player,"manifestLoaded").pipe(a.once()).subscribe(()=>{this.subscription.add(de(this.player,"playbackPlaying").pipe(a.once(),a.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),r(de(this.player,"manifestLoaded"),b=>{var T,E,A,x,M,L,B;if(!((E=(T=b.data)===null||T===void 0?void 0:T.Period)===null||E===void 0)&&E.AdaptationSet){const O=[];for(const _ of(x=(A=b.data)===null||A===void 0?void 0:A.Period)===null||x===void 0?void 0:x.AdaptationSet)if(_.contentType==="text"){const D=(M=_.Representation)===null||M===void 0?void 0:M.id,V=new URL((L=_.Representation)===null||L===void 0?void 0:L.BaseURL,(B=b.data)===null||B===void 0?void 0:B.baseUri).toString(),I="internal",P=_.lang;O.push({id:D,url:V,type:I,language:P})}t.internalTextTracks.startTransitionTo(O)}}),this.subscription.add(xt(this.video,t.isLooped,i));const{volumeState$:f,looped$:p,playbackRateState$:m,inPiP$:v,inFullscreen$:S,pause$:g,playing$:y}=dt(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$:g,tracks$:this.videoTracks$.pipe(a.map(b=>b.map(({track:T})=>T)))}),this.subscription.add(ot(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(p.subscribe(e.loopedEvent$)),this.subscription.add(Pt(this.video,t.playbackRate,m,i)),this.subscription.add(v.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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const r=$e(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,ie.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){}ut(this.video),this.params.output.element$.next(void 0)}}var Ei=s=>{switch(s){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 Dn=s=>{if(s instanceof DOMException&&["Failed to load because no supported source was found.","The element has no supported sources."].includes(s.message))throw s;return!(s instanceof DOMException&&(s.code===20||s.name==="AbortError"))};var _t=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!Dn(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return Dn(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function Ee(){return a.now()}function Jo(s){return Ee()-s}function In(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,r=o=>i.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 Tp(s,e,t){const i=(...r)=>{t.apply(null,r),s.removeEventListener(e,i)};s.addEventListener(e,i)}function vs(s,e,t,i){const r=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,p="arraybuffer",m=7e3,v=2e3,S=()=>{if(d)return;a.assertNonNullable(c);const _=Jo(c);let D;if(_<v){D=v-_,setTimeout(S,D);return}v*=2,v>m&&(v=m),o&&o.abort(),o=new r,A()};const g=_=>(n=_,O),y=_=>(h=_,O),b=()=>(p="json",O),T=()=>{if(!d){if(--u>=0){S(),i&&i();return}d=!0,h&&h(),t&&t()}},E=_=>(f=_,O),A=()=>{c=Ee(),o=new r,o.open("get",s);let _=0,D,V=0;const I=()=>(a.assertNonNullable(c),Math.max(c,Math.max(D||0,V||0)));if(n&&o.addEventListener("progress",P=>{const N=Ee();n.updateChunk&&P.loaded>_&&(n.updateChunk(I(),P.loaded-_),_=P.loaded,D=N)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>T())),o.addEventListener("load",()=>{if(d)return;a.assertNonNullable(o);const P=o.status;if(P>=200&&P<300){if(o.response.byteLength&&n){const N=o.response.byteLength-_;N&&n.updateChunk&&n.updateChunk(I(),N)}h&&h(),o&&e(o.response)}else T()}),o.addEventListener("error",()=>{T()}),f){const P=()=>{a.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(V=Ee(),o.removeEventListener("readystatechange",P))};o.addEventListener("readystatechange",P)}return o.responseType=p,o.send(),O},O={withBitrateReporting:g,withParallel:E,withJSONResponse:b,withRetryCount:_=>(u=_,O),withRetryInterval:(_,D)=>(a.isNonNullable(_)&&(v=_),a.isNonNullable(D)&&(m=D),O),withTimeout:_=>(l=_,O),withFinally:y,send:A,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return O}const Ep=100,$p=2e3,kp=500;let wp=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,i){return{start:e,end:t,bytes:i}}_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-kp;if(t-e>$p){let i=0,r=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=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;i+=o;const d=n.bytes*o/l;r+=d,n.start=t,n.bytes-=d}}}if(r>0&&i>0){const n=r*8/(i/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(i)} 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,i){return this.intervals.push(this._createInterval(e,t,i)),this._joinIntervals(),this.intervals.length>Ep&&(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 Ap{constructor(e,t,i,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=i,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 i=Ee(),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=Ee()-i,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=vs(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=Ee()}_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=Ee();if(Object.keys(this.activeRequests).length>=e)return!1;const i=this._getPrefetchDelay()-(t-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),i>0?(this.throttleTimeout=window.setTimeout(()=>this._sendPending(),i),!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,i,r){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,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}`),i(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=i,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 ns=1e4,os=3,Pp=300,_p=2e3,Dp=6e4,Ip=10,Rp=1,Cp=500;class Lp{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 wp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=In(e),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(e){this.autoQuality=e}setMaxAutoQuality(e){this.maxAutoQuality=e}switchByName(e){let t;for(let i=0;i<this.manifest.length;++i)if(t=this.manifest[i],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=In(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 i=e.buffered.length;return i!==0&&(t=e.buffered.end(i-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 i;!!e.error&&!this.destroyed&&(t(`Video element error: ${(i=e.error)===null||i===void 0?void 0:i.code}`),this.params.playerCallback({name:"error",type:"media"}))}),e.addEventListener("timeupdate",()=>{const i=this._getBufferSizeSec();!this.paused&&i<.3?this.buffering||(this.buffering=!0,window.setTimeout(()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0)},(i+.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,i=t.buffered.length;let r;i!==0&&(r=t.buffered.start(i-1),t.currentTime<r&&(e("Fixup stall"),t.currentTime=r))}_selectQuality(e){const{videoElement:t}=this.params;let i,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):(!i||i.bitrate>n.bitrate)&&(i=n));return r||i}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:i,videoElement:r,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("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=()=>{Tp(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 Ap(os,ns,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,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,A)=>{d&&d.abort(),d=vs(this.urlResolver.resolve(T,!1),E,A,()=>this._retryCallback()).withTimeout(ns).withBitrateReporting(this.bitrateSwitcher).withRetryCount(os).withFinally(()=>{d=null}).send()},p=(T,E,A)=>{a.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(T,!1),E,A,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=T=>{const E=i.playbackRate;i.playbackRate!==T&&(t(`Playback rate switch: ${E}=>${T}`),i.playbackRate=T)},v=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 A=Ee()-1e4;let x=0;for(let L=0;L<this.bufferStates.length;L++){const B=this.bufferStates[L];T=Math.min(T,B.buf),B.ts<A&&x++}this.bufferStates.splice(0,x),t(`update playback rate; minBuffer=${T} drop=${x} jitter=${this.sourceJitter}`);let M=T-Rp;this.sourceJitter>=0?M-=this.sourceJitter/2:this.sourceJitter-=1,M>3?m(1.15):M>1?m(1.1):M>.3?m(1.05):m(1)}},g=T=>{let E;const A=()=>E&&E.start?E.start.length:0,x=P=>E.start[P]/1e3,M=P=>E.dur[P]/1e3,L=P=>E.fragIndex+P,B=(P,N)=>({chunkIdx:L(P),startTS:x(P),dur:M(P),discontinuity:N}),O=()=>{let P=0;if(E&&E.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,G=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=N;this.sourceJitter>1&&(X+=this.sourceJitter-1);let se=E.dur.length-1;for(;se>=0&&(X-=E.dur[se],!(X<=0));--se);P=Math.min(se,E.dur.length-1-G),P=Math.max(P,0)}return B(P,!0)},_=P=>{const N=A();if(!(N<=0)){if(a.isNonNullable(P)){for(let G=0;G<N;G++)if(x(G)>P)return B(G)}return O()}},D=P=>{const N=A(),G=P?P.chunkIdx+1:0,X=G-E.fragIndex;if(!(N<=0)){if(!P||X<0||X-N>Ip)return t(`Resync: offset=${X} bChunks=${N} chunk=`+JSON.stringify(P)),O();if(!(X>=N))return B(G-E.fragIndex,!1)}},V=(P,N,G)=>{u&&u.abort(),u=vs(this.urlResolver.resolve(P,!0,this.lowLatency),N,G,()=>this._retryCallback()).withTimeout(ns).withRetryCount(os).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(P,N)=>{V(T,G=>{if(!h())return;E=G;const X=!!E.lowLatency;X!==this.lowLatency&&v(X);let se=0;for(let ce=0;ce<E.dur.length;++ce)se+=E.dur[ce];se>0&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(se/E.dur.length)),r({name:"index",zeroTime:E.zeroTime,shiftDuration:E.shiftDuration}),this.sourceJitter=E.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,E.jitter/1e3)):1,P(_(N))},()=>this._handleNetworkError())},nextChunk:D}},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:A}=this.params;let x=g(e.jidxUrl),M,L,B,O,_=0,D,V,I;const P=()=>{D&&(clearTimeout(D),D=void 0);const Y=Math.max(Cp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ve=_+Y,Ae=Ee(),he=Math.min(1e4,ve-Ae);_=Ae;const le=()=>{u||h()&&x.seek(()=>{h()&&(_=Ee(),N(),P())})};he>0?D=window.setTimeout(()=>{this.paused?P():le()},he):le()},N=()=>{let Y;for(;Y=x.nextChunk(O);)O=Y,we(Y);const ve=x.nextChunk(B);if(ve){if(B&&ve.discontinuity){A("Detected discontinuity; restarting playback"),this.paused?P():(y(),this._initPlayerWith(e));return}ce(ve)}else P()},G=(Y,ve)=>{if(!h()||!this.sourceBuffer)return;let Ae,he,le;const ht=ft=>{window.setTimeout(()=>{h()&&G(Y,ve)},ft)};if(this.sourceBuffer.updating)A("Source buffer is updating; delaying appendBuffer"),ht(100);else{const ft=Ee(),It=E.currentTime;!this.paused&&E.buffered.length>1&&V===It&&ft-I>500&&(A("Stall suspected; trying to fix"),this._fixupStall()),V!==It&&(V=It,I=ft);const pt=this._getBufferSizeSec();if(pt>30)A(`Buffered ${pt} seconds; delaying appendBuffer`),ht(2e3);else try{this.sourceBuffer.appendBuffer(Y),this.videoPlayStarted?(this.bufferStates.push({ts:ft,buf:pt}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ve&&ve()}catch(ii){if(ii.name==="QuotaExceededError")A("QuotaExceededError; delaying appendBuffer"),le=this.sourceBuffer.buffered.length,le!==0&&(Ae=this.sourceBuffer.buffered.start(0),he=It,he-Ae>4&&this.sourceBuffer.remove(Ae,he-3)),ht(1e3);else throw ii}}},X=()=>{L&&M&&(A([`Appending chunk, sz=${L.byteLength}:`,JSON.stringify(B)]),G(L,function(){L=null,N()}))},se=Y=>e.fragUrlTemplate.replace("%%id%%",Y.chunkIdx),ce=Y=>{h()&&p(se(Y),(ve,Ae)=>{if(h()){if(Ae/=1e3,L=ve,B=Y,o=Y.startTS,Ae){const he=Math.min(10,Y.dur/Ae);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*he:he}X()}},()=>this._handleNetworkError())},we=Y=>{h()&&(a.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(se(Y),!1)))},Oe=Y=>{h()&&(e.cachedHeader=Y,G(Y,()=>{M=!0,X()}))};n=!0,x.seek(Y=>{if(h()){if(_=Ee(),!Y){P();return}O=Y,!a.isNullable(T)||Y.startTS>T?ce(Y):(B=Y,N())}},T),e.cachedHeader?Oe(e.cachedHeader):f(e.headerUrl,Oe,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=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),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return a.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=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=Ee();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&&Jo(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const p=n.updateChunk(h,f);return p&&u(),p},notifySwitch:h=>{const f=Ee();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=vs(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ns).withRetryCount(os).withRetryInterval(Pp,_p).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;_t(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,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):(i({name:"error",type:"partial_metadata"}),[])};this.manifest=n(e),t(`Valid manifest entries: ${this.manifest.length}/${e.length}`),i({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))},Dp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var z;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(z||(z={}));const xp=[z.PAUSED,z.PLAYING,z.READY],Np=[z.PAUSED,z.PLAYING,z.READY];class Bp{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(z.STOPPED),this.representations$=new a.ValueSubject([]),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,this.maxSeekBackTime$=new a.ValueSubject(1/0),this.zeroTime$=new a.ValueSubject(void 0),this.liveOffset=new Wi,this._dashCb=r=>{var n,o,l,d;switch(r.name){case"buffering":{const u=r.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${r.type}`,category:a.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=r.manifest,c=[];for(const h of u){const f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),p=(o=Ei(h.name))!==null&&o!==void 0?o:a.videoSizeToQuality(h.video),m=h.bitrate/1e3,v={...h.video};if(!p)continue;const S={id:f,quality:p,bitrate:m,size:v};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)===z.MANIFEST_READY&&this.videoState.setState(z.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!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(z.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Np.includes(r)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===H.Requested&&xp.includes(r)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(r){case z.STOPPED:this.videoState.startTransitionTo(z.MANIFEST_READY),this.dash.attachSource($e(this.params.source.url));return;case z.MANIFEST_READY:this.videoState.startTransitionTo(z.READY),this.prepare();break;case z.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(z.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(z.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(z.PAUSED)})}return;case z.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case z.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(z.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(z.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($e(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=lt(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(ke(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 i=dt(this.video);this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.representations$.pipe(a.map(r=>r.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{var r;((r=this.videoState.getTransition())===null||r===void 0?void 0:r.to)===z.READY&&this.videoState.setState(z.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===H.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(z.PLAYING)},t)).add(i.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:i.timeUpdate$}).subscribe(({zeroTime:r,position:n})=>this.params.output.liveTime$.next(r+n*1e3),t)).add(xt(this.video,this.params.desiredState.isLooped,t)).add(ot(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Pt(this.video,this.params.desiredState.playbackRate,i.playbackRateState$,t)).add(i.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(i.playing$.subscribe(this.params.output.firstFrameEvent$)).add(i.canplay$.subscribe(this.params.output.canplay$)).add(i.inPiP$.subscribe(this.params.output.inPiP$)).add(i.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 z.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case z.MANIFEST_READY:case z.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 z.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case z.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),ut(this.video)}createLiveDashPlayer(){const e=new Lp({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,i,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=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&r!==void 0?r:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&a.isNonNullable(d)?d:ti(l.map(({track:v})=>v),{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 v=(o=l.find(({track:S})=>S.id===h))===null||o===void 0?void 0:o.representation;a.assertNonNullable(v,"Representations missing"),this.dash.startPlay(v,u)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:r})=>r.id===e.id))===null||t===void 0?void 0:t.representation;a.assertNonNullable(i,`No such representation ${e.id}`),this.dash.switchByName(i.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(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===z.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit($e(this.params.source.url,o)),r&&this.dash.pause(),this.liveOffset.resetTo(o,r)}}var Pa=s=>{var e,t;const i=s.get("X-Delivery-Type"),r=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==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}},De=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const r=s.start(i)*1e3,n=s.end(i)*1e3;r<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Op=s=>{const e=document.createElement("a");return e.href=s,e.origin},Mp=s=>{const e=document.createElement("a");return e.href=s,e.host};class Xo{constructor(e,t=[],i,r,n,o){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=e,this._failoverHosts=t,this._completeCb=i,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,i,r,n,o,l,d,u;if(this._xhr){if(((t=this._xhr)===null||t===void 0?void 0:t.status)>=400){(i=this._errorCb)===null||i===void 0||i.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=Kt(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 i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.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(Mp(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 $s{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(i){if(i.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",i),i}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(e,t,i,r,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,f=0;const p=v=>{r($s._str2ua(v.substr(d))),d=v.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=Lt(m)),this._lastXhr=new Xo(m,e.failoverHosts,v=>{this._lastXhr=void 0,p(v);const S=Date.now()-u;this._params.onBandwidthChange({size:v.length,duration:S,speed:8*v.length/(S/1e3)}),this._onDashCallback("loading",{size:v.length,done:!0}),n==null||n()},v=>{if(v.length-d>l&&p(v),h===0){h=Date.now();return}f=v.length-c;const S=Date.now()-h;f>=100*1024&&S>=1e3&&(this._params.onBandwidthChange({size:f,duration:S,speed:8*f/(S/1e3)}),f=0,c=v.length,h=Date.now()),this._onDashCallback("loading",{size:v.length,done:!1})},o,(v,S,g)=>this._params.onError(v,S,g))})}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(i){throw this._params.onError("SourceBuffer","Source Buffer update error",i),i}};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=$s._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 i=new Uint8Array(e.byteLength+t.byteLength);return i.set(e,0),i.set(t,e.byteLength),i}static _str2ua(e){const t=new Uint8Array(e.length);for(let i=0;i<e.length;i++)t[i]=e.charCodeAt(i);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 Vp{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)?)?$/,i=(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:i(r==null?void 0:r[2],n),months:i(r==null?void 0:r[3],n),weeks:i(r==null?void 0:r[4],n),days:i(r==null?void 0:r[5],n),hours:i(r==null?void 0:r[6],n),minutes:i(r==null?void 0:r[7],n),seconds:i(r==null?void 0:r[8],n)};return o.hours*3600+o.minutes*60+o.seconds}getRepresentations(){return this._representations}attachSource(e,t){let i=e;this._config.REQUEST_QUIC&&(i=Lt(i)),new Xo(i,t,r=>{this.attachManifest(r,t,Op(i))},void 0,r=>{this._params.onResponseHeaders(r)},(r,n,o)=>this._params.onError(r,n,o))}attachManifest(e,t,i){const n=new DOMParser().parseFromString(e,"text/xml").documentElement,o=(u,c)=>{const h=u.attributes.getNamedItem(c);return h?h.value:null};this._duration=this._parseDurationFromISO8601(String(o(n,"mediaPresentationDuration")));const l=[],d=[];if(Array.prototype.forEach.call(n.getElementsByTagName("Representation"),u=>{var c,h,f,p,m,v,S,g,y,b,T,E,A,x,M,L,B,O,_;const D=u.getElementsByTagName("SegmentBase")[0],V=D&&o(D,"indexRange").split("-"),I=D&&D.getElementsByTagName("Initialization")[0],P=I&&o(I,"range").split("-");if(!P||!V){const we=u.parentElement;if((we==null?void 0:we.getAttribute("contentType"))==="text"){const Oe=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,Y=(i?i+"/":"")+((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),ve=(v=we.getAttribute("lang"))!==null&&v!==void 0?v:void 0;Y&&d.push({id:Oe,url:Y,language:ve})}return}const N=.1,G=Number((S=u.attributes.getNamedItem("bandwidth"))===null||S===void 0?void 0:S.value),X=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let se;const ce=(y=(g=u.attributes.getNamedItem("frameRate"))===null||g===void 0?void 0:g.value)!==null&&y!==void 0?y:void 0;se=ce?js(ce):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:G,baseURL:X,failoverHosts:t,indexFrom:Number(V[0]),indexTo:Number(V[1]),initFrom:Number(P[0]),initTo:Number(P[1]),codecs:(A=(E=u.attributes.getNamedItem("codecs"))===null||E===void 0?void 0:E.value)!==null&&A!==void 0?A:void 0,mimeType:(M=(x=u.attributes.getNamedItem("mimeType"))===null||x===void 0?void 0:x.value)!==null&&M!==void 0?M:void 0,fps:se,bufferSize:N*G/8,bufferLength:N,name:(B=(L=u.attributes.getNamedItem("okQuality"))===null||L===void 0?void 0:L.value)!==null&&B!==void 0?B:void 0,id:(_=(O=u.attributes.getNamedItem("id"))===null||O===void 0?void 0:O.value)!==null&&_!==void 0?_:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");h&&f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady({representations:this._representations,textRepresentations:d})}_loadInitAndSidx(e,t){if(e===this._currentRepresentation){t&&t();return}if(e.refs){this._stream.abort(()=>{this._stream.append(e.initMessage,t)});return}const i=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()-i)},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 i=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=i.addSourceBuffer(`${e.mimeType}; codecs="${e.codecs}"`);this._stream=new $s({mediaSource:i,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),i.duration||(i.duration=this._duration),this._loopTimeout||l(),i.removeEventListener("sourceopen",d),i.removeEventListener("webkitsourceopen",d)};i.addEventListener("sourceopen",d,!1),i.addEventListener("webkitsourceopen",d,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),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,i=!1,r=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(e,()=>{this._currentRepresentation=e;const n=this._findRef(t);if(n){if(i){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 i=this._buffer.getByTime(this._video.currentTime),r=this._findRef(this._video.currentTime);if(!i||!r){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(r.toTime<i.to+n){const o=this._findRef(r.toTime);o&&o.toTime<i.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 i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return;if(Array.isArray(i)&&i.length===0){this._params.onError("emptyrefs","Empty refs");return}let r;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!r||o.fromTime<r.fromTime)&&(r=o)}if(!r){const n=i[i.length-1];if(e>n.toTime)return n}return r}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const r=i[i.length-1];return e.fromTime===r.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),r=this._video.buffered.end(t);if(e>i&&e<r)return Math.round(r*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var W;(function(s){s.STOPPED="stopped",s.MANIFEST_LOADED="manifest-loaded",s.INITIAL_REPRESENTATION_SELECTED="initial-representation-selected",s.METADATA_LOADED="metadata-loaded",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));const Fp=[W.PAUSED,W.PLAYING];class Up{constructor(e){this.videoState=new J(W.STOPPED),this.subscription=new a.Subscription,this.representations$=new a.ValueSubject([]),this.currentRepresentation$=new a.ValueSubject(void 0),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,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:i})=>{var r,n,o;const l=[];for(const d of t){const u=(n=(r=d.name)!==null&&r!==void 0?r:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Ei(d.name))!==null&&o!==void 0?o:a.videoSizeToQuality(d),h=d.bandwidth/1e3,f={width:d.width,height:d.height},p=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:f,fps:p};l.push({track:m,representation:d})}if(this.representations$.next(l),this.params.output.availableVideoTracks$.next(l.map(({track:d})=>d)),(i==null?void 0:i.length)>0){const d=[];for(const u of i){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(W.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const r=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.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(),i=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(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.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(W.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===H.Requested&&Fp.includes(t)&&this.seek(o.position,o.forcePrecise),t){case W.STOPPED:this.videoState.startTransitionTo(W.MANIFEST_LOADED),this.prepare();return;case W.MANIFEST_LOADED:this.videoState.startTransitionTo(W.INITIAL_REPRESENTATION_SELECTED);return;case W.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(W.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case W.METADATA_LOADED:this.videoState.startTransitionTo(W.READY),this.dash.updateRefsForCurrentTime();return;case W.READY:r===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&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:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=lt(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ip(this.video),this.dash=new Vp({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:i})=>this.dashLiteEvents.manifestReady$.next({representations:t,textRepresentations:i}),onRepresentationPlay:t=>this.dashLiteEvents.representationPlay$.next(t),onBandwidthChange:t=>this.params.dependencies.throughputEstimator.addRawSpeed(t.size,t.duration),onError:(t,i,r)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,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,i=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=dt(this.video),o=(l,d)=>this.subscription.add(l.subscribe(d,i));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!==H.Applying)&&(this.videoState.getState()===W.PLAYING||this.videoState.getState()===W.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(xt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pt(this.video,t.playbackRate,n.playbackRateState$,i)),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(Hi(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING),w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(W.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).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,v=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),g=r();p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to);let y;if(!g&&a.isNonNullable(m))y=m;else{const b=De(this.video.buffered,this.video.currentTime*1e3),T=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(b/T,1);y=(u=ti(f.map(({track:x})=>x),{container:S,throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(d=f.find(({representation:x})=>x===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 A=t.autoVideoTrackLimits.getTransition();A&&e.autoVideoTrackLimits$.next(A.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$,i)).add(a.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(a.filter(l=>l.to===W.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(a.filter(a.isNonNullable))}).pipe(a.once()).subscribe(()=>this.videoState.setState(W.INITIAL_REPRESENTATION_SELECTED),i)).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=De(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(ke(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Pa(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,i)).add(this.dashLiteEvents.representationPlay$.pipe(a.filter(a.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy(),this.buffer.destroy(),this.dash.destroy(),this.params.output.element$.next(void 0),ut(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(){_t(this.video).then(e=>{e||(this.videoState.setState(W.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 be;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(be||(be={}));var ks;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(ks||(ks={}));var Fe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Fe||(Fe={}));var Q;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(Q||(Q={}));var mi;(function(s){s.MP4="mp4",s.WEBM="webm"})(mi||(mi={}));var ws;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(ws||(ws={}));var ae;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ae||(ae={}));class Rn{constructor(){Object.defineProperty(this,"listeners",{value:{},writable:!0,configurable:!0})}addEventListener(e,t,i){e in this.listeners||(this.listeners[e]=[]),this.listeners[e].push({callback:t,options:i})}removeEventListener(e,t){if(!(e in this.listeners))return;const i=this.listeners[e];for(let r=0,n=i.length;r<n;r++)if(i[r].callback===t){i.splice(r,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let r=0,n=i.length;r<n;r++){const o=i[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 Zo extends Rn{constructor(){super(),this.listeners||Rn.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 el=class{constructor(){Object.defineProperty(this,"signal",{value:new Zo,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 i=e;if(i===void 0)if(typeof document=="undefined")i=new Error("This operation was aborted"),i.name="AbortError";else try{i=new DOMException("signal is aborted without reason")}catch(r){i=new Error("This operation was aborted"),i.name="AbortError"}this.signal.reason=i,this.signal.dispatchEvent(t)}toString(){return"[object AbortController]"}};typeof Symbol!="undefined"&&Symbol.toStringTag&&(el.prototype[Symbol.toStringTag]="AbortController",Zo.prototype[Symbol.toStringTag]="AbortSignal");function tl(s){return s.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log("__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill"),!0):typeof s.Request=="function"&&!s.Request.prototype.hasOwnProperty("signal")||!s.AbortController}function jp(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=s;if(!tl({fetch:e,Request:t,AbortController:i,__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 Hs=tl({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),il=Hs?jp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Jt=Hs?il.fetch:window.fetch;Hs?il.Request:window.Request;const je=Hs?el:window.AbortController;var bi=(s,e)=>{for(let t=0;t<s.length;t++)if(s.start(t)*1e3<=e&&s.end(t)*1e3>e)return!0;return!1};const Hp=(s,e={})=>{const i=e.timeout||1,r=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-r-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-r))}})},1)},Gp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",As=Gp?Hp:window.requestIdleCallback;var Pr,_r;const Yp=16;let sl=!1;try{sl=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((_r=(Pr=navigator.userAgent.match(/Version\/(\d+)/))===null||Pr===void 0?void 0:Pr[1])!==null&&_r!==void 0?_r:"",10)<=Yp}catch(s){console.error(s)}let zp=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 i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;sl&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}};var Ps=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};let ct=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}},rl=class extends ct{},qp=class extends ct{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}},Wp=class extends ct{parseChildrenBoxes(){return $i(this.content)}},Qp=class extends ct{constructor(e){super(e),this.data=this.content}},Ki=class extends ct{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}},Kp=class extends Ki{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}},Jp=class extends ct{parseChildrenBoxes(){return $i(this.content)}},Xp=class extends ct{parseChildrenBoxes(){return $i(this.content)}};var Wt;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Wt||(Wt={}));let Zp=class extends Ki{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Wt.MONOSCOPIC;break;case 1:this.stereoMode=Wt.TOP_BOTTOM;break;case 2:this.stereoMode=Wt.LEFT_RIGHT;break;case 3:this.stereoMode=Wt.STEREO_CUSTOM;break;case 4:this.stereoMode=Wt.RIGHT_LEFT;break}this.cursor+=1}},em=class extends Ki{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}},tm=class extends Ki{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}},im=class extends ct{parseChildrenBoxes(){return $i(this.content)}},sm=class extends Ki{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()}},rm=class extends ct{parseChildrenBoxes(){return $i(this.content)}},am=class extends ct{parseChildrenBoxes(){return $i(this.content)}};const nm={ftyp:qp,moov:Wp,mdat:Qp,sidx:Kp,trak:Jp,mdia:im,tkhd:sm,minf:rm,sv3d:Xp,st3d:Zp,prhd:em,proj:am,equi:tm,unknown:rl};let om=class{createBox(e,t){const i=nm[e];return i?new i(t):new rl(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Gs.createBox(i,new DataView(e.buffer,e.byteOffset))}};const Gs=new om;function Vi(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,r=[];for(;i<s.byteLength;){const n=t.decode(new DataView(s.buffer,i,1));if(n===e[r.length]?r.push(n):r=[],r.length===4&&r.join("")===e){const l=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+l>s.byteLength?null:Gs.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function lm(s,e){const t=[];let i=0;for(;i<s.byteLength;){const r=Vi(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(r)t.push(r),i+=r.size+r.source.byteOffset;else break}return t}function $i(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Gs.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const um=new TextDecoder("ascii"),dm=s=>um.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",cm=s=>{const e=Gs.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:Q.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},hm=s=>{const e=lm(s,"mdat");if(e.length){const t=e.reduce((i,r)=>i+r.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},fm=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:ws.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Vi(s,"sv3d")){e.is3dVideo=!0;const i=Vi(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Vi(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=Vi(s,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},pm={validateData:dm,parseInit:fm,getIndexRange:()=>{},parseSegments:cm,parseFeedableSegmentChunk:hm};var $;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})($||($={}));var R;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(R||(R={}));const Cn={[$.EBML]:{type:R.Master},[$.EBMLVersion]:{type:R.UnsignedInteger},[$.EBMLReadVersion]:{type:R.UnsignedInteger},[$.EBMLMaxIDLength]:{type:R.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:R.UnsignedInteger},[$.DocType]:{type:R.String},[$.DocTypeVersion]:{type:R.UnsignedInteger},[$.DocTypeReadVersion]:{type:R.UnsignedInteger},[$.Void]:{type:R.Binary},[$.Segment]:{type:R.Master},[$.SeekHead]:{type:R.Master},[$.Seek]:{type:R.Master},[$.SeekID]:{type:R.Binary},[$.SeekPosition]:{type:R.UnsignedInteger},[$.Info]:{type:R.Master},[$.TimestampScale]:{type:R.UnsignedInteger},[$.Duration]:{type:R.Float},[$.Tracks]:{type:R.Master},[$.TrackEntry]:{type:R.Master},[$.Video]:{type:R.Master},[$.Projection]:{type:R.Master},[$.ProjectionType]:{type:R.UnsignedInteger},[$.ProjectionPrivate]:{type:R.Master},[$.Chapters]:{type:R.Master},[$.Cluster]:{type:R.Master},[$.Timestamp]:{type:R.UnsignedInteger},[$.SilentTracks]:{type:R.Master},[$.SilentTrackNumber]:{type:R.UnsignedInteger},[$.Position]:{type:R.UnsignedInteger},[$.PrevSize]:{type:R.UnsignedInteger},[$.SimpleBlock]:{type:R.Binary},[$.BlockGroup]:{type:R.Master},[$.EncryptedBlock]:{type:R.Binary},[$.Attachments]:{type:R.Master},[$.Tags]:{type:R.Master},[$.Cues]:{type:R.Master},[$.CuePoint]:{type:R.Master},[$.CueTime]:{type:R.UnsignedInteger},[$.CueTrackPositions]:{type:R.Master},[$.CueTrack]:{type:R.UnsignedInteger},[$.CueClusterPosition]:{type:R.UnsignedInteger},[$.CueRelativePosition]:{type:R.UnsignedInteger},[$.CueDuration]:{type:R.UnsignedInteger},[$.CueBlockNumber]:{type:R.UnsignedInteger},[$.CueCodecState]:{type:R.UnsignedInteger},[$.CueReference]:{type:R.Master},[$.CueRefTime]:{type:R.UnsignedInteger}},al=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=_s(s,t),r=i in Cn,n=r?Cn[i].type:R.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=_s(d),h=u*2**((l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},_s=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},rt=(s,e)=>{switch(e){case R.SignedInteger:return s.getInt8(0);case R.UnsignedInteger:return _s(s);case R.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case R.String:return new TextDecoder("ascii").decode(s);case R.UTF8:return new TextDecoder("utf-8").decode(s);case R.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case R.Master:return s;case R.Binary:return s;default:a.assertNever(e)}},gi=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=al(i);if(!e(r))return;r.type===R.Master&&gi(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},mm=s=>{if(s.getUint32(0)!==$.EBML)return!1;let e,t,i;const r=al(s);return gi(r.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=rt(l,o):n===$.DocType?t=rt(l,o):n===$.DocTypeReadVersion&&(i=rt(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},nl=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],bm=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],gm=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return gi(s,({tag:f,type:p,value:m,valueSize:v})=>{if(f===$.SeekID){const S=rt(m,p);u=_s(S)}else f!==$.SeekPosition&&(u=void 0);return f===$.Segment?(e=m.byteOffset,t=m.byteOffset+v):f===$.Info?n=!0:f===$.SeekHead?o=!0:f===$.TimestampScale?i=rt(m,p):f===$.Duration?r=rt(m,p):f===$.SeekPosition&&u===$.Cues?d=rt(m,p):f===$.Tracks?gi(m,({tag:S,type:g,value:y})=>S===$.ProjectionType?(c=rt(y,g)===1,!1):!0):n&&o&&nl.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:ws.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},vm=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Sm=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return gi(s,({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=rt(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=rt(u,d));break;default:t&&nl.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:Q.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}}})},ym=s=>{let e=0,t=!1;try{gi(s,i=>i.tag===$.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):bm.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[$.SimpleBlock,$.BlockGroup,$.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},Tm={validateData:mm,parseInit:gm,getIndexRange:vm,parseSegments:Sm,parseFeedableSegmentChunk:ym},ol=1e4,Em=3e4,$m=5e3,km=ol,wm=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Ei(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},Am=({id:s,bitrate:e})=>({id:s,bitrate:e}),Pm=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=pe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:pe(s,-1)},_m=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),ls=s=>{const e=[];let t=0,i=s.length-1;for(;t<ol&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};let Ln=class{constructor(e,t,i,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 je,this.destroyAbortController=new je,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=a.abortable(this.destroyAbortController.signal,async function*(c){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 zp(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},v=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:v}))),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(v=>{if(!this.sourceBuffer)return;const S=Math.min(this.bufferLimit,Ps(this.sourceBuffer.buffered)*.8);this.bufferLimit=S,this.pruneBuffer(this.getCurrentPosition(),v)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(v=>this.error$.next(v))),yield this.loadInit(h,"high",!0);const f=this.initData.get(h.id),p=this.segments.get(h.id),m=this.parsedInitData.get(h.id);a.assertNonNullable(f,"No init buffer for starting representation"),a.assertNonNullable(p,"No segments for starting representation"),f instanceof ArrayBuffer&&(this.searchGaps(p,h),yield 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,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;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 this.loadInit(h,"high",!1):p instanceof Promise&&(yield 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;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield 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,async function*(c){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const S of this.representations.keys()){const g=c.find(T=>T.id===S);g&&this.representations.set(S,g);const y=this.representations.get(S);if(!y)return;const b=ls(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=ls(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;const v=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),v&&(yield this.sourceBufferTaskQueue.remove(v.from*1e3,v.to*1e3,this.destroyAbortController.signal)),this.searchGaps(p,f),yield 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=i,i){case mi.MP4:this.containerParser=pm;break;case mi.WEBM:this.containerParser=Tm;break;default:a.assertNever(i)}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 je,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=De(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)&&Ps(this.sourceBuffer.buffered)>=this.bufferLimit){const u=De(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=pe(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===Q.FED&&!l.length&&De(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=pe(i,-1);d&&d.status===Q.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const r of e)r.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:r.time.from}),i=r.time.to;a.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,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 i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o)return;const l=o.segmentReference.segments.map(h=>({...h,status:Q.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(r=pe(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=ls(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,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const v=f<=i&&p>=i,S=f>i||v||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=i+g||p<=i+g;return(h===Q.NONE||h===Q.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!bi(this.sourceBuffer.buffered,i))&&S&&y});if(r===-1)return[];if(t!==Fe.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===Q.NONE||f.status===Q.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let r,n,o=e;const{type:l}=t.segmentReference;switch(l){case Fe.BYTE_RANGE:{r=t.segmentReference.url,n={from:pe(e,0).byte.from,to:pe(e,-1).byte.to};break}case Fe.TEMPLATE:{const u=pe(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=Q.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await a.abortable(d,async function*(){const u=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield 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:i}).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 i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=De((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,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=Q.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===Q.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=Q.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===Fe.BYTE_RANGE,m=p?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!p||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const S=p?f.byte.from-i:0,g=p?f.byte.to-i:e.byteLength,y=S<r,b=g<=r;if(f.status===Q.DOWNLOADING&&y&&b){f.status=Q.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=Q.PARTIALLY_FED,h.feedingBytes+=E.byteLength,this.sourceBufferTaskQueue.append(E,n).then(A=>{if(n.aborted)o();else if(A)h.fedBytes+=E.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===Q.PARTIALLY_FED||e.status===Q.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=Q.NONE),e.status=Q.PARTIALLY_EJECTED):e.status=Q.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=As(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,async function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async l=>{if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h),this.segments.set(e.id,this.isLive?ls(c):c),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){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===Q.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===Q.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===Q.NONE&&Math.round(p.time.from)<=Math.round(c)&&Math.round(p.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===Q.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=As(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==Q.FED&&n!==Q.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=Q.PARTIALLY_EJECTED:r.status=Q.NONE)}}};var fi;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(fi||(fi={}));let Dm=class{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new je,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,async function*(r){let n=r;this.requestQuic&&(n=Lt(n));const o=yield Jt(n,{signal:this.abortAllController.signal}).catch(Ni);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,async function*(r,{rangeMethod:n=this.compatibilityMode?fi.HEADER:fi.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,p,m;let v=r;const S=new Headers;if(o)switch(n){case fi.HEADER:{S.append("Range",`bytes=${o.from}-${o.to}`);break}case fi.PARAM:{const N=new URL(v,location.href);N.searchParams.append("bytes",`${o.from}-${o.to}`),v=N.toString();break}default:a.assertNever(n)}this.requestQuic&&(v=Lt(v));let g=this.abortAllController.signal,y;if(u){const N=new je;if(y=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{N.abort()}catch(G){Ni(G)}}),this.abortAllController.signal.aborted||u.aborted)try{N.abort()}catch(G){Ni(G)}g=N.signal}const b=a.now(),T=yield Jt(v,{priority:d,headers:S,signal:g}).catch(Ni),E=a.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-b),!T)return y==null||y.unsubscribe(),null;if(!T.ok||!T.body)return y==null||y.unsubscribe(),Promise.reject(new Error(`Fetch error ${T.status}: ${T.statusText}`));this.onHeadersReceived(T.headers);const A=parseInt((f=T.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!A){const N=yield T.arrayBuffer();return(p=this.throughputEstimator)===null||p===void 0||p.addRawSpeed(N.byteLength,a.now()-E),l==null||l(new DataView(N),N.byteLength),y==null||y.unsubscribe(),N}if(!l&&!c)return y==null||y.unsubscribe(),T.arrayBuffer();const[x,M]=T.body.tee(),L=x.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(M));let B=0;const O=new ArrayBuffer(A),_=new Uint8Array(O),D=new DataView(O);let V=!1;const I=N=>{y==null||y.unsubscribe(),V=!0,Ni(N)},P=a.abortable(g,async function*({done:N,value:G}){if(B===0&&this.lastRequestFirstBytes$.next(a.now()-b),g.aborted){y==null||y.unsubscribe();return}!N&&G&&(_.set(G,B),B+=G.byteLength,l==null||l(D,B),yield L==null?void 0:L.read().then(P,I))}.bind(this));return yield L==null?void 0:L.read().then(P,I),y==null||y.unsubscribe(),V?null:O}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n,o){var l;if(r.type!==Fe.BYTE_RANGE)return 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 v=yield this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!v)return null;const S=new DataView(v,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const g=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let b;if(f)b=new DataView(v,y.from-c,y.to-y.from+1);else{const E=yield this.fetch(r.url,{range:y,priority:o,measureThroughput:!1});if(!E)return null;b=new DataView(E)}const T=n.parseSegments(b,g,y);return{init:g,dataView:new DataView(v),segments:T}}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n){if(r.type!==Fe.TEMPLATE)return null;const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:r.segments.map(u=>({...u,status:Q.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Pa(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,n;const{type:o}=e;switch(o){case Fe.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Fe.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}};const Ni=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Im=Xt,Rm=Ns,Cm=Je,Lm=Cm("match"),xm=function(s){var e;return Im(s)&&((e=s[Lm])!==void 0?!!e:Rm(s)=="RegExp")},Nm=Us,Bm=String,Om=function(s){if(Nm(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Bm(s)},Mm=ei,Vm=function(){var s=Mm(this),e="";return s.hasIndices&&(e+="d"),s.global&&(e+="g"),s.ignoreCase&&(e+="i"),s.multiline&&(e+="m"),s.dotAll&&(e+="s"),s.unicode&&(e+="u"),s.unicodeSets&&(e+="v"),s.sticky&&(e+="y"),e},Fm=wt,Um=At,jm=ma,Hm=Vm,xn=RegExp.prototype,Gm=function(s){var e=s.flags;return e===void 0&&!("flags"in xn)&&!Um(s,"flags")&&jm(xn,s)?Fm(Hm,s):e},_a=kt,Ym=Ms,zm=Math.floor,Dr=_a("".charAt),qm=_a("".replace),Ir=_a("".slice),Wm=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Qm=/\$([$&'`]|\d{1,2})/g,Km=function(s,e,t,i,r,n){var o=t+s.length,l=i.length,d=Qm;return r!==void 0&&(r=Ym(r),d=Wm),qm(n,d,function(u,c){var h;switch(Dr(c,0)){case"$":return"$";case"&":return s;case"`":return Ir(e,0,t);case"'":return Ir(e,o);case"<":h=r[Ir(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var p=zm(f/10);return p===0?u:p<=l?i[p-1]===void 0?Dr(c,1):i[p-1]+Dr(c,1):u}h=i[f-1]}return h===void 0?"":h})},Jm=Fs,Xm=wt,Da=kt,Nn=ha,Zm=He,eb=Bs,tb=xm,li=Om,ib=Os,sb=Gm,rb=Km,ab=Je,nb=ab("replace"),ob=TypeError,ll=Da("".indexOf),lb=Da("".replace),Bn=Da("".slice),ub=Math.max,On=function(s,e,t){return t>s.length?-1:e===""?t:ll(s,e,t)};Jm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Nn(this),r,n,o,l,d,u,c,h,f,p=0,m=0,v="";if(!eb(e)){if(r=tb(e),r&&(n=li(Nn(sb(e))),!~ll(n,"g")))throw ob("`.replaceAll` does not allow non-global regexes");if(o=ib(e,nb),o)return Xm(o,e,i,t);if(r)return lb(li(i),e,t)}for(l=li(i),d=li(e),u=Zm(t),u||(t=li(t)),c=d.length,h=ub(1,c),p=On(l,d,0);p!==-1;)f=u?li(t(d,p,l)):rb(d,l,p,[],void 0,t),v+=Bn(l,m,p)+f,m=p+c,p=On(l,d,p+h);return m<l.length&&(v+=Bn(l,m)),v}});var db=Qo,cb=db("String","replaceAll"),hb=cb,fb=hb,pb=fb,mb=pb,Ds=ca(mb);const Mn=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},Rr=(s,e)=>{let t=s;t=Ds(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Ds(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},bb=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,m,v,S,g,y,b,T,E,A,x,M,L,B,O,_,D,V,I,P,N,G,X,se,ce,we,Oe,Y;const Ae=new DOMParser().parseFromString(s,"application/xml"),he={video:[],audio:[],text:[]},le=Ae.children[0],ht=le.getElementsByTagName("Period")[0],ft=ht.children,It=le.getAttribute("type")==="dynamic",pt=le.getAttribute("availabilityStartTime"),ii=pt?new Date(pt).getTime():void 0;let Se;const ki=le.getAttribute("mediaPresentationDuration"),wi=ht.getAttribute("duration"),Bt=le.getElementsByTagName("vk:Attrs")[0],Ai=Bt==null?void 0:Bt.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ki)Se=Mn(ki);else if(wi){const re=Mn(wi);a.isNonNullable(re)&&(Se=re)}else Ai&&(Se=parseInt(Ai,10));let zs=0;const Ot=(i=(t=le.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],qs=Ot.includes(ks.WEBM_AS_IN_FFMPEG)||Ot.includes(ks.WEBM_AS_IN_SPEC)?mi.WEBM:mi.MP4;for(const re of ft){const mt=re.getAttribute("mimeType"),Ws=re.getAttribute("codecs"),Pi=(r=re.getAttribute("contentType"))!==null&&r!==void 0?r:mt==null?void 0:mt.split("/")[0],Qs=(o=(n=re.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],_i=re.querySelectorAll("Representation"),Ks=re.querySelector("SegmentTemplate");if(Pi===be.TEXT){for(const F of _i){const fe=F.getAttribute("id")||"",bt=re.getAttribute("lang"),Ie=(u=(d=(l=F.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Mt=new URL(Ie,e).toString(),Vt=fe.includes("_auto");he[be.TEXT].push({id:fe,lang:bt,isAuto:Vt,kind:be.TEXT,url:Mt})}continue}for(const F of _i){const fe=(c=F.getAttribute("mimeType"))!==null&&c!==void 0?c:mt,bt=(f=(h=F.getAttribute("codecs"))!==null&&h!==void 0?h:Ws)!==null&&f!==void 0?f:"",Ie=(m=(p=F.getAttribute("contentType"))!==null&&p!==void 0?p:fe==null?void 0:fe.split("/")[0])!==null&&m!==void 0?m:Pi,Mt=(S=(v=re.getAttribute("profiles"))===null||v===void 0?void 0:v.split(","))!==null&&S!==void 0?S:[],Vt=parseInt((g=F.getAttribute("width"))!==null&&g!==void 0?g:"",10),Di=parseInt((y=F.getAttribute("height"))!==null&&y!==void 0?y:"",10),Ii=parseInt((b=F.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Ri=(T=F.getAttribute("frameRate"))!==null&&T!==void 0?T:"",Js=(E=F.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Xs=Ri?js(Ri):void 0,Zs=(A=F.getAttribute("id"))!==null&&A!==void 0?A:(zs++).toString(10),er=Ie==="video"?`${Di}p`:Ie==="audio"?`${Ii}Kbps`:bt,tr=`${Zs}@${er}`,ir=(L=(M=(x=F.querySelector("BaseURL"))===null||x===void 0?void 0:x.textContent)===null||M===void 0?void 0:M.trim())!==null&&L!==void 0?L:"",Ci=new URL(ir,e).toString(),sr=[...Ot,...Qs,...Mt];let Ft;const rr=F.querySelector("SegmentBase"),ye=(B=F.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Ks;if(rr){const Re=(_=(O=F.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&_!==void 0?_:"",[Ce,jt]=Re.split("-").map(Le=>parseInt(Le,10)),Pe={from:Ce,to:jt},Ye=(D=F.querySelector("SegmentBase"))===null||D===void 0?void 0:D.getAttribute("indexRange"),[Ht,gt]=Ye?Ye.split("-").map(Le=>parseInt(Le,10)):[],ze=Ye?{from:Ht,to:gt}:void 0;Ft={type:Fe.BYTE_RANGE,url:Ci,initRange:Pe,indexRange:ze}}else if(ye){const Re={representationId:(V=F.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(I=F.getAttribute("bandwidth"))!==null&&I!==void 0?I:void 0},Ce=parseInt((P=ye.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),jt=(N=ye.getAttribute("initialization"))!==null&&N!==void 0?N:"",Pe=ye.getAttribute("media"),Ye=(X=parseInt((G=ye.getAttribute("startNumber"))!==null&&G!==void 0?G:"",10))!==null&&X!==void 0?X:1,Ht=Rr(jt,Re);if(!Pe)throw new ReferenceError("No media attribute in SegmentTemplate");const gt=(se=ye.querySelectorAll("SegmentTimeline S"))!==null&&se!==void 0?se:[],ze=[];let Le=0;if(gt.length){let Gt=Ye,xe=0;for(const Yt of gt){const Ne=parseInt((ce=Yt.getAttribute("d"))!==null&&ce!==void 0?ce:"",10),ue=parseInt((we=Yt.getAttribute("r"))!==null&&we!==void 0?we:"",10)||0,qe=parseInt((Oe=Yt.getAttribute("t"))!==null&&Oe!==void 0?Oe:"",10);xe=Number.isFinite(qe)?qe:xe;const _e=Ne/Ce*1e3,Ze=xe/Ce*1e3;for(let vt=0;vt<ue+1;vt++){const Li=Rr(Pe,{...Re,segmentNumber:Gt.toString(10),segmentTime:(xe+vt*Ne).toString(10)}),si=(Ze||0)+vt*_e,ri=si+_e;Gt++,ze.push({time:{from:si,to:ri},url:Li})}xe+=(ue+1)*Ne,Le+=(ue+1)*_e}}else if(a.isNonNullable(Se)){const xe=parseInt((Y=ye.getAttribute("duration"))!==null&&Y!==void 0?Y:"",10)/Ce*1e3,Yt=Math.ceil(Se/xe);let Ne=0;for(let ue=1;ue<Yt;ue++){const qe=Rr(Pe,{...Re,segmentNumber:ue.toString(10),segmentTime:Ne.toString(10)});ze.push({time:{from:Ne,to:Ne+xe},url:qe}),Ne+=xe}}Ft={type:Fe.TEMPLATE,baseUrl:Ci,initUrl:Ht,totalSegmentsDurationMs:Le,segments:ze}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ie||!fe)continue;const Ut={video:be.VIDEO,audio:be.AUDIO,text:be.TEXT}[Ie];Ut&&he[Ut].push({id:tr,kind:Ut,segmentReference:Ft,profiles:sr,duration:Se,bitrate:Ii,mime:fe,codecs:bt,width:Vt,height:Di,fps:Xs,quality:Js})}}return{dynamic:It,liveAvailabilityStartTime:ii,duration:Se,container:qs,representations:he}},na=1e3,Vn=["timeupdate","progress","play","seeked","stalled","waiting"];var Me;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Me||(Me={}));let gb=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new J(Me.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 je,this.initManifest=a.abortable(this.destroyController.signal,async function*(t,i,r){var n;this.element=t,this.manifestUrlString=$e(i,r,ie.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Me.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Me.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,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!i)return this.manifest;let r;try{r=bb(i!=null?i:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return 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===be.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)),{...r,representations:Kt(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,async function*(t,i){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Me.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 Ln(be.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new Ln(be.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(na).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=Es(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P);this.manifestUrlString=$e(this.manifestUrlString,u+1e3,ie.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Vn.map(l=>a.fromEvent(this.element,l))).pipe(a.throttle(na),a.map(l=>this.element?De(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 v,S;return(S=(v=m.getLiveSegmentsToLoadState(this.manifest))===null||v===void 0?void 0:v.to)!==null&&S!==void 0?S:0}))-f}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async d=>{a.assertNonNullable(this.element);const u=this.element.playbackRate,c=Es(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P),h=Em*u,f=km*u,p=$m*u;l=d>l?d:l;const m=c===0&&d<p,v=c!==0&&d<h+p&&d>=h,S=c!==0&&d<h;if(S||v){const g=l-(h+f),y=Math.trunc(c+g/u);let b;d?y>0?b=y:b=0:b=c,this.manifestUrlString=$e(this.manifestUrlString,b,ie.DASH_CMAF_OFFSET_P)}(m||S||v)&&(await 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 new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Me.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Dm({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async seekLive(e){var t,i,r,n;a.assertNonNullable(this.element),this.manifestUrlString=$e(this.manifestUrlString,e,ie.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((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(Me.RUNNING),this.subscription.add(a.merge(...Vn.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&&bi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[be.VIDEO]:this.videoBufferManager,[be.AUDIO]:this.audioBufferManager,[be.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),bi(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(Me.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}async updateLive(){var e;this.manifest=await 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,i=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=r/1e3}}};class vb{constructor(e,t){this.fov=e,this.orientation=t}}class Sb{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/(this.options.speedFadeTime/1e3)**2}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.orientation.x+e,this.camera.orientation.y+t,this.camera.orientation.z+i)}pointCameraTo(e=0,t=0,i=0){t=this.limitCameraRotationY(t);const r=e-this.camera.orientation.x,n=t-this.camera.orientation.y,o=i-this.camera.orientation.z;this.camera.orientation.x=e,this.camera.orientation.y=t,this.camera.orientation.z=i,this.lastCameraTurn={x:r,y:n,z:o},this.lastCameraTurnTS=Date.now()}setRotationSpeed(e,t,i){this.rotationSpeed.x=e!=null?e:this.rotationSpeed.x,this.rotationSpeed.y=t!=null?t:this.rotationSpeed.y,this.rotationSpeed.z=i!=null?i: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,i){this.setRotationSpeed(e,t,i),this.fadeStartSpeed={...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,i=t/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*this.options.rotationSpeedCorrection*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i);else if(this.fading&&this.fadeStartSpeed){const r=-this.fadeCorrection*(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*i,this.rotationSpeed.y*this.options.rotationSpeedCorrection*i,this.rotationSpeed.z*this.options.rotationSpeedCorrection*i):(this.stopRotation(!0),this.stopFading()),this.fadeTime=Math.min(this.fadeTime+t,this.options.speedFadeTime)}this.lastTickTS=e}}var yb=`#define GLSLIFY 1
|
|
38
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;}`,Tb=`#ifdef GL_ES
|
|
39
39
|
precision highp float;precision highp int;
|
|
40
40
|
#else
|
|
@@ -42,5 +42,5 @@ precision highp float;
|
|
|
42
42
|
#define GLSLIFY 1
|
|
43
43
|
#endif
|
|
44
44
|
#define PI 3.14159265358979323846264
|
|
45
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class ol{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new vb(this.params.fov,this.params.orientation),this.cameraRotationManager=new Sb(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(yb,this.gl.VERTEX_SHADER),i=this.createShader(Tb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,n=e-i,o=t-r,l=e+i,d=t-r,u=e+i,c=t+r,h=e-i,f=t+r;return[n,o,l,d,u,c,h,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let ll=class{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(ae.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Wo,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===H.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ae.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();return;case ae.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(ae.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ae.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ae.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ae.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var i,r,n;if(this.scene3D)return;this.scene3D=new ol(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=lt(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 gb({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=dt(this.video),r=this.constructor.name,n=l=>{e.error$.next({id:r,category:a.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(xt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),n(Hi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Oe.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((b,y)=>y.bitrate-b.bitrate),m=Array.from(f.video).sort((b,y)=>y.bitrate-b.bitrate),v=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const b of p){const y=wm(b);y&&this.audioTracks.push({track:y,representation:b})}for(const b of m){const y=Am(b);if(y){h.push({track:y,representation:b});const g=!this.params.tuning.isAudioDisabled&&Pm(p,m,b);g&&this.audioRepresentations.set(b.id,g)}}this.videoTracks$.next(h);for(const b of v){const y=_m(b);y&&this.textTracks.push({track:y,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));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===Oe.REPRESENTATIOS_READY&&(this.videoState.setState(ae.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!==Oe.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(me.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(me.AUDIO,p.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=_e(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),v=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=ti(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:v,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),b=d?S!=null?S:c:c!=null?c:S;return b&&((l=this.videoTracks$.getValue().find(({track:y})=>y===b))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_t(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ae.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ut(this.video)}},Eb=class extends ll{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var be;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(be||(be={}));var it;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(it||(it={}));var Rs;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Rs||(Rs={}));var Fe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Fe||(Fe={}));var j;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(j||(j={}));var vi;(function(s){s.MP4="mp4",s.WEBM="webm"})(vi||(vi={}));var Is;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Is||(Is={}));var ne;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ne||(ne={}));var Cr,Lr;let ul=!1;try{ul=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Lr=(Cr=navigator.userAgent.match(/Version\/(\d+)/))===null||Cr===void 0?void 0:Cr[1])!==null&&Lr!==void 0?Lr:"",10)<16}catch(s){console.error(s)}class $b{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;ul&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}class He{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 dl extends He{}class kb extends He{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class Ab extends He{parseChildrenBoxes(){return Nt(this.content)}}class wb extends He{parseChildrenBoxes(){return Nt(this.content)}}class Pb extends He{constructor(e){super(e),this.data=this.content}}class Dt extends He{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _b extends Dt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class Db extends He{parseChildrenBoxes(){return Nt(this.content)}}class Rb extends He{parseChildrenBoxes(){return Nt(this.content)}}var Qt;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Qt||(Qt={}));class Ib extends Dt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Qt.MONOSCOPIC;break;case 1:this.stereoMode=Qt.TOP_BOTTOM;break;case 2:this.stereoMode=Qt.LEFT_RIGHT;break;case 3:this.stereoMode=Qt.STEREO_CUSTOM;break;case 4:this.stereoMode=Qt.RIGHT_LEFT;break}this.cursor+=1}}class Cb extends Dt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Lb extends Dt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class xb extends He{parseChildrenBoxes(){return Nt(this.content)}}class Nb extends Dt{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 Bb extends He{parseChildrenBoxes(){return Nt(this.content)}}class Ob extends He{parseChildrenBoxes(){return Nt(this.content)}}class Mb extends Dt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Vb extends He{parseChildrenBoxes(){return Nt(this.content)}}class Fb extends Dt{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 Ub extends Dt{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 jb extends Dt{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 Hb={ftyp:kb,moov:Ab,moof:wb,mdat:Pb,sidx:_b,trak:Db,mdia:xb,mfhd:Mb,tkhd:Nb,traf:Vb,tfhd:Fb,tfdt:Ub,trun:jb,minf:Bb,sv3d:Rb,st3d:Ib,prhd:Cb,proj:Ob,equi:Lb,unknown:dl};class Gb{createBox(e,t){const i=Hb[e];return i?new i(t):new dl(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ys.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Ys=new Gb;function Fi(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(o=>o.charCodeAt(0));let r=s.byteOffset,n=[];for(;r<t.byteLength;){if(t[r]===i[n.length]?n.push(t[r]):n=[],n.length===4){const l=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+l>s.buffer.byteLength?null:Ys.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function aa(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=Fi(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function Nt(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Ys.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Yb=new TextDecoder("ascii"),zb=s=>Yb.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",qb=s=>{const e=Ys.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:j.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},Wb=s=>{const e=aa(s,"mdat"),t=aa(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],n=i.source.byteOffset,l=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,n,l)},Qb=(s,e)=>{const t=aa(s,"traf"),i=t[t.length-1].children.find(d=>d.type==="tfhd"),r=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,u)=>d+u,0):o=i.defaultSampleDuration*n.sampleCount,(Number(r.baseMediaDecodeTime)+o)/e*1e3},Kb=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Is.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Fi(s,"sv3d")){e.is3dVideo=!0;const i=Fi(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Fi(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=Fi(s,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},Jb={validateData:zb,parseInit:Kb,getIndexRange:()=>{},parseSegments:qb,parseFeedableSegmentChunk:Wb,getSegmentEndTime:Qb};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var C;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(C||(C={}));const Mn={[k.EBML]:{type:C.Master},[k.EBMLVersion]:{type:C.UnsignedInteger},[k.EBMLReadVersion]:{type:C.UnsignedInteger},[k.EBMLMaxIDLength]:{type:C.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[k.DocType]:{type:C.String},[k.DocTypeVersion]:{type:C.UnsignedInteger},[k.DocTypeReadVersion]:{type:C.UnsignedInteger},[k.Void]:{type:C.Binary},[k.Segment]:{type:C.Master},[k.SeekHead]:{type:C.Master},[k.Seek]:{type:C.Master},[k.SeekID]:{type:C.Binary},[k.SeekPosition]:{type:C.UnsignedInteger},[k.Info]:{type:C.Master},[k.TimestampScale]:{type:C.UnsignedInteger},[k.Duration]:{type:C.Float},[k.Tracks]:{type:C.Master},[k.TrackEntry]:{type:C.Master},[k.Video]:{type:C.Master},[k.Projection]:{type:C.Master},[k.ProjectionType]:{type:C.UnsignedInteger},[k.ProjectionPrivate]:{type:C.Master},[k.Chapters]:{type:C.Master},[k.Cluster]:{type:C.Master},[k.Timestamp]:{type:C.UnsignedInteger},[k.SilentTracks]:{type:C.Master},[k.SilentTrackNumber]:{type:C.UnsignedInteger},[k.Position]:{type:C.UnsignedInteger},[k.PrevSize]:{type:C.UnsignedInteger},[k.SimpleBlock]:{type:C.Binary},[k.BlockGroup]:{type:C.Master},[k.EncryptedBlock]:{type:C.Binary},[k.Attachments]:{type:C.Master},[k.Tags]:{type:C.Master},[k.Cues]:{type:C.Master},[k.CuePoint]:{type:C.Master},[k.CueTime]:{type:C.UnsignedInteger},[k.CueTrackPositions]:{type:C.Master},[k.CueTrack]:{type:C.UnsignedInteger},[k.CueClusterPosition]:{type:C.UnsignedInteger},[k.CueRelativePosition]:{type:C.UnsignedInteger},[k.CueDuration]:{type:C.UnsignedInteger},[k.CueBlockNumber]:{type:C.UnsignedInteger},[k.CueCodecState]:{type:C.UnsignedInteger},[k.CueReference]:{type:C.Master},[k.CueRefTime]:{type:C.UnsignedInteger}},cl=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Cs(s,t),r=i in Mn,n=r?Mn[i].type:C.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=Cs(d),h=u*2**((l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},Cs=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},at=(s,e)=>{switch(e){case C.SignedInteger:return s.getInt8(0);case C.UnsignedInteger:return Cs(s);case C.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(s);case C.UTF8:return new TextDecoder("utf-8").decode(s);case C.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case C.Master:return s;case C.Binary:return s;default:a.assertNever(e)}},Si=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=cl(i);if(!e(r))return;r.type===C.Master&&Si(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Xb=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=cl(s);return Si(r.value,({tag:n,type:o,value:l})=>(n===k.EBMLReadVersion?e=at(l,o):n===k.DocType?t=at(l,o):n===k.DocTypeReadVersion&&(i=at(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},hl=[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],Zb=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],eg=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Si(s,({tag:f,type:p,value:m,valueSize:v})=>{if(f===k.SeekID){const S=at(m,p);u=Cs(S)}else f!==k.SeekPosition&&(u=void 0);return f===k.Segment?(e=m.byteOffset,t=m.byteOffset+v):f===k.Info?n=!0:f===k.SeekHead?o=!0:f===k.TimestampScale?i=at(m,p):f===k.Duration?r=at(m,p):f===k.SeekPosition&&u===k.Cues?d=at(m,p):f===k.Tracks?Si(m,({tag:S,type:b,value:y})=>S===k.ProjectionType?(c=at(y,b)===1,!1):!0):n&&o&&hl.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:Is.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},tg=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ig=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Si(s,({tag:l,type:d,value:u})=>{switch(l){case k.Cues:t=!0;break;case k.CuePoint:o&&r(o)&&n.push(o),o={};break;case k.CueTime:o&&(o.time=at(u,d));break;case k.CueTrackPositions:break;case k.CueClusterPosition:o&&(o.position=at(u,d));break;default:t&&hl.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status: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}}})},sg=s=>{let e=0,t=!1;try{Si(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Zb.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},rg={validateData:Xb,parseInit:eg,getIndexRange:tg,parseSegments:ig,parseFeedableSegmentChunk:sg},Vn=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},ci=(s,e)=>{let t=s;t=Ds(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Ds(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},ag=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,m,v,S,b,y,g,T,E,w,x,M,L,B,O,_,D,V,R,P,N,G,X,se,ce,ke,Be,Y;const Ae=new DOMParser().parseFromString(s,"application/xml"),he={video:[],audio:[],text:[]},le=Ae.children[0],ht=le.getElementsByTagName("Period")[0],ft=ht.children,Rt=le.getAttribute("type")==="dynamic",pt=le.getAttribute("availabilityStartTime"),ii=pt?new Date(pt).getTime():void 0;let ve;const ki=le.getAttribute("mediaPresentationDuration"),Ai=ht.getAttribute("duration"),Bt=le.getElementsByTagName("vk:Attrs")[0],wi=Bt==null?void 0:Bt.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ki)ve=Vn(ki);else if(Ai){const re=Vn(Ai);a.isNonNullable(re)&&(ve=re)}else wi&&(ve=parseInt(wi,10));let zs=0;const Ot=(i=(t=le.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],qs=Ot.includes(Rs.WEBM_AS_IN_FFMPEG)||Ot.includes(Rs.WEBM_AS_IN_SPEC)?vi.WEBM:vi.MP4;for(const re of ft){const mt=re.getAttribute("mimeType"),Ws=re.getAttribute("codecs"),Pi=(r=re.getAttribute("contentType"))!==null&&r!==void 0?r:mt==null?void 0:mt.split("/")[0],Qs=(o=(n=re.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],_i=re.querySelectorAll("Representation"),Ks=re.querySelector("SegmentTemplate");if(Pi===be.TEXT){for(const F of _i){const fe=F.getAttribute("id")||"",bt=re.getAttribute("lang"),De=(u=(d=(l=F.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Mt=new URL(De,e).toString(),Vt=fe.includes("_auto");he[be.TEXT].push({id:fe,lang:bt,isAuto:Vt,kind:be.TEXT,url:Mt})}continue}for(const F of _i){const fe=(c=F.getAttribute("mimeType"))!==null&&c!==void 0?c:mt,bt=(f=(h=F.getAttribute("codecs"))!==null&&h!==void 0?h:Ws)!==null&&f!==void 0?f:"",De=(m=(p=F.getAttribute("contentType"))!==null&&p!==void 0?p:fe==null?void 0:fe.split("/")[0])!==null&&m!==void 0?m:Pi,Mt=(S=(v=re.getAttribute("profiles"))===null||v===void 0?void 0:v.split(","))!==null&&S!==void 0?S:[],Vt=parseInt((b=F.getAttribute("width"))!==null&&b!==void 0?b:"",10),Di=parseInt((y=F.getAttribute("height"))!==null&&y!==void 0?y:"",10),Ri=parseInt((g=F.getAttribute("bandwidth"))!==null&&g!==void 0?g:"",10)/1e3,Ii=(T=F.getAttribute("frameRate"))!==null&&T!==void 0?T:"",Js=(E=F.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Xs=Ii?js(Ii):void 0,Zs=(w=F.getAttribute("id"))!==null&&w!==void 0?w:(zs++).toString(10),er=De==="video"?`${Di}p`:De==="audio"?`${Ri}Kbps`:bt,tr=`${Zs}@${er}`,ir=(L=(M=(x=F.querySelector("BaseURL"))===null||x===void 0?void 0:x.textContent)===null||M===void 0?void 0:M.trim())!==null&&L!==void 0?L:"",Ci=new URL(ir,e).toString(),sr=[...Ot,...Qs,...Mt];let Ft;const rr=F.querySelector("SegmentBase"),Se=(B=F.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Ks;if(rr){const Re=(_=(O=F.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&_!==void 0?_:"",[Ie,jt]=Re.split("-").map(Ce=>parseInt(Ce,10)),we={from:Ie,to:jt},Ge=(D=F.querySelector("SegmentBase"))===null||D===void 0?void 0:D.getAttribute("indexRange"),[Ht,gt]=Ge?Ge.split("-").map(Ce=>parseInt(Ce,10)):[],Ye=Ge?{from:Ht,to:gt}:void 0;Ft={type:Fe.BYTE_RANGE,url:Ci,initRange:we,indexRange:Ye}}else if(Se){const Re={representationId:(V=F.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(R=F.getAttribute("bandwidth"))!==null&&R!==void 0?R:void 0},Ie=parseInt((P=Se.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),jt=(N=Se.getAttribute("initialization"))!==null&&N!==void 0?N:"",we=Se.getAttribute("media"),Ge=(X=parseInt((G=Se.getAttribute("startNumber"))!==null&&G!==void 0?G:"",10))!==null&&X!==void 0?X:1,Ht=ci(jt,Re);if(!we)throw new ReferenceError("No media attribute in SegmentTemplate");const gt=(se=Se.querySelectorAll("SegmentTimeline S"))!==null&&se!==void 0?se:[],Ye=[];let Ce=0,Gt="",Le=0;if(gt.length){let xe=Ge,ue=0;for(const ze of gt){const Pe=parseInt((ce=ze.getAttribute("d"))!==null&&ce!==void 0?ce:"",10),Ze=parseInt((ke=ze.getAttribute("r"))!==null&&ke!==void 0?ke:"",10)||0,vt=parseInt((Be=ze.getAttribute("t"))!==null&&Be!==void 0?Be:"",10);ue=Number.isFinite(vt)?vt:ue;const Li=Pe/Ie*1e3,si=ue/Ie*1e3;for(let ri=0;ri<Ze+1;ri++){const Sl=ci(we,{...Re,segmentNumber:xe.toString(10),segmentTime:(ue+ri*Pe).toString(10)}),Da=(si!=null?si:0)+ri*Li,yl=Da+Li;xe++,Ye.push({time:{from:Da,to:yl},url:Sl})}ue+=(Ze+1)*Pe,Ce+=(Ze+1)*Li}Le=ue/Ie*1e3,Gt=ci(we,{...Re,segmentNumber:xe.toString(10),segmentTime:ue.toString(10)})}else if(a.isNonNullable(ve)){const ue=parseInt((Y=Se.getAttribute("duration"))!==null&&Y!==void 0?Y:"",10)/Ie*1e3,ze=Math.ceil(ve/ue);let Pe=0;for(let Ze=1;Ze<ze;Ze++){const vt=ci(we,{...Re,segmentNumber:Ze.toString(10),segmentTime:Pe.toString(10)});Ye.push({time:{from:Pe,to:Pe+ue},url:vt}),Pe+=ue}Le=Pe,Gt=ci(we,{...Re,segmentNumber:ze.toString(10),segmentTime:Pe.toString(10)})}const Yt={time:{from:Le,to:1/0},url:Gt};Ft={type:Fe.TEMPLATE,baseUrl:Ci,segmentTemplateUrl:we,initUrl:Ht,totalSegmentsDurationMs:Ce,segments:Ye,nextSegmentBeyondManifest:Yt,timescale:Ie}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!De||!fe)continue;const Ut={video:be.VIDEO,audio:be.AUDIO,text:be.TEXT}[De];Ut&&he[Ut].push({id:tr,kind:Ut,segmentReference:Ft,profiles:sr,duration:ve,bitrate:Ri,mime:fe,codecs:bt,width:Vt,height:Di,fps:Xs,quality:Js})}}return{dynamic:Rt,liveAvailabilityStartTime:ii,duration:ve,container:qs,representations:he}},ng=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Ei(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},og=({id:s,bitrate:e})=>({id:s,bitrate:e}),lg=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=pe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:pe(s,-1)},ug=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),Fn=s=>"size"in s,ui=s=>s.type===Fe.TEMPLATE,na=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class Un{constructor(e,t,i,r,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:d,compatibilityMode:u=!1,manifest:c}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ue,this.destroyAbortController=new Ue,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,async function*(h){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 $b(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 b=Math.min(this.bufferLimit,Ps(this.sourceBuffer.buffered)*.8);this.bufferLimit=b,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield this.loadInit(f,"high",!0);const p=this.initData.get(f.id),m=this.segments.get(f.id),v=this.parsedInitData.get(f.id);a.assertNonNullable(p,"No init buffer for starting representation"),a.assertNonNullable(m,"No segments for starting representation"),p instanceof ArrayBuffer&&(this.searchGaps(m,f),yield this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(v))}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,async function*(h){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return;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 this.loadInit(f,"high",!1):m instanceof Promise&&(yield 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;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal);const v=this.getCurrentPosition();a.isNonNullable(v)&&(this.isLive||(p.forEach(S=>S.status=j.NONE),this.pruneBuffer(v,1/0,!0)),this.maintain(v))}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,async function*(h){var f;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return;for(const y of this.representations.keys()){const g=h.find(w=>w.id===y);g&&this.representations.set(y,g);const T=this.representations.get(y);if(!T||!ui(T.segmentReference))return;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 v=this.segments.get(p);a.assertNonNullable(v,"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;const b=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),b&&(yield this.sourceBufferTaskQueue.remove(b.from*1e3,b.to*1e3,this.destroyAbortController.signal)),this.searchGaps(v,m),yield this.sourceBufferTaskQueue.append(S,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isActiveLowLatency=d,this.isLive=!!(c!=null&&c.dynamic),this.container=i,i){case vi.MP4:this.containerParser=Jb;break;case vi.WEBM:this.containerParser=rg;break;default:a.assertNever(i)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Ue,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=_e(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)&&Ps(this.sourceBuffer.buffered)>=this.bufferLimit){const u=_e(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=pe(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&&_e(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=pe(i,-1);d&&d.status===j.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+r}),i=n.time.to;a.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let n=0,o=t.length-1;do r.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!ui(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>({...h,status:j.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(r=pe(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.floor(u)>=Math.floor(h.time.from)&&Math.floor(u)<=Math.floor(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const i of this.representations.values()){const r=i.segmentReference;if(!ui(r))return;const n=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),o=ci(r.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(i.id))!==null&&t!==void 0?t:[],d=l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));d&&(d.time.to=e.segment.time.to),!!l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||l.push({status:j.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const v=f<=i&&p>=i,S=f>i||v||m===0&&i===0,b=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=i+b||p<=i+b;return(h===j.NONE||h===j.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!bi(this.sourceBuffer.buffered,i))&&S&&y});if(r===-1)return[];if(t!==Fe.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}async loadSegments(e,t,i="auto"){t.segmentReference.type===Fe.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){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,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(await a.abortable(l,async function*(){const c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,c))}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const c=await this.fetcher.fetch(o,{range:n,signal:l,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;const h=new DataView(c);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}d&&r.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(h,l),r.segment.status=j.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){if(!na(c))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(c)}}async loadByteRangeSegments(e,t,i="auto"){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&&(await a.abortable(o,async function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,d))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:r,onProgress:l,signal:o,priority:i}),this.failedDownloads=0}catch(d){if(!na(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}}prepareByteRangeFetchSegmentParams(e,t){if(ui(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:pe(e,0).byte.from,to:pe(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:r,signal:n,onProgress:(d,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ui(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},l=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});l.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:r,signal:n,onProgress:u,onProgressTasks:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=_e((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:d}=l;if(l.representationId===t){if(n.aborted){r();continue}if(l.loadedBytes=i,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u);c!=null&&c.byteLength&&(d.status=j.PARTIALLY_FED,l.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),l.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const d=l.segmentReference.type,u=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Fe.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const v=f?h.byte.from-i:0,S=f?h.byte.to-i:e.byteLength,b=v<r,y=S<=r;if(h.status===j.DOWNLOADING&&b&&y){h.status=j.DOWNLOADED;const g=new DataView(e.buffer,e.byteOffset+v,p);this.sourceBufferTaskQueue.append(g,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(c,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&b&&(c.loadedBytes=Math.min(p,r-v),c.loadedBytes>c.feedingBytes)){const g=new DataView(e.buffer,e.byteOffset+v+c.feedingBytes,c.loadedBytes-c.feedingBytes),T=c.loadedBytes===p?g:this.containerParser.parseFeedableSegmentChunk(g);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 i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=j.FED,Fn(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const n of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])n.status===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 i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=ws(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,async function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async l=>{if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h);let f=c;this.isLive&&ui(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){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=Fn(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&&i){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===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 i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=ws(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==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(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(pi||(pi={}));class dg{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new Ue,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,async function*(r){let n=r;this.requestQuic&&(n=Lt(n));const o=yield Jt(n,{signal:this.abortAllController.signal}).catch(Bi);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,async function*(r,{rangeMethod:n=this.compatibilityMode?pi.HEADER:pi.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0,isLowLatency:h=!1}={}){var f,p;let m=r;const v=new Headers;if(o)switch(n){case pi.HEADER:{v.append("Range",`bytes=${o.from}-${o.to}`);break}case pi.PARAM:{const D=new URL(m,location.href);D.searchParams.append("bytes",`${o.from}-${o.to}`),m=D.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=Lt(m));let S=this.abortAllController.signal,b;if(u){const D=new Ue;if(b=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{D.abort()}catch(V){Bi(V)}}),this.abortAllController.signal.aborted||u.aborted)try{D.abort()}catch(V){Bi(V)}S=D.signal}const y=a.now(),g=yield Jt(m,{priority:d,headers:v,signal:S}).catch(Bi),T=a.now();if(!g)return b==null||b.unsubscribe(),null;if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!g.ok||!g.body)return b==null||b.unsubscribe(),Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));if(this.onHeadersReceived(g.headers),!l&&!c)return b==null||b.unsubscribe(),g.arrayBuffer();const[E,w]=g.body.tee(),x=E.getReader();c&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(w,h));let M=0,L=new Uint8Array(0),B=!1;const O=D=>{b==null||b.unsubscribe(),B=!0,Bi(D)},_=a.abortable(S,async function*({done:D,value:V}){if(M===0&&this.lastRequestFirstBytes$.next(a.now()-y),S.aborted){b==null||b.unsubscribe();return}if(!D&&V){const R=new Uint8Array(L.length+V.length);R.set(L),R.set(V,L.length),L=R,M+=V.byteLength,l==null||l(new DataView(L.buffer),M),yield x==null?void 0:x.read().then(_,O)}}.bind(this));return yield x==null?void 0:x.read().then(_,O),b==null||b.unsubscribe(),B?null:L.buffer}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n,o){var l;if(r.type!==Fe.BYTE_RANGE)return 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 v=yield this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!v)return null;const S=new DataView(v,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const b=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(b);if(!y)throw new ReferenceError("No way to load representation index");let g;if(f)g=new DataView(v,y.from-c,y.to-y.from+1);else{const E=yield this.fetch(r.url,{range:y,priority:o,measureThroughput:!1});if(!E)return null;g=new DataView(E)}const T=n.parseSegments(g,b,y);return{init:b,dataView:new DataView(v),segments:T}}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n){if(r.type!==Fe.TEMPLATE)return null;const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:r.segments.map(u=>({...u,status:j.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Aa(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,n;const{type:o}=e;switch(o){case Fe.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Fe.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Bi=s=>{if(!na(s))throw s},oa=1e3,Ls=(s,e,t)=>t*e+(1-t)*s,fl=(s,e)=>s.reduce((t,i)=>t+i,0)/e,cg=(s,e,t,i)=>{let r=0,n=t;const o=fl(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?r++:r--,n=(s.length+n-1)%s.length;return Math.abs(r)===l};class _a{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new st(`raw_${i}`),this.smoothedSeries$=new st(`smoothed_${i}`),this.reportedSeries$=new st(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class hg extends _a{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ls(this.slow,e,this.params.emaAlphaSlow),this.fast=Ls(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class fg extends _a{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=fl(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ls(this.emaSmoothed,e,this.params.emaAlpha);const i=cg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class pg extends _a{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?Ls(this.smoothed,e,this.params.emaAlpha):e}}class la{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new hg({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new fg({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new pg({initial:e,label:"liveEdgeDelay",...t})}}const mg=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},jn=["timeupdate","progress","play","seeked","stalled","waiting"];var Me;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Me||(Me={}));let bg=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new J(Me.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 Ue,this.initManifest=a.abortable(this.destroyController.signal,async function*(t,i,r){var n;this.element=t,this.manifestUrlString=Ee(i,r,ie.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Me.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Me.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,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!i)return this.manifest;let r;try{r=ag(i!=null?i:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return 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===be.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)),{...r,representations:Kt(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,async function*(t,i){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Me.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 Un(be.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new Un(be.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(oa).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=Es(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P);this.manifestUrlString=Ee(this.manifestUrlString,u+oa,ie.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...jn.map(l=>a.fromEvent(this.element,l))).pipe(a.map(l=>this.element?_e(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),mg(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 v,S;return(S=(v=m.getLiveSegmentsToLoadState(this.manifest))===null||v===void 0?void 0:v.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(async({liveLoadBufferLength:d,bufferLength:u})=>{if(a.assertNonNullable(this.element),this.liveWaitingEventCallback.cancel(),this.isUpdatingLive)return;const c=this.element.playbackRate,h=Es(this.manifestUrlString,ie.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,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,S=this.isActiveLowLatency?u:d;let b=it.None;if(this.isActiveLowLatency?b=it.ActiveLowLatency:S<p+v&&S>=p?b=it.LiveWithTargetOffset:h!==0&&S<p&&(b=it.LiveForwardBuffering),isFinite(d)&&(l=d>l?d:l),b===it.LiveForwardBuffering||b===it.LiveWithTargetOffset){const y=l-(p+m),g=Math.trunc(h+y/c);let T;d?g>0?T=g:T=0:T=h,this.manifestUrlString=Ee(this.manifestUrlString,T,ie.DASH_CMAF_OFFSET_P)}b!==it.None&&b!==it.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 new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Me.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new dg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=la.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator}),this.liveWaitingEventCallback=_l.debounce(this._liveWaitingEventCallback,this.tuning.dashCmafLive.maxWaitingDuration)}async seekLive(e){var t,i,r,n;a.assertNonNullable(this.element),this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&e===0,this.liveLastSeekOffset=e,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=Ee(this.manifestUrlString,e,ie.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((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(Me.RUNNING),this.subscription.add(a.merge(...jn.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&&bi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.isLive$.getValue()&&this.liveWaitingEventCallback()})),this.tick()}async switchRepresentation(e,t){const i={[be.VIDEO]:this.videoBufferManager,[be.AUDIO]:this.audioBufferManager,[be.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),bi(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(Me.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}async _liveWaitingEventCallback(){try{await this.seekLive(this.liveLastSeekOffset)}catch(e){this.error$.next({id:"LiveWaitingEventCallback",category:a.ErrorCategory.WTF,message:"Error in seeking live in live waiting event callback",thrown:e})}}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await 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,i=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class pl{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(ne.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Wo,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===H.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ne.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case ne.STOPPED:this.videoState.startTransitionTo(ne.READY),this.prepare();return;case ne.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(ne.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ne.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ne.PAUSED),(r=this.liveOffset)===null||r===void 0||r.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ne.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}}},this.init3DScene=t=>{var i,r,n;if(this.scene3D)return;this.scene3D=new ol(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=lt(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 bg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=dt(this.video),r=this.constructor.name,n=l=>{e.error$.next({id:r,category:a.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(xt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),n(Hi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Me.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((b,y)=>y.bitrate-b.bitrate),m=Array.from(f.video).sort((b,y)=>y.bitrate-b.bitrate),v=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const b of p){const y=og(b);y&&this.audioTracks.push({track:y,representation:b})}for(const b of m){const y=ng(b);if(y){h.push({track:y,representation:b});const g=!this.params.tuning.isAudioDisabled&&lg(p,m,b);g&&this.audioRepresentations.set(b.id,g)}}this.videoTracks$.next(h);for(const b of v){const y=ug(b);y&&this.textTracks.push({track:y,representation:b})}this.params.output.availableVideoTracks$.next(h.map(({track:b})=>b)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:b})=>b)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:b})=>b));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===Me.REPRESENTATIOS_READY&&(this.videoState.setState(ne.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!==Me.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(be.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(be.AUDIO,p.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=_e(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),v=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=ti(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:v,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),b=d?S!=null?S:c:c!=null?c:S;return b&&((l=this.videoTracks$.getValue().find(({track:y})=>y===b))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_t(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ne.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),ut(this.video)}}class gg extends pl{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let vg=class extends ll{constructor(e){super(e),this.liveOffset=new Wi}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(ra),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===ae.PLAYING){const o=e.position$.getValue()+(r-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===ae.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 Sg extends pl{constructor(e){super(e),this.liveOffset=new Wi}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(oa),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===ne.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(r-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===ne.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 tt={};var K;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const Oi=(s,e)=>new a.Observable(t=>{const i=(r,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class yg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(K.INITIALIZING),this.textTracksManager=new Xe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==K.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===H.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case K.STOPPED:break;case K.READY:case K.PLAYING:case K.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case K.STOPPED:this.prepare();break;case K.READY:case K.PLAYING:case K.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case K.PLAYING:break;case K.STOPPED:this.prepare();break;case K.READY:case K.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case K.PAUSED:break;case K.STOPPED:this.prepare();break;case K.READY:this.videoState.setState(K.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case K.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(i)}},this.video=lt(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),ut(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(tt.Hls=r.default,tt.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(K.STOPPED)}subscribe(){a.assertNonNullable(tt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=dt(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(xt(this.video,e.isLooped,i)),this.subscription.add(ot(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Oi(this.hls,tt.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(K.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===K.READY&&this.videoState.setState(K.READY),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),n(Oi(this.hls,tt.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:v,height:S}=h,b=(p=Ei((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:v,height:S});if(!b)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,g={id:m.toString(),quality:b,bitrate:h.bitrate/1e3,size:{width:v,height:S},fps:y};return this.trackLevels.set(m,{track:g,level:h}),c.push(g),c},[]))),t.availableVideoTracks$),n(Oi(this.hls,tt.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,v="internal";c.push({id:f,url:p,language:m,type:v})}e.internalTextTracks.startTransitionTo(c)}}),n(Oi(this.hls,tt.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>$e(u))),t.hostname$),this.subscription.add(Qe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Oi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Qe(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u.id))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,m=this.hls.levels[p];!m||h.bitrate>m.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:i})),n(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(K.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(K.PLAYING),await _t(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(K.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(K.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(K.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Hn="X-Playback-Duration";var Gn=async s=>{var e;const t=await Jt(s),i=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(Hn)?parseInt(t.headers.get(Hn),10):void 0};const Tg=s=>{let e=null;if(s.QUALITY&&(e=Ei(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=a.videoSizeToQuality({width:t,height:i})}return e!=null?e:null},ml=async(s,e=s)=>{var t,i;const o=(await(await Jt(s)).text()).split(`
|
|
46
|
-
`),l=[],d=[];for(let u=0;u<o.length;u++){const c=o[u],h=c.match(/^#EXT-X-STREAM-INF:(.+)/),f=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!h&&!f)){if(h){const p=Kt(h[1].split(",").map(T=>T.split("="))),m=(t=p.QUALITY)!==null&&t!==void 0?t:`stream-${p.BANDWIDTH}`,v=Tg(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 b=p["FRAME-RATE"]?parseFloat(p["FRAME-RATE"]):void 0;let y;if(p.RESOLUTION){const[T,E]=p.RESOLUTION.split("x").map(w=>parseInt(w,10));T&&E&&(y={width:T,height:E})}const g=new URL(o[++u],e).toString();v&&l.push({id:m,quality:v,url:g,bandwidth:S,size:y,fps:b})}if(f){const p=Kt(f[1].split(",").map(b=>b.split("=")).map(([b,y])=>[b,y.replace(/^"|"$/g,"")])),m=(i=p.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),v=p.LANGUAGE,S=p.NAME;m&&v&&d.push({type:"internal",id:v,label:S,language:v,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}};var Z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(Z||(Z={}));class Eg{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(Z.STOPPED),this.textTracksManager=new Xe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new Wi,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){r!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(r===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(l||d||u){const f=this.videoState.getState();this.videoState.setState(Z.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===H.Requested){this.videoState.startTransitionTo(Z.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case Z.READY:n===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Z.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},ml(Ee(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next($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,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=dt(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next($e(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===H.Requested&&this.seek(l.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URLSearchParams(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:u,min:c}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[h,f]of[[u,"mq"],[c,"lq"]]){const p=String(parseFloat(h||""));f&&p&&o.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?ie.DASH_CMAF_OFFSET_P:ie.OFFSET_P,d=Ee(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",d),this.video.load(),Gn(d).then(u=>{var c;if(!a.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(c=this.params.source.maxSeekBackTime)!==null&&c!==void 0?c:this.maxSeekBackTime$.getValue();if(a.isNullable(h)||!isFinite(h))try{Jt(d).then(f=>f.text()).then(f=>{var p;const m=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(m){const v=new URL(m,d).toString();Gn(v).then(S=>{a.isNullable(S)||this.maxSeekBackTime$.next(S)})}})}catch(f){}}})}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var te;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(te||(te={}));class $g{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(te.STOPPED),this.textTracksManager=new Xe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===exports.PlaybackState.STOPPED){i!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(i===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(o||l||d){const h=this.videoState.getState();this.videoState.setState(te.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&c.state===H.Requested&&this.seek(c.position),i){case te.READY:r===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(te.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case te.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case te.CHANGING_MANIFEST:break;default:return a.assertNever(i)}},this.params=e,this.video=lt(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),ml(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=dt(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(xt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===te.READY&&this.videoState.setState(te.READY),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next($e(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===te.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===H.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!a.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(a.merge(a.fromEvent(l,"addtrack"),a.fromEvent(l,"removetrack"),a.fromEvent(l,"change"),a.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<l.length;d++)l[d].mode="hidden"},i))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URLSearchParams(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,c]of[[l,"mq"],[d,"lq"]]){const h=String(parseFloat(u||""));c&&h&&o.set(c,h)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(te.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(oe||(oe={}));class kg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(oe.STOPPED),this.trackUrls={},this.textTracksManager=new Xe,this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.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(oe.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.seekState.getState();if(u&&n!==oe.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(c){const{currentTime:f}=this.video;this.prepare(),h.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:f*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[c.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===H.Requested&&this.seek(h.position),n){case oe.READY:o===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(oe.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case oe.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(n)}},this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=dt(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(xt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===oe.READY&&this.videoState.setState(oe.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()===oe.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;a.assertNonNullable(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];a.assertNonNullable(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=Lt(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next($e(i))}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(oe.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,r,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const d=(i=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||i===void 0?void 0:i.track,u=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,c=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(d&&c&&a.isHigherOrEqual(c.quality,d.quality)&&(o=d),!o){const h=Object.values(this.trackUrls).filter(p=>!a.isInvariantQuality(p.track.quality)&&a.isHigher(p.track.quality,e)),f=h.length;f&&(o=h[f-1].track)}o&&(l=o.quality)}else if(!e){const d=Object.values(this.trackUrls).map(u=>u.track);o=ti(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 Yn=["stun:videostun.mycdn.me:80"],Ag=1e3,wg=3,xr=()=>null;class Pg{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=xr,this.externalStopCallback=xr,this.externalErrorCallback=xr,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Yn}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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})}async onPeerConnectionStream(e){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()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Ag)}normalizeOptions(e={}){const t={stunServerList:Yn,maxRetryNumber:wg,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ee||(ee={}));class _g{constructor(e){this.videoState=new J(ee.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case ee.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed()):(r==null?void 0:r.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return a.assertNever(t)}},this.subscription=new a.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=lt(e.container),this.liveStreamClient=new Pg(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),ut(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const r=dt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ee.READY&&this.videoState.setState(ee.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ot(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case ee.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case ee.READY:break;case ee.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case ee.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},i)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next($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,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(ee.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(){_t(this.video).then(e=>{e||(this.videoState.setState(ee.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:a.ErrorCategory.DOM,thrown:e}))}prepare(){this.liveStreamClient.connect()}}class zn{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 Nr,Br,Or,Mr,Vr,Fr,us,Ur,ds,jr,cs,Hr,hs,Gr,fs,Yr,ps,zr;const bl=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Ct=document.createElement("video"),Dg='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Rg='video/mp4; codecs="hev1.1.6.L93.B0"',gl='video/webm; codecs="vp09.00.10.08"',vl='video/webm; codecs="av01.0.00M.08"',Ig='audio/mp4; codecs="mp4a.40.2"',Cg='audio/webm; codecs="opus"',qe={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Br=(Nr=window.SourceBuffer)===null||Nr===void 0?void 0:Nr.prototype)===null||Br===void 0)&&Br.appendBuffer)),hls:!!(!((Or=Ct.canPlayType)===null||Or===void 0)&&Or.call(Ct,"application/x-mpegurl")||!((Mr=Ct.canPlayType)===null||Mr===void 0)&&Mr.call(Ct,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Ne={mp4:!!(!((Vr=Ct.canPlayType)===null||Vr===void 0)&&Vr.call(Ct,"video/mp4")),webm:!!(!((Fr=Ct.canPlayType)===null||Fr===void 0)&&Fr.call(Ct,"video/webm")),cmaf:!0},nt={h264:!!(!((Ur=(us=window.MediaSource)===null||us===void 0?void 0:us.isTypeSupported)===null||Ur===void 0)&&Ur.call(us,Dg)),h265:!!(!((jr=(ds=window.MediaSource)===null||ds===void 0?void 0:ds.isTypeSupported)===null||jr===void 0)&&jr.call(ds,Rg)),vp9:!!(!((Hr=(cs=window.MediaSource)===null||cs===void 0?void 0:cs.isTypeSupported)===null||Hr===void 0)&&Hr.call(cs,gl)),av1:!!(!((Gr=(hs=window.MediaSource)===null||hs===void 0?void 0:hs.isTypeSupported)===null||Gr===void 0)&&Gr.call(hs,vl)),aac:!!(!((Yr=(fs=window.MediaSource)===null||fs===void 0?void 0:fs.isTypeSupported)===null||Yr===void 0)&&Yr.call(fs,Ig)),opus:!!(!((zr=(ps=window.MediaSource)===null||ps===void 0?void 0:ps.isTypeSupported)===null||zr===void 0)&&zr.call(ps,Cg))},di=(nt.h264||nt.h265)&&nt.aac;var It;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(It||(It={}));var Tt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Tt||(Tt={}));let zt;const Lg=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:vl}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:gl}})]);zt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Lg()}catch(s){console.error(s)}const Gi=qe.hls&&Ne.mp4,xg=()=>Object.keys(nt).filter(s=>nt[s]),Ng=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return qe.mse&&Ne.mp4&&di;case exports.VideoFormat.DASH_SEP:return qe.mse&&Ne.mp4&&di;case exports.VideoFormat.DASH_WEBM:return qe.mse&&Ne.webm&&nt.vp9&&nt.opus;case exports.VideoFormat.DASH_WEBM_AV1:return qe.mse&&Ne.webm&&nt.av1&&nt.opus;case exports.VideoFormat.DASH_LIVE:return qe.mse&&Ne.mp4&&di;case exports.VideoFormat.DASH_LIVE_CMAF:return qe.mse&&Ne.mp4&&di&&Ne.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return qe.mse&&Ne.mp4&&di;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return Gi||e&&qe.mse&&Ne.mp4&&di;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return Gi;case exports.VideoFormat.MPEG:return Ne.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return qe.webrtc&&qe.ws&&nt.h264&&(Ne.mp4||Ne.webm);default:return a.assertNever(t)}}),Mi=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case It.VP9:return[e,t];case It.AV1:return[t,e];case It.NONE:return[];case It.SMOOTH:return zt?zt[t].smooth?[t,e]:zt[e].smooth?[e,t]:[t,e]:[e,t];case It.POWER_EFFICIENT:return zt?zt[t].powerEfficient?[t,e]:zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(s)}return[e,t]},Bg=({webmCodec:s,androidPreferredFormat:e})=>{if(bl)switch(e){case Tt.MPEG:return[exports.VideoFormat.MPEG,...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case Tt.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case Tt.DASH:return[...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return Gi?[...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Og=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],r=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...r],o=[...r,...i];let l;if(bl)switch(s){case Tt.DASH:{l=n;break}case Tt.HLS:case Tt.MPEG:{l=o;break}}else Gi?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},qn=s=>s?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Mg=s=>new a.Observable(e=>{const t=new a.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Vg={cacheDuration:12e4},Fg={chunkDuration:5e3,maxParallelRequests:5};class Ug{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=Ng([...Og(this.params.tuning),...Bg(this.params.tuning)],this.params.tuning.useHlsJs).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let n=[];i?n=[i]:r.length?n=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new zn(n);const o=[...qn(!0),...qn(!1)];this.chromecastFormatsIterator=new zn(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(a.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==H.None;if(this.params.desiredState.seekState.setState({state:H.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case ye.SCREEN:return this.createScreenProvider(t);case ye.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Up({...o,source:l,config:Vg})}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 wn({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new gg({...o,source:l}):new Eb({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJsCMAF?new wn({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new Sg({...o,source:l}):new vg({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),Gi||!this.params.tuning.useHlsJs?new $g({...o,source:l}):new yg({...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 Eg({...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 kg({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bp({...o,source:l,config:{...Fg,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new _g({container:i,source:l,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new zf({connection:l,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?ye.CHROMECAST:ye.SCREEN}chooseFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case ye.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case ye.SCREEN:return this.screenFormatsIterator.next();case ye.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case ye.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case ye.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const n=new URL(r);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Kt(Object.entries(e).map(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,i=0;return e.add(a.merge(this.providerOutput.error$,Mg({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===ye.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(ye.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=i<this.params.tuning.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:ye.SCREEN)}})),e}}const jg=5e3,Wn="one_video_throughput",Qn="one_video_rtt",Et=window.navigator.connection,Kn=()=>{const s=Et==null?void 0:Et.downlink;if(a.isNonNullable(s)&&s!==10)return s*1e3},Jn=()=>{const s=Et==null?void 0:Et.rtt;if(a.isNonNullable(s)&&s!==3e3)return s},Xn=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Ui{constructor(e){var t,i;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Ui.load(Wn)||(e.useBrowserEstimation?Kn():void 0)||jg,n=(i=(t=Ui.load(Qn))!==null&&t!==void 0?t:e.useBrowserEstimation?Jn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(Xn(r,n,e.rttPenaltyRequestSize)),this.throughput=la.getSmoothedValue(r,-1,e),this.rtt=la.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Kn();d&&this.throughput.next(d);const u=Jn();a.isNonNullable(u)&&this.rtt.next(u)};Et&&"onchange"in Et&&this.subscription.add(a.fromEvent(Et,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(Wn,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(Qn,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})=>Xn(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=a.now();const r=new a.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,i=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=a.now()}));break}r.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,n=a.now(),o=0,l=a.now();const d=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:h})=>{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());await(i==null?void 0:i.read().then(u,d))}};this.concurrentDownloads.add(e),i==null||i.read().then(u,d)}addRawSpeed(e,t,i=1,r=!1){if(Ui.sanityCheck(e,t,r)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=a.safeStorage.get(e);if(a.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Zn={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:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:It.VP9,androidPreferredFormat:Tt.MPEG,preferCMAF:!0,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}},Hg=s=>{var e;return{...a.fillWithDefault(s,Zn),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Zn.configName]}};var eo=({seekState:s,position$:e})=>a.merge(s.stateChangeEnded$.pipe(a.map(({to:t})=>{var i;return t.state===H.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>s.getState().state===H.None))),Gg=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return a.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const Yg=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class zg{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 J(exports.PlaybackState.STOPPED),seekState:new J({state:H.None}),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),playbackRate:new J(1),externalTextTracks:new J([]),internalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({}),cameraOrientation:new J({x:0,y:0})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),canChangePlaybackSpeed$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),atLiveDurationEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:bp},this.initLogs(),this.tuning=Hg(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Rl({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ui(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,r);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Gg(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Ug({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?a.fromEvent(document,"visibilitychange").pipe(a.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:H.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Yg(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){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(),i=t.state===H.None?void 0:t.position;return a.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===H.Requested?this.desiredState.seekState.setState({...o,state:H.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===H.Applying&&(this.desiredState.seekState.setState({state:H.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:eo({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(eo({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>i.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,i).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:n})=>n===r),i||this.setAutoQuality(!0)),i||(i=ti(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),mp(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>pp(i)),this.providerContainer.current$.subscribe(({type:i})=>as("provider",i)),t.duration$.subscribe(i=>as("duration",i)),t.availableVideoTracks$.pipe(a.filter(i=>!!i.length),a.once()).subscribe(i=>as("tracks",i)),this.events.fatalError$.subscribe(new st("fatalError")),this.events.managedError$.subscribe(new st("managedError")),t.position$.subscribe(new st("position")),t.currentVideoTrack$.pipe(a.map(i=>i==null?void 0:i.quality)).subscribe(new st("quality")),this.info.currentBuffer$.subscribe(new st("buffer")),t.isBuffering$.subscribe(new st("isBuffering"))].forEach(i=>this.subscription.add(i)),as("codecs",xg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(r)})})};this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);r&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const qg=`@vkontakte/videoplayer-core@${to}`;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=zg;exports.SDK_VERSION=qg;exports.VERSION=to;
|
|
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 ul{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const r=this.canvas.getContext("webgl");if(!r)throw new Error("Could not initialize WebGL context");this.gl=r,this.container.appendChild(this.canvas),this.camera=new vb(this.params.fov,this.params.orientation),this.cameraRotationManager=new Sb(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),r=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(r,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(yb,this.gl.VERTEX_SHADER),i=this.createShader(Tb,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const r=this.frameHeight/(this.frameWidth/this.viewportWidth);return r>this.viewportHeight?t=this.viewportHeight/r:i=r/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,r=this.camera.fov.y/180/2,n=e-i,o=t-r,l=e+i,d=t-r,u=e+i,c=t+r,h=e-i,f=t+r;return[n,o,l,d,u,c,h,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}let dl=class{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(ae.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ko,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===H.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ae.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==ae.STOPPED&&(this.videoState.startTransitionTo(ae.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(ae.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case ae.STOPPED:this.videoState.startTransitionTo(ae.READY),this.prepare();return;case ae.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(ae.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ae.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ae.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ae.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 ae.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ae.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 i,r,n;if(this.scene3D)return;this.scene3D=new ul(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=lt(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(ke(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new gb({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=dt(this.video),r=this.constructor.name,n=l=>{e.error$.next({id:r,category:a.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(xt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),n(Hi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ae.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ae.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ae.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Me.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();a.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((g,y)=>y.bitrate-g.bitrate),m=Array.from(f.video).sort((g,y)=>y.bitrate-g.bitrate),v=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const y=Am(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=wm(g);if(y){h.push({track:y,representation:g});const b=!this.params.tuning.isAudioDisabled&&Pm(p,m,g);b&&this.audioRepresentations.set(g.id,b)}}this.videoTracks$.next(h);for(const g of v){const y=_m(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===Me.REPRESENTATIOS_READY&&(this.videoState.setState(ae.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!==Me.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(be.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(be.AUDIO,p.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=De(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),v=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=ti(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:v,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=d?S!=null?S:c:c!=null?c:S;return g&&((l=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_t(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ae.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),ut(this.video)}},Eb=class extends dl{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}};var ge;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(ge||(ge={}));var it;(function(s){s[s.ActiveLowLatency=0]="ActiveLowLatency",s[s.LiveWithTargetOffset=1]="LiveWithTargetOffset",s[s.LiveForwardBuffering=2]="LiveForwardBuffering",s[s.None=3]="None"})(it||(it={}));var Is;(function(s){s.WEBM_AS_IN_SPEC="urn:mpeg:dash:profile:webm-on-demand:2012",s.WEBM_AS_IN_FFMPEG="urn:webm:dash:profile:webm-on-demand:2012"})(Is||(Is={}));var Ue;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(Ue||(Ue={}));var j;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(j||(j={}));var vi;(function(s){s.MP4="mp4",s.WEBM="webm"})(vi||(vi={}));var Rs;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Rs||(Rs={}));var ne;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ne||(ne={}));var Cr,Lr;let cl=!1;try{cl=a.getCurrentBrowser().browser===a.CurrentClientBrowser.Safari&&parseInt((Lr=(Cr=navigator.userAgent.match(/Version\/(\d+)/))===null||Cr===void 0?void 0:Cr[1])!==null&&Lr!==void 0?Lr:"",10)<16}catch(s){console.error(s)}class $b{constructor(e){this.bufferFull$=new a.Subject,this.error$=new a.Subject,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const i=(t=this.currentTask.signal)===null||t===void 0?void 0:t.aborted;this.currentTask.callback(!i),this.currentTask=null}this.queue.length&&this.pull()}catch(i){this.error$.next({id:"BufferTaskQueueUnknown",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer appending or removal failed",thrown:i})}},this.buffer=e,this.buffer.addEventListener("updateend",this.completeTask)}async append(e,t){return t&&t.aborted?!1:new Promise(i=>{const r={operation:"append",data:e,signal:t,callback:i};this.queue.push(r),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(r=>{const n={operation:"remove",from:e,to:t,signal:i,callback:r};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;cl&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:r}of this.queue)r(!1);i&&(this.queue=[i]),this.pull()})}destroy(){this.destroyed=!0,this.buffer.removeEventListener("updateend",this.completeTask),this.queue=[],this.currentTask=null;try{this.buffer.abort()}catch(e){if(!(e instanceof DOMException&&e.name==="InvalidStateError"))throw e}}pull(){var e;if(this.buffer.updating||this.currentTask||this.destroyed)return;const t=this.queue.shift();if(!t)return;if(!((e=t.signal)===null||e===void 0)&&e.aborted){t.callback(!1),this.pull();return}this.currentTask=t;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(n){n instanceof DOMException&&n.name==="QuotaExceededError"&&i==="append"?this.bufferFull$.next(this.currentTask.data.byteLength):n instanceof DOMException&&n.name==="InvalidStateError"||this.error$.next({id:`BufferTaskQueue:${i}`,category:a.ErrorCategory.VIDEO_PIPELINE,message:"Buffer operation failed",thrown:n}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&this.currentTask.operation==="abort"&&this.completeTask()}execute(e){const{operation:t}=e;switch(t){case"append":this.buffer.appendBuffer(e.data);break;case"remove":this.buffer.remove(e.from/1e3,e.to/1e3);break;case"abort":this.buffer.abort();break;case"safariAbort":{this.buffer.abort(),this.buffer.appendBuffer(e.init);break}default:a.assertNever(t)}}}class Ge{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 hl extends Ge{}class kb extends Ge{constructor(e){super(e),this.compatibleBrands=[],this.majorBrand=this.readString(4),this.minorVersion=this.readUint32();let t=this.size-this.cursor;for(;t;){const i=this.readString(4);this.compatibleBrands.push(i),t-=4}}}class wb extends Ge{parseChildrenBoxes(){return Nt(this.content)}}class Ab extends Ge{parseChildrenBoxes(){return Nt(this.content)}}class Pb extends Ge{constructor(e){super(e),this.data=this.content}}class Dt extends Ge{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class _b extends Dt{get earliestPresentationTime(){return this.earliestPresentationTime32}get firstOffset(){return this.firstOffset32}constructor(e){super(e),this.segments=[],this.referenceId=this.readUint32(),this.timescale=this.readUint32(),this.earliestPresentationTime32=this.readUint32(),this.firstOffset32=this.readUint32(),this.earliestPresentationTime64=0,this.firstOffset64=0,this.referenceCount=this.readUint32()&65535;for(let t=0;t<this.referenceCount;t++){let i=this.readUint32();const r=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:r,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class Db extends Ge{parseChildrenBoxes(){return Nt(this.content)}}class Ib extends Ge{parseChildrenBoxes(){return Nt(this.content)}}var Qt;(function(s){s[s.MONOSCOPIC=0]="MONOSCOPIC",s[s.TOP_BOTTOM=1]="TOP_BOTTOM",s[s.LEFT_RIGHT=2]="LEFT_RIGHT",s[s.STEREO_CUSTOM=3]="STEREO_CUSTOM",s[s.RIGHT_LEFT=4]="RIGHT_LEFT"})(Qt||(Qt={}));class Rb extends Dt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Qt.MONOSCOPIC;break;case 1:this.stereoMode=Qt.TOP_BOTTOM;break;case 2:this.stereoMode=Qt.LEFT_RIGHT;break;case 3:this.stereoMode=Qt.STEREO_CUSTOM;break;case 4:this.stereoMode=Qt.RIGHT_LEFT;break}this.cursor+=1}}class Cb extends Dt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class Lb extends Dt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class xb extends Ge{parseChildrenBoxes(){return Nt(this.content)}}class Nb extends Dt{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 Bb extends Ge{parseChildrenBoxes(){return Nt(this.content)}}class Ob extends Ge{parseChildrenBoxes(){return Nt(this.content)}}class Mb extends Dt{constructor(e){super(e),this.sequenceNumber=this.readUint32()}}class Vb extends Ge{parseChildrenBoxes(){return Nt(this.content)}}class Fb extends Dt{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 Ub extends Dt{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 jb extends Dt{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 Hb={ftyp:kb,moov:wb,moof:Ab,mdat:Pb,sidx:_b,trak:Db,mdia:xb,mfhd:Mb,tkhd:Nb,traf:Vb,tfhd:Fb,tfdt:Ub,trun:jb,minf:Bb,sv3d:Ib,st3d:Rb,prhd:Cb,proj:Ob,equi:Lb,unknown:hl};class Gb{createBox(e,t){const i=Hb[e];return i?new i(t):new hl(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Ys.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Ys=new Gb;function Fi(s,e){const t=new Uint8Array(s.buffer),i=e.split("").map(o=>o.charCodeAt(0));let r=s.byteOffset,n=[];for(;r<t.byteLength;){if(t[r]===i[n.length]?n.push(t[r]):n=[],n.length===4){const l=new DataView(s.buffer,r-7,4).getUint32(0);return r-7+l>s.buffer.byteLength?null:Ys.createBox(e,new DataView(s.buffer,r-7))}r++}return null}function oa(s,e){const t=[];let i=s.byteOffset;for(;i<s.buffer.byteLength;){const r=Fi(new DataView(s.buffer,i,s.buffer.byteLength-i),e);if(r)t.push(r),i=r.source.byteOffset+r.size;else break}return t}function Nt(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Ys.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Yb=new TextDecoder("ascii"),zb=s=>Yb.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",qb=s=>{const e=Ys.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:j.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},Wb=s=>{const e=oa(s,"mdat"),t=oa(s,"moof");if(!(e.length&&t.length))return null;const i=t[0],r=e[e.length-1],n=i.source.byteOffset,l=r.source.byteOffset-i.source.byteOffset+r.size;return new DataView(s.buffer,n,l)},Qb=(s,e)=>{const t=oa(s,"traf"),i=t[t.length-1].children.find(d=>d.type==="tfhd"),r=t[t.length-1].children.find(d=>d.type==="tfdt"),n=t[t.length-1].children.find(d=>d.type==="trun");let o=0;return n.sampleDuration.length?o=n.sampleDuration.reduce((d,u)=>d+u,0):o=i.defaultSampleDuration*n.sampleCount,(Number(r.baseMediaDecodeTime)+o)/e*1e3},Kb=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Rs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Fi(s,"sv3d")){e.is3dVideo=!0;const i=Fi(s,"st3d");i&&(e.stereoMode=i.stereoMode);const r=Fi(s,"prhd");r&&(e.projectionData.pose.yaw=r.poseYawDegrees,e.projectionData.pose.pitch=r.posePitchDegrees,e.projectionData.pose.roll=r.poseRollDegrees);const n=Fi(s,"equi");n&&(e.projectionData.bounds.top=n.projectionBoundsTop,e.projectionData.bounds.right=n.projectionBoundsRight,e.projectionData.bounds.bottom=n.projectionBoundsBottom,e.projectionData.bounds.left=n.projectionBoundsLeft)}return e},Jb={validateData:zb,parseInit:Kb,getIndexRange:()=>{},parseSegments:qb,parseFeedableSegmentChunk:Wb,getSegmentEndTime:Qb};var k;(function(s){s[s.EBML=440786851]="EBML",s[s.EBMLVersion=17030]="EBMLVersion",s[s.EBMLReadVersion=17143]="EBMLReadVersion",s[s.EBMLMaxIDLength=17138]="EBMLMaxIDLength",s[s.EBMLMaxSizeLength=17139]="EBMLMaxSizeLength",s[s.DocType=17026]="DocType",s[s.DocTypeVersion=17031]="DocTypeVersion",s[s.DocTypeReadVersion=17029]="DocTypeReadVersion",s[s.Void=236]="Void",s[s.Segment=408125543]="Segment",s[s.SeekHead=290298740]="SeekHead",s[s.Seek=19899]="Seek",s[s.SeekID=21419]="SeekID",s[s.SeekPosition=21420]="SeekPosition",s[s.Info=357149030]="Info",s[s.TimestampScale=2807729]="TimestampScale",s[s.Duration=17545]="Duration",s[s.Tracks=374648427]="Tracks",s[s.TrackEntry=174]="TrackEntry",s[s.Video=224]="Video",s[s.Projection=30320]="Projection",s[s.ProjectionType=30321]="ProjectionType",s[s.ProjectionPrivate=30322]="ProjectionPrivate",s[s.Chapters=272869232]="Chapters",s[s.Cluster=524531317]="Cluster",s[s.Timestamp=231]="Timestamp",s[s.SilentTracks=22612]="SilentTracks",s[s.SilentTrackNumber=22743]="SilentTrackNumber",s[s.Position=167]="Position",s[s.PrevSize=171]="PrevSize",s[s.SimpleBlock=163]="SimpleBlock",s[s.BlockGroup=160]="BlockGroup",s[s.EncryptedBlock=175]="EncryptedBlock",s[s.Attachments=423732329]="Attachments",s[s.Tags=307544935]="Tags",s[s.Cues=475249515]="Cues",s[s.CuePoint=187]="CuePoint",s[s.CueTime=179]="CueTime",s[s.CueTrackPositions=183]="CueTrackPositions",s[s.CueTrack=247]="CueTrack",s[s.CueClusterPosition=241]="CueClusterPosition",s[s.CueRelativePosition=240]="CueRelativePosition",s[s.CueDuration=178]="CueDuration",s[s.CueBlockNumber=21368]="CueBlockNumber",s[s.CueCodecState=234]="CueCodecState",s[s.CueReference=219]="CueReference",s[s.CueRefTime=150]="CueRefTime"})(k||(k={}));var C;(function(s){s.SignedInteger="int",s.UnsignedInteger="uint",s.Float="float",s.String="string",s.UTF8="utf8",s.Date="date",s.Master="master",s.Binary="binary"})(C||(C={}));const Fn={[k.EBML]:{type:C.Master},[k.EBMLVersion]:{type:C.UnsignedInteger},[k.EBMLReadVersion]:{type:C.UnsignedInteger},[k.EBMLMaxIDLength]:{type:C.UnsignedInteger},[k.EBMLMaxSizeLength]:{type:C.UnsignedInteger},[k.DocType]:{type:C.String},[k.DocTypeVersion]:{type:C.UnsignedInteger},[k.DocTypeReadVersion]:{type:C.UnsignedInteger},[k.Void]:{type:C.Binary},[k.Segment]:{type:C.Master},[k.SeekHead]:{type:C.Master},[k.Seek]:{type:C.Master},[k.SeekID]:{type:C.Binary},[k.SeekPosition]:{type:C.UnsignedInteger},[k.Info]:{type:C.Master},[k.TimestampScale]:{type:C.UnsignedInteger},[k.Duration]:{type:C.Float},[k.Tracks]:{type:C.Master},[k.TrackEntry]:{type:C.Master},[k.Video]:{type:C.Master},[k.Projection]:{type:C.Master},[k.ProjectionType]:{type:C.UnsignedInteger},[k.ProjectionPrivate]:{type:C.Master},[k.Chapters]:{type:C.Master},[k.Cluster]:{type:C.Master},[k.Timestamp]:{type:C.UnsignedInteger},[k.SilentTracks]:{type:C.Master},[k.SilentTrackNumber]:{type:C.UnsignedInteger},[k.Position]:{type:C.UnsignedInteger},[k.PrevSize]:{type:C.UnsignedInteger},[k.SimpleBlock]:{type:C.Binary},[k.BlockGroup]:{type:C.Master},[k.EncryptedBlock]:{type:C.Binary},[k.Attachments]:{type:C.Master},[k.Tags]:{type:C.Master},[k.Cues]:{type:C.Master},[k.CuePoint]:{type:C.Master},[k.CueTime]:{type:C.UnsignedInteger},[k.CueTrackPositions]:{type:C.Master},[k.CueTrack]:{type:C.UnsignedInteger},[k.CueClusterPosition]:{type:C.UnsignedInteger},[k.CueRelativePosition]:{type:C.UnsignedInteger},[k.CueDuration]:{type:C.UnsignedInteger},[k.CueBlockNumber]:{type:C.UnsignedInteger},[k.CueCodecState]:{type:C.UnsignedInteger},[k.CueReference]:{type:C.Master},[k.CueRefTime]:{type:C.UnsignedInteger}},fl=s=>{const e=s.getUint8(0);let t=0;e&128?t=1:e&64?t=2:e&32?t=3:e&16&&(t=4);const i=Cs(s,t),r=i in Fn,n=r?Fn[i].type:C.Binary,o=s.getUint8(t);let l=0;o&128?l=1:o&64?l=2:o&32?l=3:o&16?l=4:o&8?l=5:o&4?l=6:o&2?l=7:o&1&&(l=8);const d=new DataView(s.buffer,s.byteOffset+t+1,l-1),u=o&255>>l,c=Cs(d),h=u*2**((l-1)*8)+c,f=t+l;let p;return f+h>s.byteLength?p=new DataView(s.buffer,s.byteOffset+f):p=new DataView(s.buffer,s.byteOffset+f,h),{tag:r?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:p,valueSize:h}},Cs=(s,e=s.byteLength)=>{switch(e){case 1:return s.getUint8(0);case 2:return s.getUint16(0);case 3:return s.getUint8(0)*2**16+s.getUint16(1);case 4:return s.getUint32(0);case 5:return s.getUint8(0)*2**32+s.getUint32(1);case 6:return s.getUint16(0)*2**32+s.getUint32(2);case 7:{const t=s.getUint8(0)*281474976710656+s.getUint16(1)*4294967296+s.getUint32(3);if(Number.isSafeInteger(t))return t}case 8:throw new ReferenceError("Int64 is not supported")}return 0},at=(s,e)=>{switch(e){case C.SignedInteger:return s.getInt8(0);case C.UnsignedInteger:return Cs(s);case C.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case C.String:return new TextDecoder("ascii").decode(s);case C.UTF8:return new TextDecoder("utf-8").decode(s);case C.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case C.Master:return s;case C.Binary:return s;default:a.assertNever(e)}},Si=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),r=fl(i);if(!e(r))return;r.type===C.Master&&Si(r.value,e),t=r.value.byteOffset-s.byteOffset+r.valueSize}},Xb=s=>{if(s.getUint32(0)!==k.EBML)return!1;let e,t,i;const r=fl(s);return Si(r.value,({tag:n,type:o,value:l})=>(n===k.EBMLReadVersion?e=at(l,o):n===k.DocType?t=at(l,o):n===k.DocTypeReadVersion&&(i=at(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},pl=[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],Zb=[k.Timestamp,k.SilentTracks,k.SilentTrackNumber,k.Position,k.PrevSize,k.SimpleBlock,k.BlockGroup,k.EncryptedBlock],eg=s=>{let e,t,i,r,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Si(s,({tag:f,type:p,value:m,valueSize:v})=>{if(f===k.SeekID){const S=at(m,p);u=Cs(S)}else f!==k.SeekPosition&&(u=void 0);return f===k.Segment?(e=m.byteOffset,t=m.byteOffset+v):f===k.Info?n=!0:f===k.SeekHead?o=!0:f===k.TimestampScale?i=at(m,p):f===k.Duration?r=at(m,p):f===k.SeekPosition&&u===k.Cues?d=at(m,p):f===k.Tracks?Si(m,({tag:S,type:g,value:y})=>S===k.ProjectionType?(c=at(y,g)===1,!1):!0):n&&o&&pl.includes(f)&&(l=!0),!l}),a.assertNonNullable(e,"Failed to parse webm Segment start"),a.assertNonNullable(t,"Failed to parse webm Segment end"),a.assertNonNullable(r,"Failed to parse webm Segment duration"),i=i!=null?i:1e6,{segmentStart:Math.round(e/1e9*i*1e3),segmentEnd:Math.round(t/1e9*i*1e3),timeScale:i,segmentDuration:Math.round(r/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:Rs.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},tg=s=>{if(a.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},ig=(s,e)=>{let t=!1,i=!1;const r=l=>a.isNonNullable(l.time)&&a.isNonNullable(l.position),n=[];let o;return Si(s,({tag:l,type:d,value:u})=>{switch(l){case k.Cues:t=!0;break;case k.CuePoint:o&&r(o)&&n.push(o),o={};break;case k.CueTime:o&&(o.time=at(u,d));break;case k.CueTrackPositions:break;case k.CueClusterPosition:o&&(o.position=at(u,d));break;default:t&&pl.includes(l)&&(i=!0)}return!(t&&i)}),o&&r(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status: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}}})},sg=s=>{let e=0,t=!1;try{Si(s,i=>i.tag===k.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Zb.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[k.SimpleBlock,k.BlockGroup,k.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},rg={validateData:Xb,parseInit:eg,getIndexRange:tg,parseSegments:ig,parseFeedableSegmentChunk:sg},Un=s=>{if(!s.startsWith("P"))return;const e=(o,l)=>{const d=o?parseFloat(o.replace(",",".")):NaN;return(isNaN(d)?0:d)*l},i=/^(-|\+)?P(?:([-+]?[0-9,.]*)Y)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)W)?(?:([-+]?[0-9,.]*)D)?(?:T(?:([-+]?[0-9,.]*)H)?(?:([-+]?[0-9,.]*)M)?(?:([-+]?[0-9,.]*)S)?)?$/.exec(s),r=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],r),hours:e(i==null?void 0:i[6],r),minutes:e(i==null?void 0:i[7],r),seconds:e(i==null?void 0:i[8],r)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},ci=(s,e)=>{let t=s;t=Ds(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[r,n]of Object.entries(i)){const o=new RegExp(`\\$${r}(?:%0(\\d+)d)?\\$`,"g");t=Ds(t,o,(l,d)=>a.isNullable(n)?l:a.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},ag=(s,e)=>{var t,i,r,n,o,l,d,u,c,h,f,p,m,v,S,g,y,b,T,E,A,x,M,L,B,O,_,D,V,I,P,N,G,X,se,ce,we,Oe,Y;const Ae=new DOMParser().parseFromString(s,"application/xml"),he={video:[],audio:[],text:[]},le=Ae.children[0],ht=le.getElementsByTagName("Period")[0],ft=ht.children,It=le.getAttribute("type")==="dynamic",pt=le.getAttribute("availabilityStartTime"),ii=pt?new Date(pt).getTime():void 0;let Se;const ki=le.getAttribute("mediaPresentationDuration"),wi=ht.getAttribute("duration"),Bt=le.getElementsByTagName("vk:Attrs")[0],Ai=Bt==null?void 0:Bt.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ki)Se=Un(ki);else if(wi){const re=Un(wi);a.isNonNullable(re)&&(Se=re)}else Ai&&(Se=parseInt(Ai,10));let zs=0;const Ot=(i=(t=le.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],qs=Ot.includes(Is.WEBM_AS_IN_FFMPEG)||Ot.includes(Is.WEBM_AS_IN_SPEC)?vi.WEBM:vi.MP4;for(const re of ft){const mt=re.getAttribute("mimeType"),Ws=re.getAttribute("codecs"),Pi=(r=re.getAttribute("contentType"))!==null&&r!==void 0?r:mt==null?void 0:mt.split("/")[0],Qs=(o=(n=re.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],_i=re.querySelectorAll("Representation"),Ks=re.querySelector("SegmentTemplate");if(Pi===ge.TEXT){for(const F of _i){const fe=F.getAttribute("id")||"",bt=re.getAttribute("lang"),Ie=(u=(d=(l=F.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Mt=new URL(Ie,e).toString(),Vt=fe.includes("_auto");he[ge.TEXT].push({id:fe,lang:bt,isAuto:Vt,kind:ge.TEXT,url:Mt})}continue}for(const F of _i){const fe=(c=F.getAttribute("mimeType"))!==null&&c!==void 0?c:mt,bt=(f=(h=F.getAttribute("codecs"))!==null&&h!==void 0?h:Ws)!==null&&f!==void 0?f:"",Ie=(m=(p=F.getAttribute("contentType"))!==null&&p!==void 0?p:fe==null?void 0:fe.split("/")[0])!==null&&m!==void 0?m:Pi,Mt=(S=(v=re.getAttribute("profiles"))===null||v===void 0?void 0:v.split(","))!==null&&S!==void 0?S:[],Vt=parseInt((g=F.getAttribute("width"))!==null&&g!==void 0?g:"",10),Di=parseInt((y=F.getAttribute("height"))!==null&&y!==void 0?y:"",10),Ii=parseInt((b=F.getAttribute("bandwidth"))!==null&&b!==void 0?b:"",10)/1e3,Ri=(T=F.getAttribute("frameRate"))!==null&&T!==void 0?T:"",Js=(E=F.getAttribute("quality"))!==null&&E!==void 0?E:void 0,Xs=Ri?js(Ri):void 0,Zs=(A=F.getAttribute("id"))!==null&&A!==void 0?A:(zs++).toString(10),er=Ie==="video"?`${Di}p`:Ie==="audio"?`${Ii}Kbps`:bt,tr=`${Zs}@${er}`,ir=(L=(M=(x=F.querySelector("BaseURL"))===null||x===void 0?void 0:x.textContent)===null||M===void 0?void 0:M.trim())!==null&&L!==void 0?L:"",Ci=new URL(ir,e).toString(),sr=[...Ot,...Qs,...Mt];let Ft;const rr=F.querySelector("SegmentBase"),ye=(B=F.querySelector("SegmentTemplate"))!==null&&B!==void 0?B:Ks;if(rr){const Re=(_=(O=F.querySelector("SegmentBase Initialization"))===null||O===void 0?void 0:O.getAttribute("range"))!==null&&_!==void 0?_:"",[Ce,jt]=Re.split("-").map(Le=>parseInt(Le,10)),Pe={from:Ce,to:jt},Ye=(D=F.querySelector("SegmentBase"))===null||D===void 0?void 0:D.getAttribute("indexRange"),[Ht,gt]=Ye?Ye.split("-").map(Le=>parseInt(Le,10)):[],ze=Ye?{from:Ht,to:gt}:void 0;Ft={type:Ue.BYTE_RANGE,url:Ci,initRange:Pe,indexRange:ze}}else if(ye){const Re={representationId:(V=F.getAttribute("id"))!==null&&V!==void 0?V:void 0,bandwidth:(I=F.getAttribute("bandwidth"))!==null&&I!==void 0?I:void 0},Ce=parseInt((P=ye.getAttribute("timescale"))!==null&&P!==void 0?P:"",10),jt=(N=ye.getAttribute("initialization"))!==null&&N!==void 0?N:"",Pe=ye.getAttribute("media"),Ye=(X=parseInt((G=ye.getAttribute("startNumber"))!==null&&G!==void 0?G:"",10))!==null&&X!==void 0?X:1,Ht=ci(jt,Re);if(!Pe)throw new ReferenceError("No media attribute in SegmentTemplate");const gt=(se=ye.querySelectorAll("SegmentTimeline S"))!==null&&se!==void 0?se:[],ze=[];let Le=0,Gt="",xe=0;if(gt.length){let Ne=Ye,ue=0;for(const qe of gt){const _e=parseInt((ce=qe.getAttribute("d"))!==null&&ce!==void 0?ce:"",10),Ze=parseInt((we=qe.getAttribute("r"))!==null&&we!==void 0?we:"",10)||0,vt=parseInt((Oe=qe.getAttribute("t"))!==null&&Oe!==void 0?Oe:"",10);ue=Number.isFinite(vt)?vt:ue;const Li=_e/Ce*1e3,si=ue/Ce*1e3;for(let ri=0;ri<Ze+1;ri++){const Tl=ci(Pe,{...Re,segmentNumber:Ne.toString(10),segmentTime:(ue+ri*_e).toString(10)}),Ra=(si!=null?si:0)+ri*Li,El=Ra+Li;Ne++,ze.push({time:{from:Ra,to:El},url:Tl})}ue+=(Ze+1)*_e,Le+=(Ze+1)*Li}xe=ue/Ce*1e3,Gt=ci(Pe,{...Re,segmentNumber:Ne.toString(10),segmentTime:ue.toString(10)})}else if(a.isNonNullable(Se)){const ue=parseInt((Y=ye.getAttribute("duration"))!==null&&Y!==void 0?Y:"",10)/Ce*1e3,qe=Math.ceil(Se/ue);let _e=0;for(let Ze=1;Ze<qe;Ze++){const vt=ci(Pe,{...Re,segmentNumber:Ze.toString(10),segmentTime:_e.toString(10)});ze.push({time:{from:_e,to:_e+ue},url:vt}),_e+=ue}xe=_e,Gt=ci(Pe,{...Re,segmentNumber:qe.toString(10),segmentTime:_e.toString(10)})}const Yt={time:{from:xe,to:1/0},url:Gt};Ft={type:Ue.TEMPLATE,baseUrl:Ci,segmentTemplateUrl:Pe,initUrl:Ht,totalSegmentsDurationMs:Le,segments:ze,nextSegmentBeyondManifest:Yt,timescale:Ce}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Ie||!fe)continue;const Ut={video:ge.VIDEO,audio:ge.AUDIO,text:ge.TEXT}[Ie];Ut&&he[Ut].push({id:tr,kind:Ut,segmentReference:Ft,profiles:sr,duration:Se,bitrate:Ii,mime:fe,codecs:bt,width:Vt,height:Di,fps:Xs,quality:Js})}}return{dynamic:It,liveAvailabilityStartTime:ii,duration:Se,container:qs,representations:he}},ng=({id:s,width:e,height:t,bitrate:i,fps:r,quality:n})=>{var o;const l=(o=n?Ei(n):void 0)!==null&&o!==void 0?o:a.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:r}},og=({id:s,bitrate:e})=>({id:s,bitrate:e}),lg=(s,e,t)=>{var i;const r=e.indexOf(t);return(i=pe(s,Math.round(s.length*r/e.length)))!==null&&i!==void 0?i:pe(s,-1)},ug=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),jn=s=>"size"in s,ui=s=>s.type===Ue.TEMPLATE,la=s=>s instanceof DOMException&&(s.name==="AbortError"||s.code===20);class Hn{constructor(e,t,i,r,{fetcher:n,tuning:o,getCurrentPosition:l,isActiveLowLatency:d,compatibilityMode:u=!1,manifest:c}){switch(this.onLastSegment$=new a.ValueSubject(!1),this.fullyBuffered$=new a.ValueSubject(!1),this.playingRepresentation$=new a.ValueSubject(void 0),this.playingRepresentationInit$=new a.ValueSubject(void 0),this.error$=new a.Subject,this.gaps=[],this.subscription=new a.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new je,this.destroyAbortController=new je,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,async function*(h){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 $b(this.sourceBuffer),this.subscription.add(a.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:a.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(a.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:a.ErrorCategory.VIDEO_PIPELINE,message:"SourceBuffer Error event fired"}))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe(S=>{if(!this.sourceBuffer)return;const g=Math.min(this.bufferLimit,Ps(this.sourceBuffer.buffered)*.8);this.bufferLimit=g,this.pruneBuffer(this.getCurrentPosition(),S)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(S=>this.error$.next(S))),yield this.loadInit(f,"high",!0);const p=this.initData.get(f.id),m=this.segments.get(f.id),v=this.parsedInitData.get(f.id);a.assertNonNullable(p,"No init buffer for starting representation"),a.assertNonNullable(m,"No segments for starting representation"),p instanceof ArrayBuffer&&(this.searchGaps(m,f),yield this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(v))}.bind(this)),this.switchTo=a.abortable(this.destroyAbortController.signal,async function*(h){if(h===this.downloadingRepresentationId||h===this.switchingToRepresentationId)return;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 this.loadInit(f,"high",!1):m instanceof Promise&&(yield 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;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=h,this.abort(),yield this.sourceBufferTaskQueue.append(m,this.downloadAbortController.signal);const v=this.getCurrentPosition();a.isNonNullable(v)&&(this.isLive||(p.forEach(S=>S.status=j.NONE),this.pruneBuffer(v,1/0,!0)),this.maintain(v))}.bind(this)),this.seekLive=a.abortable(this.destroyAbortController.signal,async function*(h){var f;if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!h)return;for(const y of this.representations.keys()){const b=h.find(A=>A.id===y);b&&this.representations.set(y,b);const T=this.representations.get(y);if(!T||!ui(T.segmentReference))return;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 v=this.segments.get(p);a.assertNonNullable(v,"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;const g=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),g&&(yield this.sourceBufferTaskQueue.remove(g.from*1e3,g.to*1e3,this.destroyAbortController.signal)),this.searchGaps(v,m),yield this.sourceBufferTaskQueue.append(S,this.destroyAbortController.signal),this.isSeekingLive=!1}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=u,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.isActiveLowLatency=d,this.isLive=!!(c!=null&&c.dynamic),this.container=i,i){case vi.MP4:this.containerParser=Jb;break;case vi.WEBM:this.containerParser=rg;break;default:a.assertNever(i)}this.initData=new Map(r.map(h=>[h.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(r.map(h=>[h.id,h])),this.kind=e,this.mediaSource=t,this.sourceBuffer=null}abort(){for(const e of this.activeSegments)this.abortSegment(e.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new je,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(a.isNullable(e)||a.isNullable(this.downloadingRepresentationId)||a.isNullable(this.playingRepresentationId)||a.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(a.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const r=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=De(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)&&Ps(this.sourceBuffer.buffered)>=this.bufferLimit){const u=De(this.sourceBuffer.buffered,e),c=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;this.pruneBuffer(e,1/0,u<c);return}let l=[];if(!this.activeSegments.size&&(l=this.selectForwardBufferSegments(i,t.segmentReference.type,n),l.length)){let u="auto";if(this.tuning.dash.useFetchPriorityHints&&r)if(l.includes(r))u="high";else{const c=pe(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&&De(this.sourceBuffer.buffered,e)>3e3||this.isActiveLowLatency())&&this.loadNextInit();const d=pe(i,-1);d&&d.status===j.FED&&(this.fullyBuffered$.next(!0),this.isLive||this.onLastSegment$.next(r===d))}searchGaps(e,t){this.gaps=[];let i=0;const r=this.isLive?this.liveInitialAdditionalOffset:0;for(const n of e)Math.trunc(n.time.from-i)>0&&this.gaps.push({representation:t.id,from:i,to:n.time.from+r}),i=n.time.to;a.isNonNullable(t.duration)&&t.duration-i>0&&this.gaps.push({representation:t.id,from:i,to:t.duration})}getActualLiveStartingSegments(e){const t=e.segments,i=this.isActiveLowLatency()?this.tuning.dashCmafLive.lowLatency.maxTargetOffset:this.tuning.dashCmafLive.maxActiveLiveOffset,r=[];let n=0,o=t.length-1;do r.unshift(t[o]),n+=t[o].time.to-t[o].time.from,o--;while(n<i&&o>=0);return this.liveInitialAdditionalOffset=n-i,this.isActiveLowLatency()?[r[0]]:r}getLiveSegmentsToLoadState(e){const t=e==null?void 0:e.representations[this.kind].find(r=>r.id===this.downloadingRepresentationId);if(!t)return;const i=this.segments.get(t.id);if(i!=null&&i.length)return{from:i[0].time.from,to:i[i.length-1].time.to}}updateLive(e){var t,i,r,n;for(const o of(t=e==null?void 0:e.representations[this.kind].values())!==null&&t!==void 0?t:[]){if(!o||!ui(o.segmentReference))return;const l=o.segmentReference.segments.map(h=>({...h,status:j.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(r=pe(d,-1))===null||r===void 0?void 0:r.time.to)!==null&&n!==void 0?n:0,c=l==null?void 0:l.findIndex(h=>Math.floor(u)>=Math.floor(h.time.from)&&Math.floor(u)<=Math.floor(h.time.to));if(c===-1){this.liveUpdateSegmentIndex=0;const h=this.getActualLiveStartingSegments(o.segmentReference);this.segments.set(o.id,h)}else{const h=l.slice(c+1);this.segments.set(o.id,[...d,...h])}}}updateLowLatencyLive(e){var t;if(this.isActiveLowLatency())for(const i of this.representations.values()){const r=i.segmentReference;if(!ui(r))return;const n=Math.round(e.segment.time.to*r.timescale/1e3).toString(10),o=ci(r.segmentTemplateUrl,{segmentTime:n}),l=(t=this.segments.get(i.id))!==null&&t!==void 0?t:[],d=l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.from));d&&(d.time.to=e.segment.time.to),!!l.find(c=>Math.floor(c.time.from)===Math.floor(e.segment.time.to))||l.push({status:j.NONE,time:{from:e.segment.time.to,to:1/0},url:o})}}findSegmentStartTime(e){var t,i,r;const n=(i=(t=this.switchingToRepresentationId)!==null&&t!==void 0?t:this.downloadingRepresentationId)!==null&&i!==void 0?i:this.playingRepresentationId;if(!n)return;const o=this.segments.get(n);if(!o)return;const l=o.find(d=>d.time.from<=e&&d.time.to>=e);return(r=l==null?void 0:l.time.from)!==null&&r!==void 0?r:void 0}setTarget(e){this.forwardBufferTarget=e}setPreloadOnly(e){this.preloadOnly=e}destroy(){var e;if(this.initData.clear(),this.segments.clear(),this.parsedInitData.clear(),this.representations.clear(),(e=this.sourceBufferTaskQueue)===null||e===void 0||e.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer){this.mediaSource.readyState==="open"&&this.abortBuffer();try{this.mediaSource.removeSourceBuffer(this.sourceBuffer)}catch(t){if(!(t instanceof DOMException&&t.name==="NotFoundError"))throw t}}this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){return this.isLive?this.selectForwardBufferSegmentsLive(e,i):this.selectForwardBufferSegmentsRecord(e,t,i)}selectForwardBufferSegmentsLive(e,t){const i=e.findIndex(r=>t>=r.time.from&&t<r.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const r=e.findIndex(({status:h,time:{from:f,to:p}},m)=>{const v=f<=i&&p>=i,S=f>i||v||m===0&&i===0,g=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=i+g||p<=i+g;return(h===j.NONE||h===j.PARTIALLY_EJECTED&&S&&y&&this.sourceBuffer&&!bi(this.sourceBuffer.buffered,i))&&S&&y});if(r===-1)return[];if(t!==Ue.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}async loadSegments(e,t,i="auto"){t.segmentReference.type===Ue.TEMPLATE?await this.loadTemplateSegment(e[0],t,i):await this.loadByteRangeSegments(e,t,i)}async loadTemplateSegment(e,t,i="auto"){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,onProgressTasks:u}=this.prepareTemplateFetchSegmentParams(e,t);this.failedDownloads&&l&&(await a.abortable(l,async function*(){const c=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(h=>setTimeout(h,c))}.bind(this))(),l.aborted&&this.abortActiveSegments([e]));try{const c=await this.fetcher.fetch(o,{range:n,signal:l,onProgress:d,priority:i,isLowLatency:this.isActiveLowLatency()});if(!c)return;const h=new DataView(c);if(this.isActiveLowLatency()){const f=t.segmentReference.timescale;r.segment.time.to=this.containerParser.getSegmentEndTime(h,f)}d&&r.feedingBytes&&u?await Promise.all(u):await this.sourceBufferTaskQueue.append(h,l),r.segment.status=j.DOWNLOADED,this.onSegmentFullyAppended(r,t.id),this.failedDownloads=0}catch(c){if(!la(c))return;this.abortActiveSegments([e]),this.onSegmentDownloadError(c)}}async loadByteRangeSegments(e,t,i="auto"){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&&(await a.abortable(o,async function*(){const d=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(u=>setTimeout(u,d))}.bind(this))(),o.aborted&&this.abortActiveSegments(e));try{await this.fetcher.fetch(n,{range:r,onProgress:l,signal:o,priority:i}),this.failedDownloads=0}catch(d){if(!la(d))return;this.abortActiveSegments(e),this.onSegmentDownloadError(d)}}prepareByteRangeFetchSegmentParams(e,t){if(ui(t.segmentReference))throw new Error("Representation is not byte range type");const i=t.segmentReference.url,r={from:pe(e,0).byte.from,to:pe(e,-1).byte.to},{signal:n}=this.downloadAbortController,o=()=>{this.abort()};return{url:i,range:r,signal:n,onProgress:(d,u)=>{if(!n.aborted)try{this.onSomeByteRangesDataLoaded({dataView:d,loaded:u,signal:n,onSegmentAppendFailed:o,globalFrom:r?r.from:0,representationId:t.id})}catch(c){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:c})}}}}prepareTemplateFetchSegmentParams(e,t){if(!ui(t.segmentReference))throw new Error("Representation is not template type");const i=new URL(e.url,t.segmentReference.baseUrl);this.isActiveLowLatency()&&i.searchParams.set("low-latency","yes");const r=i.toString(),{signal:n}=this.downloadAbortController,o=()=>{this.abort()},l=[],u=this.isActiveLowLatency()||this.tuning.dash.enableSubSegmentBufferFeeding&&this.liveUpdateSegmentIndex<3?(c,h)=>{if(!n.aborted)try{const f=this.onSomeTemplateDataLoaded({dataView:c,loaded:h,signal:n,onSegmentAppendFailed:o,representationId:t.id});l.push(f)}catch(f){this.error$.next({id:"SegmentFeeding",category:a.ErrorCategory.VIDEO_PIPELINE,message:"Error when feeding segments",thrown:f})}}:void 0;return{url:r,signal:n,onProgress:u,onProgressTasks:l}}abortActiveSegments(e){for(const t of this.activeSegments)e.includes(t.segment)&&this.abortSegment(t.segment)}onSegmentDownloadError(e){var t;let i=!1;const r=this.getCurrentPosition();this.sourceBuffer&&a.isNonNullable(r)&&(i=De((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:a.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}async onSomeTemplateDataLoaded({dataView:e,representationId:t,loaded:i,onSegmentAppendFailed:r,signal:n}){if(!(!this.activeSegments.size||!this.representations.get(t)))for(const l of this.activeSegments){const{segment:d}=l;if(l.representationId===t){if(n.aborted){r();continue}if(l.loadedBytes=i,l.loadedBytes>l.feedingBytes){const u=new DataView(e.buffer,e.byteOffset+l.feedingBytes,l.loadedBytes-l.feedingBytes),c=this.containerParser.parseFeedableSegmentChunk(u);c!=null&&c.byteLength&&(d.status=j.PARTIALLY_FED,l.feedingBytes+=c.byteLength,await this.sourceBufferTaskQueue.append(c),l.fedBytes+=c.byteLength)}}}}onSomeByteRangesDataLoaded({dataView:e,representationId:t,globalFrom:i,loaded:r,signal:n,onSegmentAppendFailed:o}){if(!this.activeSegments.size)return;const l=this.representations.get(t);if(!l)return;const d=l.segmentReference.type,u=e.byteLength;for(const c of this.activeSegments){const{segment:h}=c,f=d===Ue.BYTE_RANGE,p=f?h.byte.to-h.byte.from+1:u;if(c.representationId!==t||!(!f||h.byte.from>=i&&h.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const v=f?h.byte.from-i:0,S=f?h.byte.to-i:e.byteLength,g=v<r,y=S<=r;if(h.status===j.DOWNLOADING&&g&&y){h.status=j.DOWNLOADED;const b=new DataView(e.buffer,e.byteOffset+v,p);this.sourceBufferTaskQueue.append(b,n).then(T=>T&&!n.aborted?this.onSegmentFullyAppended(c,t):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(c.loadedBytes=Math.min(p,r-v),c.loadedBytes>c.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+v+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 i;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),e.segment.status=j.FED,jn(e.segment)&&(e.segment.size=e.fedBytes);for(const r of this.representations.values())if(r.id!==t)for(const n of(i=this.segments.get(r.id))!==null&&i!==void 0?i:[])n.status===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 i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[r,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=r)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=As(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const r=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?a.abortable(this.destroyAbortController.signal,async function*(){const l=a.getExponentialDelay(this.failedDownloads,this.tuning.downloadBackoff);yield new Promise(d=>setTimeout(d,l))}.bind(this))():Promise.resolve()).then(()=>this.fetcher.fetchRepresentation(e.segmentReference,this.containerParser,r)).then(async l=>{if(!l)return;const{init:d,dataView:u,segments:c}=l,h=u.buffer.slice(u.byteOffset,u.byteOffset+u.byteLength);this.initData.set(e.id,h);let f=c;this.isLive&&ui(e.segmentReference)&&(f=this.getActualLiveStartingSegments(e.segmentReference)),(!this.isLive||!this.segments.has(e.id))&&this.segments.set(e.id,f),d&&this.parsedInitData.set(e.id,d)}).then(()=>this.failedDownloads=0,l=>{this.initData.set(e.id,null),i&&this.error$.next({id:"LoadInits",category:a.ErrorCategory.WTF,message:"loadInit threw",thrown:l})});return this.initData.set(e.id,o),o}async pruneBuffer(e,t,i=!1){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=jn(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&&i){r=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===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 i of t){let r={representation:e,from:i.time.from,to:i.time.to};for(let n=0;n<this.sourceBuffer.buffered.length;n++){const o=this.sourceBuffer.buffered.start(n)*1e3,l=this.sourceBuffer.buffered.end(n)*1e3;if(!(l<=i.time.from||o>=i.time.to)){if(o<=i.time.from&&l>=i.time.to){r=void 0;break}l>i.time.from&&l<i.time.to&&(r.from=l),o<i.time.to&&o>i.time.from&&(r.to=o)}}r&&r.to-r.from>1&&!this.gaps.some(n=>r&&n.from===r.from&&n.to===r.to)&&this.gaps.push(r)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=As(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:a.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(a.isNullable(this.sourceBuffer)||a.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const r=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:r,to:n})}const t=1;for(const i of this.segments.values())for(const r of i){const{status:n}=r;if(n!==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(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(pi||(pi={}));class dg{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new a.ValueSubject(void 0),this.lastConnectionReused$=new a.ValueSubject(void 0),this.lastRequestFirstBytes$=new a.ValueSubject(void 0),this.abortAllController=new je,this.subscription=new a.Subscription,this.fetchManifest=a.abortable(this.abortAllController.signal,async function*(r){let n=r;this.requestQuic&&(n=Lt(n));const o=yield Jt(n,{signal:this.abortAllController.signal}).catch(Bi);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=a.abortable(this.abortAllController.signal,async function*(r,{rangeMethod:n=this.compatibilityMode?pi.HEADER:pi.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0,isLowLatency:h=!1}={}){var f,p;let m=r;const v=new Headers;if(o)switch(n){case pi.HEADER:{v.append("Range",`bytes=${o.from}-${o.to}`);break}case pi.PARAM:{const D=new URL(m,location.href);D.searchParams.append("bytes",`${o.from}-${o.to}`),m=D.toString();break}default:a.assertNever(n)}this.requestQuic&&(m=Lt(m));let S=this.abortAllController.signal,g;if(u){const D=new je;if(g=a.merge(a.fromEvent(this.abortAllController.signal,"abort"),a.fromEvent(u,"abort")).subscribe(()=>{try{D.abort()}catch(V){Bi(V)}}),this.abortAllController.signal.aborted||u.aborted)try{D.abort()}catch(V){Bi(V)}S=D.signal}const y=a.now(),b=yield Jt(m,{priority:d,headers:v,signal:S}).catch(Bi),T=a.now();if(!b)return g==null||g.unsubscribe(),null;if((f=this.throughputEstimator)===null||f===void 0||f.addRawRtt(T-y),!b.ok||!b.body)return g==null||g.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));if(this.onHeadersReceived(b.headers),!l&&!c)return g==null||g.unsubscribe(),b.arrayBuffer();const[E,A]=b.body.tee(),x=E.getReader();c&&((p=this.throughputEstimator)===null||p===void 0||p.trackStream(A,h));let M=0,L=new Uint8Array(0),B=!1;const O=D=>{g==null||g.unsubscribe(),B=!0,Bi(D)},_=a.abortable(S,async function*({done:D,value:V}){if(M===0&&this.lastRequestFirstBytes$.next(a.now()-y),S.aborted){g==null||g.unsubscribe();return}if(!D&&V){const I=new Uint8Array(L.length+V.length);I.set(L),I.set(V,L.length),L=I,M+=V.byteLength,l==null||l(new DataView(L.buffer),M),yield x==null?void 0:x.read().then(_,O)}}.bind(this));return yield x==null?void 0:x.read().then(_,O),g==null||g.unsubscribe(),B?null:L.buffer}.bind(this)),this.fetchByteRangeRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n,o){var l;if(r.type!==Ue.BYTE_RANGE)return 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 v=yield this.fetch(r.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!v)return null;const S=new DataView(v,d-c,u-c+1);if(!n.validateData(S))throw new Error("Invalid media file");const g=n.parseInit(S),y=(l=r.indexRange)!==null&&l!==void 0?l:n.getIndexRange(g);if(!y)throw new ReferenceError("No way to load representation index");let b;if(f)b=new DataView(v,y.from-c,y.to-y.from+1);else{const E=yield this.fetch(r.url,{range:y,priority:o,measureThroughput:!1});if(!E)return null;b=new DataView(E)}const T=n.parseSegments(b,g,y);return{init:g,dataView:new DataView(v),segments:T}}.bind(this)),this.fetchTemplateRepresentation=a.abortable(this.abortAllController.signal,async function*(r,n){if(r.type!==Ue.TEMPLATE)return null;const o=new URL(r.initUrl,r.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:r.segments.map(u=>({...u,status:j.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Pa(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var r,n;const{type:o}=e;switch(o){case Ue.BYTE_RANGE:return(r=await this.fetchByteRangeRepresentation(e,t,i))!==null&&r!==void 0?r:null;case Ue.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:a.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Bi=s=>{if(!la(s))throw s},ua=1e3,Ls=(s,e,t)=>t*e+(1-t)*s,ml=(s,e)=>s.reduce((t,i)=>t+i,0)/e,cg=(s,e,t,i)=>{let r=0,n=t;const o=ml(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?r++:r--,n=(s.length+n-1)%s.length;return Math.abs(r)===l};class Ia{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new a.ValueSubject(e.initial),this.debounced$=new a.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new st(`raw_${i}`),this.smoothedSeries$=new st(`smoothed_${i}`),this.reportedSeries$=new st(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const r=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*r,o=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(a.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class hg extends Ia{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ls(this.slow,e,this.params.emaAlphaSlow),this.fast=Ls(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class fg extends Ia{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=ml(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ls(this.emaSmoothed,e,this.params.emaAlpha);const i=cg(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class pg extends Ia{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?Ls(this.smoothed,e,this.params.emaAlpha):e}}class da{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new hg({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new fg({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}static getLiveEstimatedDelaySmoothedValue(e,t){return new pg({initial:e,label:"liveEdgeDelay",...t})}}const mg=(s,e)=>{s&&s.playbackRate!==e&&(s.playbackRate=e)},Gn=["timeupdate","progress","play","seeked","stalled","waiting"];var Ve;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(Ve||(Ve={}));let bg=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new a.Subscription,this.representationSubscription=new a.Subscription,this.state$=new J(Ve.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 je,this.initManifest=a.abortable(this.destroyController.signal,async function*(t,i,r){var n;this.element=t,this.manifestUrlString=$e(i,r,ie.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(Ve.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(Ve.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,async function*(){var t;const i=yield this.fetcher.fetchManifest(this.manifestUrlString).catch(o=>{!this.manifest&&!this.bufferLength$.getValue()&&this.error$.next({id:"LoadManifest",category:a.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!i)return null;let r;try{r=ag(i!=null?i:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:a.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!r)return 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===ge.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)),{...r,representations:Kt(Object.entries(r.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=a.abortable(this.destroyController.signal,async function*(t,i){a.assertNonNullable(this.manifest),a.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(Ve.REPRESENTATIOS_READY),window.ManagedMediaSource?(this.source=new ManagedMediaSource,this.element.disableRemotePlayback=!0):this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source),this.isActiveLowLatency=this.isLive$.getValue()&&this.tuning.dashCmafLive.lowLatency.isActive;const r={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,isActiveLowLatency:()=>this.isActiveLowLatency,manifest:this.manifest};if(this.videoBufferManager=new Hn(ge.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,r),this.bufferManagers=[this.videoBufferManager],a.isNonNullable(i)&&(this.audioBufferManager=new Hn(ge.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(ua).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=Es(this.manifestUrlString,ie.DASH_CMAF_OFFSET_P);this.manifestUrlString=$e(this.manifestUrlString,u+ua,ie.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(a.merge(...Gn.map(l=>a.fromEvent(this.element,l))).pipe(a.map(l=>this.element?De(this.element.buffered,this.element.currentTime*1e3):0),a.filterChanged(),a.filter(l=>!!l),a.tap(l=>{this.waitingEventInterval&&(window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=void 0)})).subscribe(this.bufferLength$)),this.isLive$.getValue()){this.representationSubscription.add(this.bufferLength$.pipe(a.filter(d=>this.isActiveLowLatency&&!!d)).subscribe(d=>this.liveEstimatedDelay.next(d))),this.representationSubscription.add(this.liveEstimatedDelay.smoothed$.subscribe(d=>{if(!this.isActiveLowLatency)return;const u=this.tuning.dashCmafLive.lowLatency.maxTargetOffset,c=this.tuning.dashCmafLive.lowLatency.maxTargetOffsetDeviation,h=this.tuning.dashCmafLive.lowLatency.playbackCatchupSpeedup,f=d-u;let p=1+Math.sign(f)*h;Math.abs(f)<c?p=1:Math.abs(f)>c*2&&(p=1+Math.sign(f)*h*2),mg(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 v,S;return(S=(v=m.getLiveSegmentsToLoadState(this.manifest))===null||v===void 0?void 0:v.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(async({liveLoadBufferLength:d,bufferLength:u})=>{if(a.assertNonNullable(this.element),this.isUpdatingLive)return;const c=this.element.playbackRate,h=Es(this.manifestUrlString,ie.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,v=this.tuning.dashCmafLive.normalizedLiveMinBufferSize*c,S=this.isActiveLowLatency?u:d;let g=it.None;if(this.isActiveLowLatency?g=it.ActiveLowLatency:S<p+v&&S>=p?g=it.LiveWithTargetOffset:h!==0&&S<p&&(g=it.LiveForwardBuffering),isFinite(d)&&(l=d>l?d:l),g===it.LiveForwardBuffering||g===it.LiveWithTargetOffset){const y=l-(p+m),b=this.normolizeLiveOffset(Math.trunc(h+y/c)),T=Math.abs(b-h);let E;!d||T<=this.tuning.dashCmafLive.offsetCalculationError?E=h:b>0&&T>this.tuning.dashCmafLive.offsetCalculationError?E=b:E=0,this.manifestUrlString=$e(this.manifestUrlString,E,ie.DASH_CMAF_OFFSET_P)}g!==it.None&&g!==it.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 new Promise(l=>{var d;return(d=this.source)===null||d===void 0?void 0:d.addEventListener("sourceopen",l)})),a.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&a.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(Ve.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const r=this.element.currentTime*1e3;this.videoBufferManager.maintain(r),(t=this.audioBufferManager)===null||t===void 0||t.maintain(r),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=a.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:a.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new dg({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode}),this.liveEstimatedDelay=da.getLiveEstimatedDelaySmoothedValue(0,{...e.tuning.dashCmafLive.lowLatency.delayEstimator})}async seekLive(e){var t,i,r,n;a.assertNonNullable(this.element);const o=this.normolizeLiveOffset(e);this.isActiveLowLatency=this.tuning.dashCmafLive.lowLatency.isActive&&o===0,this.liveLastSeekOffset=o,this.isJumpGapAfterSeekLive=!0,this.manifestUrlString=$e(this.manifestUrlString,o,ie.DASH_CMAF_OFFSET_P),this.manifest=await this.updateManifest(),this.manifest&&(await((t=this.videoBufferManager)===null||t===void 0?void 0:t.seekLive((i=this.manifest)===null||i===void 0?void 0:i.representations.video)),await((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(Ve.RUNNING),this.subscription.add(a.merge(...Gn.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&&bi(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime),this.waitingEventInterval&&window.clearInterval(this.waitingEventInterval),this.waitingEventInterval=window.setInterval(this.waitingEventCallback.bind(this),this.tuning.dashMaxWaitingDuration)})),this.tick()}async switchRepresentation(e,t){const i={[ge.VIDEO]:this.videoBufferManager,[ge.AUDIO]:this.audioBufferManager,[ge.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,r,n,o,l;a.assertNonNullable(this.element),a.assertNonNullable(this.videoBufferManager);let d;t||this.element.duration*1e3<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(this.element.currentTime*1e3-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?d=e:d=Math.max((i=this.videoBufferManager.findSegmentStartTime(e))!==null&&i!==void 0?i:e,(n=(r=this.audioBufferManager)===null||r===void 0?void 0:r.findSegmentStartTime(e))!==null&&n!==void 0?n:e),bi(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(Ve.NONE)}setBufferTarget(e){for(const t of this.bufferManagers)t.setTarget(e)}getRepresentations(){var e;return(e=this.manifest)===null||e===void 0?void 0:e.representations}setPreloadOnly(e){for(const t of this.bufferManagers)t.setPreloadOnly(e)}destroy(){var e;this.subscription.unsubscribe(),this.representationSubscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),window.clearInterval(this.waitingEventInterval),this.stop(),((e=this.source)===null||e===void 0?void 0:e.readyState)==="open"&&Array.from(this.source.sourceBuffers).every(t=>!t.updating)&&this.source.endOfStream(),this.source=null}async waitingEventCallback(){try{if(!this.element)return;this.isLive$.getValue()?await this.seekLive(this.liveLastSeekOffset):this.seek(this.element.currentTime*1e3,!0)}catch(e){this.error$.next({id:"WaitingEventCallback",category:a.ErrorCategory.WTF,message:"Error in seeking in waiting event callback",thrown:e})}}normolizeLiveOffset(e){return Math.trunc(e/1e3)*1e3}async updateLive(){var e;this.isUpdatingLive=!0,this.manifest=await this.updateManifest(),this.manifest&&((e=this.bufferManagers)===null||e===void 0||e.forEach(t=>t.updateLive(this.manifest))),this.isUpdatingLive=!1}jumpGap(){if(!this.element||!this.videoBufferManager)return;const e=this.videoBufferManager.getDebugBufferState();if(!e)return;this.isJumpGapAfterSeekLive&&!this.isActiveLowLatency&&this.element.currentTime>e.to&&(this.isJumpGapAfterSeekLive=!1,this.element.currentTime=0);const t=this.element.currentTime*1e3,i=[];for(const r of this.bufferManagers)for(const n of r.gaps)r.playingRepresentation$.getValue()===n.representation&&n.from<=t&&n.to>t&&(this.element.duration*1e3-n.to<this.tuning.endGapTolerance?i.push(1/0):i.push(n.to));if(i.length){const r=Math.max(...i);r===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):Math.trunc(this.element.currentTime*1e3)!==Math.trunc(r)&&(this.element.currentTime=r/1e3)}}};class bl{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(ne.STOPPED),this.elementSize$=new a.ValueSubject(void 0),this.textTracksManager=new Xe,this.droppedFramesManager=new Qi,this.videoTracks$=new a.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Ko,this.textTracks=[],this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===H.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==ne.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==ne.STOPPED&&(this.videoState.startTransitionTo(ne.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(ne.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case ne.STOPPED:this.videoState.startTransitionTo(ne.READY),this.prepare();return;case ne.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(ne.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ne.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&w(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case ne.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ne.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 ne.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ne.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 i,r,n;if(this.scene3D)return;this.scene3D=new ul(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((r=t.projectionData)===null||r===void 0?void 0:r.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=lt(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(ke(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new bg({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=dt(this.video),r=this.constructor.name,n=l=>{e.error$.next({id:r,category:a.ErrorCategory.WTF,message:`${r} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:r,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(a.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(a.filter(a.isNonNullable),a.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(xt(this.video,t.isLooped,r)),this.subscription.add(ot(this.video,t.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),this.subscription.add(Pt(this.video,t.playbackRate,i.playbackRateState$,r)),n(Hi(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(ne.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},r)).add(i.pause$.subscribe(()=>{this.videoState.setState(ne.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},r)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===ne.PLAYING&&this.playIfAllowed()},r)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===Ve.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const f=this.player.getRepresentations();a.assertNonNullable(f,"Manifest not loaded or empty");const p=Array.from(f.audio).sort((g,y)=>y.bitrate-g.bitrate),m=Array.from(f.video).sort((g,y)=>y.bitrate-g.bitrate),v=Array.from(f.text);if(!this.params.tuning.isAudioDisabled)for(const g of p){const y=og(g);y&&this.audioTracks.push({track:y,representation:g})}for(const g of m){const y=ng(g);if(y){h.push({track:y,representation:g});const b=!this.params.tuning.isAudioDisabled&&lg(p,m,g);b&&this.audioRepresentations.set(g.id,b)}}this.videoTracks$.next(h);for(const g of v){const y=ug(g);y&&this.textTracks.push({track:y,representation:g})}this.params.output.availableVideoTracks$.next(h.map(({track:g})=>g)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:g})=>g)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:g})=>g));const S=this.selectVideoRepresentation();a.assertNonNullable(S),this.player.initRepresentations(S.id,(c=this.audioRepresentations.get(S.id))===null||c===void 0?void 0:c.id)}else u===Ve.REPRESENTATIOS_READY&&(this.videoState.setState(ne.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!==Ve.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(ge.VIDEO,h.id).catch(o);const p=this.audioRepresentations.get(h.id);p&&this.player.switchRepresentation(ge.AUDIO,p.id).catch(o)}},r)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(a.filterChanged(),a.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,r)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(f){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${f}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},r)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(a.map(({to:u})=>u===exports.PlaybackState.READY),a.filterChanged());this.subscription.add(a.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(a.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}selectVideoRepresentation(){var e,t,i,r,n,o,l;const d=this.params.desiredState.autoVideoTrackSwitching.getState(),u=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id,c=(t=this.videoTracks$.getValue().find(({track:{id:y}})=>y===u))===null||t===void 0?void 0:t.track,h=this.params.output.currentVideoTrack$.getValue(),f=De(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),v=Math.max(c&&!d&&(r=(i=this.audioRepresentations.get(c.id))===null||i===void 0?void 0:i.bitrate)!==null&&r!==void 0?r:0,h&&(o=(n=this.audioRepresentations.get(h.id))===null||n===void 0?void 0:n.bitrate)!==null&&o!==void 0?o:0),S=ti(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:v,forwardBufferHealth:m,current:h,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=d?S!=null?S:c:c!=null?c:S;return g&&((l=this.videoTracks$.getValue().find(({track:y})=>y===g))===null||l===void 0?void 0:l.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){_t(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(ne.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),ut(this.video)}}class gg extends bl{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}let vg=class extends dl{constructor(e){super(e),this.liveOffset=new Wi}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(a.combine({interval:a.interval(na),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===ae.PLAYING){const o=e.position$.getValue()+(r-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===ae.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 Sg extends bl{constructor(e){super(e),this.liveOffset=new Wi}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(this.params.output.position$.subscribe(this.player.livePositionFromPlayer$)).add(a.combine({interval:a.interval(ua),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:r})=>{var n;if(this.videoState.getState()===ne.PLAYING&&!this.player.isActiveLowLatency){const o=e.position$.getValue()+(r-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(a.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(a.map(({liveBufferTime:r,liveAvailabilityStartTime:n})=>r&&n?r+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),r=t===exports.PlaybackState.PAUSED&&i===ne.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 tt={};var K;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));const Oi=(s,e)=>new a.Observable(t=>{const i=(r,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class yg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(K.INITIALIZING),this.textTracksManager=new Xe,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(t!==K.INITIALIZING)switch((r==null?void 0:r.to)!==exports.PlaybackState.PAUSED&&n.state===H.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case K.STOPPED:break;case K.READY:case K.PLAYING:case K.PAUSED:this.stop();break;default:a.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case K.STOPPED:this.prepare();break;case K.READY:case K.PLAYING:case K.PAUSED:break;default:a.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case K.PLAYING:break;case K.STOPPED:this.prepare();break;case K.READY:case K.PAUSED:this.playIfAllowed();break;default:a.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case K.PAUSED:break;case K.STOPPED:this.prepare();break;case K.READY:this.videoState.setState(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case K.PLAYING:this.pause();break;default:a.assertNever(t)}break;default:a.assertNever(i)}},this.video=lt(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(ke(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),ut(this.video)}loadHlsJs(){let e=!1;const t=r=>{e||this.params.output.error$.next({id:r==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:a.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:r}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(r=>{e||(tt.Hls=r.default,tt.Events=r.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){a.assertNonNullable(tt.Hls,"hls.js not loaded"),this.hls=new tt.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(K.STOPPED)}subscribe(){a.assertNonNullable(tt.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:a.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},r=dt(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(r.timeUpdate$,t.position$),n(r.durationChange$,t.duration$),n(r.ended$,t.endedEvent$),n(r.looped$,t.loopedEvent$),n(r.error$,t.error$),n(r.isBuffering$,t.isBuffering$),n(r.currentBuffer$,t.currentBuffer$),n(r.loadStart$,t.firstBytesEvent$),n(r.playing$,t.firstFrameEvent$),n(r.canplay$,t.canplay$),n(r.seeked$,t.seekedEvent$),n(r.inPiP$,t.inPiP$),n(r.inFullscreen$,t.inFullscreen$),this.subscription.add(xt(this.video,e.isLooped,i)),this.subscription.add(ot(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Pt(this.video,e.playbackRate,r.playbackRateState$,i)),this.subscription.add(Oi(this.hls,tt.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(K.PLAYING),w(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),w(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===K.READY&&this.videoState.setState(K.READY),this.videoState.getState()===K.PLAYING&&this.playIfAllowed()},i)),n(Oi(this.hls,tt.Events.MANIFEST_PARSED).pipe(a.map(({levels:u})=>u.reduce((c,h)=>{var f,p;const m=h.name||h.height.toString(10),{width:v,height:S}=h,g=(p=Ei((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&p!==void 0?p:a.videoSizeToQuality({width:v,height:S});if(!g)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,b={id:m.toString(),quality:g,bitrate:h.bitrate/1e3,size:{width:v,height:S},fps:y};return this.trackLevels.set(m,{track:b,level:h}),c.push(b),c},[]))),t.availableVideoTracks$),n(Oi(this.hls,tt.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,v="internal";c.push({id:f,url:p,language:m,type:v})}e.internalTextTracks.startTransitionTo(c)}}),n(Oi(this.hls,tt.Events.LEVEL_LOADING).pipe(a.map(({url:u})=>ke(u))),t.hostname$),this.subscription.add(Qe(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Oi(this.hls,tt.Events.LEVEL_SWITCHED).pipe(a.map(({level:u})=>o(this.hls.levels[u])));l.pipe(a.filter(a.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(Qe(e.videoTrack,()=>o(this.hls.levels[this.hls.currentLevel]),u=>{var c;if(a.isNullable(u))return;const h=(c=this.trackLevels.get(u.id))===null||c===void 0?void 0:c.level;if(!h)return;const f=this.hls.levels.indexOf(h),p=this.hls.currentLevel,m=this.hls.levels[p];!m||h.bitrate>m.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{changed$:l,onError:i})),n(r.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=a.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(K.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(K.PLAYING),await _t(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(K.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(K.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(K.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Yn="X-Playback-Duration";var zn=async s=>{var e;const t=await Jt(s),i=await t.text(),r=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return r?parseInt(r,10):t.headers.has(Yn)?parseInt(t.headers.get(Yn),10):void 0};const Tg=s=>{let e=null;if(s.QUALITY&&(e=Ei(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(r=>parseInt(r,10));e=a.videoSizeToQuality({width:t,height:i})}return e!=null?e:null},gl=async(s,e=s)=>{var t,i;const o=(await(await Jt(s)).text()).split(`
|
|
46
|
+
`),l=[],d=[];for(let u=0;u<o.length;u++){const c=o[u],h=c.match(/^#EXT-X-STREAM-INF:(.+)/),f=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!h&&!f)){if(h){const p=Kt(h[1].split(",").map(T=>T.split("="))),m=(t=p.QUALITY)!==null&&t!==void 0?t:`stream-${p.BANDWIDTH}`,v=Tg(p);let S;p.BANDWIDTH&&(S=parseInt(p.BANDWIDTH,10)/1e3||void 0),!S&&p["AVERAGE-BANDWIDTH"]&&(S=parseInt(p["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const g=p["FRAME-RATE"]?parseFloat(p["FRAME-RATE"]):void 0;let y;if(p.RESOLUTION){const[T,E]=p.RESOLUTION.split("x").map(A=>parseInt(A,10));T&&E&&(y={width:T,height:E})}const b=new URL(o[++u],e).toString();v&&l.push({id:m,quality:v,url:b,bandwidth:S,size:y,fps:g})}if(f){const p=Kt(f[1].split(",").map(g=>g.split("=")).map(([g,y])=>[g,y.replace(/^"|"$/g,"")])),m=(i=p.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),v=p.LANGUAGE,S=p.NAME;m&&v&&d.push({type:"internal",id:v,label:S,language:v,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}};var Z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(Z||(Z={}));class Eg{constructor(e){var t;this.subscription=new a.Subscription,this.videoState=new J(Z.STOPPED),this.textTracksManager=new Xe,this.manifests$=new a.ValueSubject([]),this.liveOffset=new Wi,this.manifestStartTime$=new a.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const r=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.autoVideoTrackLimits.getTransition();if(n===exports.PlaybackState.STOPPED){r!==Z.STOPPED&&(this.videoState.startTransitionTo(Z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Z.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(r===Z.STOPPED){this.videoState.startTransitionTo(Z.READY),this.prepare();return}if(l||d||u){const f=this.videoState.getState();this.videoState.setState(Z.CHANGING_MANIFEST),this.videoState.startTransitionTo(f),this.prepare(),u&&this.params.output.autoVideoTrackLimits$.next(u.to),h.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&h.state===H.Requested){this.videoState.startTransitionTo(Z.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(r){case Z.READY:n===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Z.PAUSED),this.liveOffset.pause(),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Z.PLAYING),this.playIfAllowed());return;case Z.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Z.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Z.PAUSED:if(n===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(Z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);else{let f=this.liveOffset.getTotalOffset();f>=this.maxSeekBackTime$.getValue()&&(f=0,this.liveOffset.resetTo(f)),this.liveOffset.resume(),this.params.output.position$.next(-f/1e3),this.prepare()}else(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case Z.CHANGING_MANIFEST:break;default:return a.assertNever(r)}},this.params=e,this.video=lt(e.container),this.params.output.element$.next(this.video),this.masterManifest={id:"master",quality:a.VideoQuality.INVARIANT,url:this.params.source.url},gl($e(this.params.source.url),this.params.source.url).then(({qualityManifests:i})=>{if(i.length===0){this.params.output.error$.next({id:"HlsLiveProviderInternal:partial_metadata",category:a.ErrorCategory.WTF,message:"HlsLiveProvider: there are no qualities in manifest"});return}this.manifests$.next([this.masterManifest,...i])},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ke(this.params.source.url)),this.maxSeekBackTime$=new a.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:a.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},r=dt(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.ended$,e.endedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(Z.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(Z.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Z.READY&&this.videoState.setState(Z.READY),this.videoState.getState()===Z.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(a.filterChanged(),a.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ke(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===H.Requested&&this.seek(l.position)},i)),this.subscription.add(r.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(a.combine({startTime:this.manifestStartTime$.pipe(a.filter(a.isNonNullable)),currentTime:r.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:u,min:c}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[h,f]of[[u,"mq"],[c,"lq"]]){const p=String(parseFloat(h||""));f&&h&&o.searchParams.set(f,p)}}const l=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?ie.DASH_CMAF_OFFSET_P:ie.OFFSET_P,d=$e(o.toString(),this.liveOffset.getTotalOffset(),l);this.video.setAttribute("src",d),this.video.load(),zn(d).then(u=>{var c;if(!a.isNullable(u))this.maxSeekBackTime$.next(u);else{const h=(c=this.params.source.maxSeekBackTime)!==null&&c!==void 0?c:this.maxSeekBackTime$.getValue();if(a.isNullable(h)||!isFinite(h))try{Jt(d).then(f=>f.text()).then(f=>{var p;const m=(p=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(f))===null||p===void 0?void 0:p[1];if(m){const v=new URL(m,d).toString();zn(v).then(S=>{a.isNullable(S)||this.maxSeekBackTime$.next(S)})}})}catch(f){}}})}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(Z.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,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var te;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(te||(te={}));class $g{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(te.STOPPED),this.textTracksManager=new Xe,this.manifests$=new a.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const i=this.videoState.getState(),r=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.autoVideoTrackLimits.getTransition();if(r===exports.PlaybackState.STOPPED){i!==te.STOPPED&&(this.videoState.startTransitionTo(te.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(te.STOPPED),w(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(i===te.STOPPED){this.videoState.startTransitionTo(te.READY),this.prepare();return}if(o||l||d){const h=this.videoState.getState();this.videoState.setState(te.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:f}=this.video;this.prepare(),d&&this.params.output.autoVideoTrackLimits$.next(d.to),c.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:f*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&c.state===H.Requested&&this.seek(c.position),i){case te.READY:r===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):r===exports.PlaybackState.PAUSED?(this.videoState.setState(te.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed());return;case te.PLAYING:r===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(te.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case te.PAUSED:r===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(te.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case te.CHANGING_MANIFEST:break;default:return a.assertNever(i)}},this.params=e,this.video=lt(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(ke(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),gl(this.params.source.url).then(({qualityManifests:t,textTracks:i})=>{this.manifests$.next([this.masterManifest,...t]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(i)},t=>this.params.output.error$.next({id:"ExtractHlsQualities",category:a.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:t})),this.subscribe()}selectManifest(){var e,t,i,r;const{autoVideoTrackSwitching:n,videoTrack:o}=this.params.desiredState,l=n.getState(),d=o.getTransition(),u=(r=(t=(e=d==null?void 0:d.to)===null||e===void 0?void 0:e.id)!==null&&t!==void 0?t:(i=o.getState())===null||i===void 0?void 0:i.id)!==null&&r!==void 0?r:"master",c=this.manifests$.getValue();if(!c.length)return;const h=l?"master":u;return l&&!d&&o.startTransitionTo(this.masterManifest),c.find(f=>f.id===h)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:a.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},r=dt(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(xt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(te.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(te.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===te.READY&&this.videoState.setState(te.READY),this.videoState.getState()===te.PLAYING&&this.playIfAllowed()},i).add(r.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&a.isNonNullable(u.to)){const h=u.to.id;this.params.desiredState.videoTrack.setState(u.to);const f=this.manifests$.getValue().find(p=>p.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ke(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===te.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===H.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(a.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!a.isIOS()||!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(a.merge(a.fromEvent(l,"addtrack"),a.fromEvent(l,"removetrack"),a.fromEvent(l,"change"),a.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<l.length;d++)l[d].mode="hidden"},i))}const o=a.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e,t;const i=this.selectManifest();if(a.isNullable(i))return;const r=this.params.desiredState.autoVideoTrackLimits.getTransition(),n=this.params.desiredState.autoVideoTrackLimits.getState(),o=new URL(i.url);if((r||n)&&i.id===this.masterManifest.id){const{max:l,min:d}=(t=(e=r==null?void 0:r.to)!==null&&e!==void 0?e:n)!==null&&t!==void 0?t:{};for(const[u,c]of[[l,"mq"],[d,"lq"]]){const h=String(parseFloat(u||""));c&&u&&o.searchParams.set(c,h)}}this.video.setAttribute("src",o.toString()),this.video.load()}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(te.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 oe;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(oe||(oe={}));class kg{constructor(e){this.subscription=new a.Subscription,this.videoState=new J(oe.STOPPED),this.trackUrls={},this.textTracksManager=new Xe,this.syncPlayback=()=>{var t,i,r;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==oe.STOPPED&&(this.videoState.startTransitionTo(oe.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(oe.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!==oe.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===oe.STOPPED){this.videoState.startTransitionTo(oe.READY),this.prepare();return}if(c){const{currentTime:f}=this.video;this.prepare(),h.state===H.None&&this.params.desiredState.seekState.setState({state:H.Requested,position:f*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((r=(i=this.trackUrls[c.to.id])===null||i===void 0?void 0:i.track)===null||r===void 0?void 0:r.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===H.Requested&&this.seek(h.position),n){case oe.READY:o===exports.PlaybackState.READY?w(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(oe.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(oe.PLAYING),this.playIfAllowed());return;case oe.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(oe.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case oe.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(oe.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=lt(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],r)=>{const n=r.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:a.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},r=dt(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(r.timeUpdate$,e.position$),n(r.durationChange$,e.duration$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),n(r.loadedMetadata$,e.firstBytesEvent$),n(r.playing$,e.firstFrameEvent$),n(r.canplay$,e.canplay$),n(r.seeked$,e.seekedEvent$),n(r.inPiP$,e.inPiP$),n(r.inFullscreen$,e.inFullscreen$),this.subscription.add(xt(this.video,t.isLooped,i)),this.subscription.add(ot(this.video,t.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Pt(this.video,t.playbackRate,r.playbackRateState$,i)),this.subscription.add(r.playing$.subscribe(()=>{this.videoState.setState(oe.PLAYING),w(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(oe.PAUSED),w(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(r.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===oe.READY&&this.videoState.setState(oe.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()===oe.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=a.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),ut(this.video)}prepare(){var e;const t=(e=this.params.desiredState.videoTrack.getState())===null||e===void 0?void 0:e.id;a.assertNonNullable(t,"MpegProvider: track is not selected");let{url:i}=this.trackUrls[t];a.assertNonNullable(i,`MpegProvider: No url for ${t}`),this.params.tuning.requestQuick&&(i=Lt(i)),this.video.setAttribute("src",i),this.video.load(),this.params.output.hostname$.next(ke(i))}playIfAllowed(){_t(this.video).then(e=>{e||(this.videoState.setState(oe.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,i,r,n;let o,l=e;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const d=(i=Object.values(this.trackUrls).find(h=>!a.isInvariantQuality(h.track.quality)&&a.isLowerOrEqual(h.track.quality,e)))===null||i===void 0?void 0:i.track,u=(r=this.params.desiredState.videoTrack.getState())===null||r===void 0?void 0:r.id,c=(n=this.trackUrls[u!=null?u:"0"])===null||n===void 0?void 0:n.track;if(d&&c&&a.isHigherOrEqual(c.quality,d.quality)&&(o=d),!o){const h=Object.values(this.trackUrls).filter(p=>!a.isInvariantQuality(p.track.quality)&&a.isHigher(p.track.quality,e)),f=h.length;f&&(o=h[f-1].track)}o&&(l=o.quality)}else if(!e){const d=Object.values(this.trackUrls).map(u=>u.track);o=ti(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 qn=["stun:videostun.mycdn.me:80"],wg=1e3,Ag=3,xr=()=>null;class Pg{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=xr,this.externalStopCallback=xr,this.externalErrorCallback=xr,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:qn}]};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=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await 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})}async onPeerConnectionStream(e){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()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),wg)}normalizeOptions(e={}){const t={stunServerList:qn,maxRetryNumber:Ag,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var ee;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(ee||(ee={}));class _g{constructor(e){this.videoState=new J(ee.STOPPED),this.maxSeekBackTime$=new a.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==ee.STOPPED&&(this.videoState.startTransitionTo(ee.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(ee.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===ee.STOPPED){this.videoState.startTransitionTo(ee.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case ee.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(ee.PAUSED),w(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(ee.PLAYING),this.playIfAllowed());return;case ee.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(ee.PAUSED),this.video.pause()):(r==null?void 0:r.to)===exports.PlaybackState.PLAYING&&w(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case ee.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(ee.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=lt(e.container),this.liveStreamClient=new Pg(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),ut(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:a.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};a.merge(this.videoState.stateChangeStarted$.pipe(a.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(a.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const r=dt(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(r.timeUpdate$,e.liveTime$),n(r.ended$,e.endedEvent$),n(r.looped$,e.loopedEvent$),n(r.error$,e.error$),n(r.isBuffering$,e.isBuffering$),n(r.currentBuffer$,e.currentBuffer$),this.subscription.add(r.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(r.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===ee.READY&&this.videoState.setState(ee.READY)},i)).add(r.pause$.subscribe(()=>{this.videoState.setState(ee.PAUSED)},i)).add(r.playing$.subscribe(()=>{this.videoState.setState(ee.PLAYING)},i)).add(r.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(ot(this.video,t.volume,r.volumeState$,i)).add(r.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case ee.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case ee.READY:break;case ee.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case ee.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return a.assertNever(o.to)}},i)).add(a.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,a.observableFrom(["init"])).pipe(a.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(ke(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(ee.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(){_t(this.video).then(e=>{e||(this.videoState.setState(ee.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 Wn{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 Nr,Br,Or,Mr,Vr,Fr,Ur,jr,us,Hr,ds,Gr,cs,Yr,hs,zr,fs,qr,ps,Wr;const vl=a.getCurrentBrowser().device===a.CurrentClientDevice.Android,Ct=document.createElement("video"),Dg='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Ig='video/mp4; codecs="hev1.1.6.L93.B0"',Sl='video/webm; codecs="vp09.00.10.08"',yl='video/webm; codecs="av01.0.00M.08"',Rg='audio/mp4; codecs="mp4a.40.2"',Cg='audio/webm; codecs="opus"',me={mms:!!(window.ManagedMediaSource&&(!((Br=(Nr=window.ManagedSourceBuffer)===null||Nr===void 0?void 0:Nr.prototype)===null||Br===void 0)&&Br.appendBuffer)),mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Mr=(Or=window.SourceBuffer)===null||Or===void 0?void 0:Or.prototype)===null||Mr===void 0)&&Mr.appendBuffer)),hls:!!(!((Vr=Ct.canPlayType)===null||Vr===void 0)&&Vr.call(Ct,"application/x-mpegurl")||!((Fr=Ct.canPlayType)===null||Fr===void 0)&&Fr.call(Ct,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},Be={mp4:!!(!((Ur=Ct.canPlayType)===null||Ur===void 0)&&Ur.call(Ct,"video/mp4")),webm:!!(!((jr=Ct.canPlayType)===null||jr===void 0)&&jr.call(Ct,"video/webm")),cmaf:!0},nt={h264:!!(!((Hr=(us=window.MediaSource||window.ManagedMediaSource)===null||us===void 0?void 0:us.isTypeSupported)===null||Hr===void 0)&&Hr.call(us,Dg)),h265:!!(!((Gr=(ds=window.MediaSource||window.ManagedMediaSource)===null||ds===void 0?void 0:ds.isTypeSupported)===null||Gr===void 0)&&Gr.call(ds,Ig)),vp9:!!(!((Yr=(cs=window.MediaSource||window.ManagedMediaSource)===null||cs===void 0?void 0:cs.isTypeSupported)===null||Yr===void 0)&&Yr.call(cs,Sl)),av1:!!(!((zr=(hs=window.MediaSource||window.ManagedMediaSource)===null||hs===void 0?void 0:hs.isTypeSupported)===null||zr===void 0)&&zr.call(hs,yl)),aac:!!(!((qr=(fs=window.MediaSource||window.ManagedMediaSource)===null||fs===void 0?void 0:fs.isTypeSupported)===null||qr===void 0)&&qr.call(fs,Rg)),opus:!!(!((Wr=(ps=window.MediaSource||window.ManagedMediaSource)===null||ps===void 0?void 0:ps.isTypeSupported)===null||Wr===void 0)&&Wr.call(ps,Cg))},di=(nt.h264||nt.h265)&&nt.aac;var Rt;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(Rt||(Rt={}));var Tt;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Tt||(Tt={}));let zt;const Lg=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:yl}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:Sl}})]);zt={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{Lg()}catch(s){console.error(s)}const Gi=me.hls&&Be.mp4,xg=()=>Object.keys(nt).filter(s=>nt[s]),Ng=(s,e=!1,t=!1)=>s.filter(i=>{switch(i){case exports.VideoFormat.DASH:return me.mse&&Be.mp4&&di;case exports.VideoFormat.DASH_SEP:return(me.mse||me.mms&&t)&&Be.mp4&&di;case exports.VideoFormat.DASH_WEBM:return(me.mse||me.mms&&t)&&Be.webm&&nt.vp9&&nt.opus;case exports.VideoFormat.DASH_WEBM_AV1:return(me.mse||me.mms&&t)&&Be.webm&&nt.av1&&nt.opus;case exports.VideoFormat.DASH_LIVE:return me.mse&&Be.mp4&&di;case exports.VideoFormat.DASH_LIVE_CMAF:return(me.mse||me.mms&&t)&&Be.mp4&&di&&Be.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return(me.mse||me.mms&&t)&&Be.mp4&&di;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return Gi||e&&me.mse&&Be.mp4&&di;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return Gi;case exports.VideoFormat.MPEG:return Be.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return me.webrtc&&me.ws&&nt.h264&&(Be.mp4||Be.webm);default:return a.assertNever(i)}}),Mi=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case Rt.VP9:return[e,t];case Rt.AV1:return[t,e];case Rt.NONE:return[];case Rt.SMOOTH:return zt?zt[t].smooth?[t,e]:zt[e].smooth?[e,t]:[t,e]:[e,t];case Rt.POWER_EFFICIENT:return zt?zt[t].powerEfficient?[t,e]:zt[e].powerEfficient?[e,t]:[t,e]:[e,t];default:a.assertNever(s)}return[e,t]},Bg=({webmCodec:s,androidPreferredFormat:e})=>{if(vl)switch(e){case Tt.MPEG:return[exports.VideoFormat.MPEG,...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case Tt.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case Tt.DASH:return[...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return Gi?[...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Mi(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Og=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],r=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...r],o=[...r,...i];let l;if(vl)switch(s){case Tt.DASH:{l=n;break}case Tt.HLS:case Tt.MPEG:{l=o;break}}else Gi?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},Qn=s=>s?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Mg=s=>new a.Observable(e=>{const t=new a.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(a.map(({from:u,to:c})=>`${u}-${c}`)),r=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(a.map(({type:u})=>u!==void 0)),o=new a.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(r.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Vg={cacheDuration:12e4},Fg={chunkDuration:5e3,maxParallelRequests:5};class Ug{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=Ng([...Og(this.params.tuning),...Bg(this.params.tuning)],this.params.tuning.useHlsJs,this.params.tuning.useManagedMediaSource).filter(l=>a.isNonNullable(e.sources[l])),{forceFormat:i,formatsToAvoid:r}=this.params.tuning;let n=[];i?n=[i]:r.length?n=[...t.filter(l=>!r.includes(l)),...t.filter(l=>r.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Wn(n),console.log("this.params.tuning.useManagedMediaSource "+this.params.tuning.useManagedMediaSource),console.log(n);const o=[...Qn(!0),...Qn(!1)];this.chromecastFormatsIterator=new Wn(o.filter(l=>a.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(console.log("Choose provider "+t),a.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(r){this.providerError$.next({id:"ProviderNotConstructed",category:a.ErrorCategory.WTF,message:"Failed to create provider",thrown:r})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),r=i.state!==H.None;if(this.params.desiredState.seekState.setState({state:H.Requested,position:r?i.position:t,forcePrecise:r?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case Te.SCREEN:return this.createScreenProvider(t);case Te.CHROMECAST:return this.createChromecastProvider(t);default:return a.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:r}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(console.log("Creating provider "+e),e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Up({...o,source:l,config:Vg})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{console.log("Inside CASE DASH_SEP");const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJs?new _n({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?(console.log("WE ARE IN A RIGHT PLACE"),new gg({...o,source:l})):new Eb({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),this.params.tuning.useDashJsCMAF?new _n({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):this.params.tuning.useNewDashVkProvider?new Sg({...o,source:l}):new vg({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),Gi||!this.params.tuning.useHlsJs?new $g({...o,source:l}):new yg({...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 Eg({...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 kg({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new Bp({...o,source:l,config:{...Fg,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return a.assertNonNullable(l),new _g({container:i,source:l,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return a.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:r,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return a.assertNonNullable(l),new zf({connection:l,meta:n,container:i,source:t,format:e,desiredState:r,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?Te.CHROMECAST:Te.SCREEN}chooseFormat(e){switch(e){case Te.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case Te.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return a.assertNever(e)}}skipFormat(e){switch(e){case Te.SCREEN:return this.screenFormatsIterator.next();case Te.CHROMECAST:return this.chromecastFormatsIterator.next();default:return a.assertNever(e)}}handleNoFormatsError(e){switch(e){case Te.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case Te.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return a.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=r=>{const n=new URL(r);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return Kt(Object.entries(e).map(([r,n])=>[r,i(n)]))}initProviderErrorHandling(){const e=new a.Subscription;let t=!1,i=0;const r=a.now();return e.add(a.merge(this.providerOutput.error$,Mg({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(a.map(n=>({id:`ProviderHangup:${n}`,category:a.ErrorCategory.WTF,message:`A ${n} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const n=this.params.desiredState.playbackState.transitionEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>t=!0);e.add(n)})),e.add(this.providerError$.subscribe(n=>{const o=this.current$.getValue().destination;if(o===Te.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(Te.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const l=n.category===a.ErrorCategory.NETWORK,d=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),u=i<this.params.tuning.providerErrorLimit,c=d&&(l&&t||!u),h=n.id.includes("partial_metadata"),f=a.now()-r;c?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):h&&f<=this.params.tuning.providerRefetchManifestMaxTime?this.reinitProvider():u?(i++,this.reinitProvider()):this.switchToNextProvider(o!=null?o:Te.SCREEN)}})),e}}const jg=5e3,Kn="one_video_throughput",Jn="one_video_rtt",Et=window.navigator.connection,Xn=()=>{const s=Et==null?void 0:Et.downlink;if(a.isNonNullable(s)&&s!==10)return s*1e3},Zn=()=>{const s=Et==null?void 0:Et.rtt;if(a.isNonNullable(s)&&s!==3e3)return s},eo=(s,e,t)=>{const i=t*8,r=i/s;return i/(r+e)};class Ui{constructor(e){var t,i;this.subscription=new a.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Ui.load(Kn)||(e.useBrowserEstimation?Xn():void 0)||jg,n=(i=(t=Ui.load(Jn))!==null&&t!==void 0?t:e.useBrowserEstimation?Zn():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new a.ValueSubject(r),this.rtt$=new a.ValueSubject(n),this.rttAdjustedThroughput$=new a.ValueSubject(eo(r,n,e.rttPenaltyRequestSize)),this.throughput=da.getSmoothedValue(r,-1,e),this.rtt=da.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Xn();d&&this.throughput.next(d);const u=Zn();a.isNonNullable(u)&&this.rtt.next(u)};Et&&"onchange"in Et&&this.subscription.add(a.fromEvent(Et,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{a.safeStorage.set(Kn,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{a.safeStorage.set(Jn,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})=>eo(o,l,e.rttPenaltyRequestSize)),a.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=a.now();const r=new a.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(a.fromEvent(e,"progress").pipe(a.once()).subscribe(n=>{t=n.loaded,i=a.now()}));break;case 1:case 0:r.add(a.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=a.now()}));break}r.add(a.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=a.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),r.unsubscribe()}))}trackStream(e,t=!1){const i=e.getReader();if(!i){e.cancel("Could not get reader");return}let r=0,n=a.now(),o=0,l=a.now();const d=c=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${c}`).catch(()=>{})},u=async({done:c,value:h})=>{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());await(i==null?void 0:i.read().then(u,d))}};this.concurrentDownloads.add(e),i==null||i.read().then(u,d)}addRawSpeed(e,t,i=1,r=!1){if(Ui.sanityCheck(e,t,r)){const n=e*8/t;this.throughput.next(n*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t,i=!1){const r=e*8/t;return!(!r||!isFinite(r)||r>1e6||r<30||i&&e<1e4||!i&&e<10*1024||!i&&t<=20)}static load(e){var t;const i=a.safeStorage.get(e);if(a.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const to={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5,lowLatency:{continuesByteSequenceInterval:10}},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:a.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,maxSegmentDurationLeftToSelectNextSegment:3e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},dashCmafLive:{maxActiveLiveOffset:1e4,normalizedTargetMinBufferSize:6e4,normalizedLiveMinBufferSize:5e3,normalizedActualBufferOffset:1e4,offsetCalculationError:3e3,lowLatency:{maxTargetOffset:3e3,maxTargetOffsetDeviation:500,playbackCatchupSpeedup:.05,isActive:!1,delayEstimator:{emaAlpha:.45,changeThreshold:.05,deviationDepth:20,deviationFactor:.5,extremumInterval:5}}},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Rt.VP9,androidPreferredFormat:Tt.MPEG,preferCMAF:!0,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,dashMaxWaitingDuration:5e3,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!1,useNewDashVkProvider:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,useManagedMediaSource:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,providerRefetchManifestMaxTime:1e4,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},Hg=s=>{var e;return{...a.fillWithDefault(s,to),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...to.configName]}};var io=({seekState:s,position$:e})=>a.merge(s.stateChangeEnded$.pipe(a.map(({to:t})=>{var i;return t.state===H.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),a.filter(a.isNonNullable)),e.pipe(a.filter(()=>s.getState().state===H.None))),Gg=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return a.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const Yg=(s,e,t,i)=>{s!==void 0&&e.getState()===void 0&&e.getPrevState()===void 0&&(t==null?void 0:t.getValue().length)===0?t.pipe(a.filter(r=>r.length>0),a.once()).subscribe(r=>{r.find(i)&&e.startTransitionTo(s)}):(s===void 0||t!=null&&t.getValue().find(i))&&e.startTransitionTo(s)};class zg{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 J(exports.PlaybackState.STOPPED),seekState:new J({state:H.None}),volume:new J({volume:1,muted:!1}),videoTrack:new J(void 0),autoVideoTrackSwitching:new J(!0),autoVideoTrackLimits:new J({}),isLooped:new J(!1),playbackRate:new J(1),externalTextTracks:new J([]),internalTextTracks:new J([]),currentTextTrack:new J(void 0),textTrackCuesSettings:new J({}),cameraOrientation:new J({x:0,y:0})},this.info={playbackState$:new a.ValueSubject(exports.PlaybackState.STOPPED),position$:new a.ValueSubject(0),duration$:new a.ValueSubject(1/0),muted$:new a.ValueSubject(!1),volume$:new a.ValueSubject(1),availableQualities$:new a.ValueSubject([]),availableQualitiesFps$:new a.ValueSubject({}),availableAudioTracks$:new a.ValueSubject([]),isAudioAvailable$:new a.ValueSubject(!0),currentQuality$:new a.ValueSubject(void 0),isAutoQualityEnabled$:new a.ValueSubject(!0),autoQualityLimitingAvailable$:new a.ValueSubject(!1),autoQualityLimits$:new a.ValueSubject({}),currentPlaybackRate$:new a.ValueSubject(1),currentBuffer$:new a.ValueSubject({start:0,end:0}),isBuffering$:new a.ValueSubject(!0),isStalled$:new a.ValueSubject(!1),isEnded$:new a.ValueSubject(!1),isLooped$:new a.ValueSubject(!1),isLive$:new a.ValueSubject(void 0),canChangePlaybackSpeed$:new a.ValueSubject(void 0),atLiveEdge$:new a.ValueSubject(void 0),atLiveDurationEdge$:new a.ValueSubject(void 0),liveTime$:new a.ValueSubject(void 0),liveBufferTime$:new a.ValueSubject(void 0),currentFormat$:new a.ValueSubject(void 0),availableTextTracks$:new a.ValueSubject([]),currentTextTrack$:new a.ValueSubject(void 0),throughputEstimation$:new a.ValueSubject(void 0),rttEstimation$:new a.ValueSubject(void 0),videoBitrate$:new a.ValueSubject(void 0),hostname$:new a.ValueSubject(void 0),httpConnectionType$:new a.ValueSubject(void 0),httpConnectionReused$:new a.ValueSubject(void 0),surface$:new a.ValueSubject(exports.Surface.NONE),chromecastState$:new a.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new a.ValueSubject(void 0),intrinsicVideoSize$:new a.ValueSubject(void 0),availableSources$:new a.ValueSubject(void 0),is3DVideo$:new a.ValueSubject(!1)},this.events={inited$:new a.Subject,ready$:new a.Subject,started$:new a.Subject,playing$:new a.Subject,paused$:new a.Subject,stopped$:new a.Subject,willStart$:new a.Subject,willResume$:new a.Subject,willPause$:new a.Subject,willStop$:new a.Subject,willDestruct$:new a.Subject,watchCoverageRecord$:new a.Subject,watchCoverageLive$:new a.Subject,managedError$:new a.Subject,fatalError$:new a.Subject,ended$:new a.Subject,looped$:new a.Subject,seeked$:new a.Subject,willSeek$:new a.Subject,firstBytes$:new a.Subject,firstFrame$:new a.Subject,canplay$:new a.Subject,log$:new a.Subject},this.experimental={element$:new a.ValueSubject(void 0),tuningConfigName$:new a.ValueSubject([]),enableDebugTelemetry$:new a.ValueSubject(!1),dumpTelemetry:bp},this.initLogs(),this.tuning=Hg(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Il({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ui(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,r)=>{const n=Reflect.get(t,i,r);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(f,p)=>{const m=typeof p;return["number","string","boolean"].includes(m)?p:p===null?null:`<${m}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:a.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,r;return this.config=e,this.domContainer=Gg(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Ug({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(r=e.failoverHosts)!==null&&r!==void 0?r:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?a.fromEvent(document,"visibilitychange").pipe(a.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),r=this.info.isLive$.getValue();return e>=i&&!r&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:H.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){a.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();return this.desiredState.videoTrack.getState()===void 0&&this.desiredState.videoTrack.getPrevState()===void 0&&t.length===0?this.providerContainer.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setVideoTrackIdByQuality(i,e)}):t.length>0&&this.setVideoTrackIdByQuality(t,e),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;a.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t;return Yg(e,this.desiredState.currentTextTrack,(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$,i=>i.id===e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const r=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:r.x+n.x,y:r.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){if(!this.providerContainer)return 0;const e=this.providerContainer.providerOutput.element$.getValue();if(a.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===H.None?void 0:t.position;return a.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:r})=>i||r||0,0),height:e.reduce((i,{height:r})=>i||r||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(a.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(a.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(a.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(a.filter(({from:e})=>e===exports.PlaybackState.STOPPED),a.once()).subscribe(()=>{this.initedAt=a.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===H.Requested?this.desiredState.seekState.setState({...o,state:H.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===H.Applying&&(this.desiredState.seekState.setState({state:H.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:io({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(io({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(a.merge(e.providerOutput.endedEvent$.pipe(a.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(a.mapTo(!1))).pipe(a.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(a.map(o=>({id:o?`No${o}`:"NoProviders",category:a.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(a.once(),a.map(o=>o!=null?o:a.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(a.once(),a.map(()=>a.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new a.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new a.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(a.filter(({to:o})=>o===exports.PlaybackState.PLAYING),a.once()).subscribe(()=>i.next(!1)));let r=0;const n=a.merge(e.providerOutput.isBuffering$,t,i).pipe(a.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.getValue();return o&&!l}),a.filterChanged());this.subscription.add(n.subscribe(o=>{o?r=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})),this.subscription.add(a.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(a.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(a.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new a.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(a.filterChanged((i,r)=>i.provider===r.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(a.filter(i=>i.length>0),a.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){var t;let i;const r=(t=this.desiredState.videoTrack.getState())===null||t===void 0?void 0:t.quality;r&&(i=e.find(({quality:n})=>n===r),i||this.setAutoQuality(!0)),i||(i=ti(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(i),this.info.currentQuality$.next(i.quality),this.info.videoBitrate$.next(i.bitrate)}initLogs(){this.subscription.add(a.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(a.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(a.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;a.assertNonNullable(this.providerContainer),a.assertNonNullable(t),mp(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>pp(i)),this.providerContainer.current$.subscribe(({type:i})=>as("provider",i)),t.duration$.subscribe(i=>as("duration",i)),t.availableVideoTracks$.pipe(a.filter(i=>!!i.length),a.once()).subscribe(i=>as("tracks",i)),this.events.fatalError$.subscribe(new st("fatalError")),this.events.managedError$.subscribe(new st("managedError")),t.position$.subscribe(new st("position")),t.currentVideoTrack$.pipe(a.map(i=>i==null?void 0:i.quality)).subscribe(new st("quality")),this.info.currentBuffer$.subscribe(new st("buffer")),t.isBuffering$.subscribe(new st("isBuffering"))].forEach(i=>this.subscription.add(i)),as("codecs",xg())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(r=>{r instanceof DOMException&&r.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:a.ErrorCategory.DOM,message:String(r)})})};this.subscription.add(a.merge(a.fromEvent(document,"visibilitychange"),a.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const r=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);r&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}setVideoTrackIdByQuality(e,t){const i=e.find(r=>r.quality===t);i?this.desiredState.videoTrack.startTransitionTo(i):this.setAutoQuality(!0)}}const qg=`@vkontakte/videoplayer-core@${so}`;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=zg;exports.SDK_VERSION=qg;exports.VERSION=so;
|