@vkontakte/videoplayer-core 2.0.95 → 2.0.96
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +5 -5
- package/es2015.esm.js +5 -5
- package/es2018.cjs.js +5 -5
- package/es2018.esm.js +5 -5
- package/esnext.cjs.js +5 -5
- package/esnext.esm.js +5 -5
- package/evergreen.esm.js +5 -5
- package/package.json +1 -1
package/es2018.cjs.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.96
|
|
3
|
+
* Wed, 13 Dec 2023 12:11:59 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-96/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Co=Object.create;var Ia=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var No=Object.getPrototypeOf,Lo=Object.prototype.hasOwnProperty;var Oo=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of xo(e))!Lo.call(s,a)&&a!==t&&Ia(s,a,{get:()=>e[a],enumerable:!(i=Io(e,a))||i.enumerable});return s};var xa=(s,e,t)=>(t=s!=null?Co(No(s)):{},Oo(e||!s||!s.__esModule?Ia(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Bo=require("lodash/debounce.js");const sn="2.0.95";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 re;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(re||(re={}));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 B;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(B||(B={}));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 Mo=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 Vo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.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 a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Mo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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,a,n;(n=(a=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.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 r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(Fo),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();r.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.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(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,i,a;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Fo=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 r.assertNever(s)}};var is=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ia(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Me=function(s){try{return!!s()}catch(e){return!0}},Uo=Me,Ni=!Uo(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),an=Ni,rn=Function.prototype,js=rn.call,jo=an&&rn.bind.bind(js,js),Ve=an?jo:function(s){return function(){return js.apply(s,arguments)}},nn=Ve,Ho=nn({}.toString),Go=nn("".slice),Li=function(s){return Go(Ho(s),8,-1)},Yo=Ve,qo=Me,zo=Li,ss=Object,Wo=Yo("".split),Qo=qo(function(){return!ss("z").propertyIsEnumerable(0)})?function(s){return zo(s)=="String"?Wo(s,""):ss(s)}:ss,Oi=function(s){return s==null},Ko=Oi,Jo=TypeError,sa=function(s){if(Ko(s))throw Jo("Can't call method on "+s);return s},Xo=Qo,Zo=sa,zt=function(s){return Xo(Zo(s))},_t={},ai=function(s){return s&&s.Math==Math&&s},Ee=ai(typeof globalThis=="object"&&globalThis)||ai(typeof window=="object"&&window)||ai(typeof self=="object"&&self)||ai(typeof is=="object"&&is)||function(){return this}()||is||Function("return this")(),Hs=typeof document=="object"&&document.all,el=typeof Hs=="undefined"&&Hs!==void 0,on={all:Hs,IS_HTMLDDA:el},ln=on,tl=ln.all,ve=ln.IS_HTMLDDA?function(s){return typeof s=="function"||s===tl}:function(s){return typeof s=="function"},il=Ee,sl=ve,Na=il.WeakMap,al=sl(Na)&&/native code/.test(String(Na)),La=ve,un=on,rl=un.all,ot=un.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:La(s)||s===rl}:function(s){return typeof s=="object"?s!==null:La(s)},nl=Me,lt=!nl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Dt={},ol=Ee,Oa=ot,Gs=ol.document,ll=Oa(Gs)&&Oa(Gs.createElement),dn=function(s){return ll?Gs.createElement(s):{}},ul=lt,dl=Me,cl=dn,cn=!ul&&!dl(function(){return Object.defineProperty(cl("div"),"a",{get:function(){return 7}}).a!=7}),hl=lt,pl=Me,hn=hl&&pl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),fl=ot,ml=String,vl=TypeError,ut=function(s){if(fl(s))return s;throw vl(ml(s)+" is not an object")},Sl=Ni,ri=Function.prototype.call,Fe=Sl?ri.bind(ri):function(){return ri.apply(ri,arguments)},aa={},as=aa,rs=Ee,bl=ve,Ba=function(s){return bl(s)?s:void 0},ra=function(s,e){return arguments.length<2?Ba(as[s])||Ba(rs[s]):as[s]&&as[s][e]||rs[s]&&rs[s][e]},gl=Ve,na=gl({}.isPrototypeOf),yl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",pn=Ee,ns=yl,Ma=pn.process,Va=pn.Deno,Fa=Ma&&Ma.versions||Va&&Va.version,Ua=Fa&&Fa.v8,ge,Ai;Ua&&(ge=Ua.split("."),Ai=ge[0]>0&&ge[0]<4?1:+(ge[0]+ge[1]));!Ai&&ns&&(ge=ns.match(/Edge\/(\d+)/),(!ge||ge[1]>=74)&&(ge=ns.match(/Chrome\/(\d+)/),ge&&(Ai=+ge[1])));var Tl=Ai,ja=Tl,El=Me,$l=Ee,kl=$l.String,fn=!!Object.getOwnPropertySymbols&&!El(function(){var s=Symbol();return!kl(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&ja&&ja<41}),Pl=fn,mn=Pl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Al=ra,wl=ve,_l=na,Dl=mn,Rl=Object,vn=Dl?function(s){return typeof s=="symbol"}:function(s){var e=Al("Symbol");return wl(e)&&_l(e.prototype,Rl(s))},Cl=String,oa=function(s){try{return Cl(s)}catch(e){return"Object"}},Il=ve,xl=oa,Nl=TypeError,la=function(s){if(Il(s))return s;throw Nl(xl(s)+" is not a function")},Ll=la,Ol=Oi,Bi=function(s,e){var t=s[e];return Ol(t)?void 0:Ll(t)},os=Fe,ls=ve,us=ot,Bl=TypeError,Ml=function(s,e){var t,i;if(e==="string"&&ls(t=s.toString)&&!us(i=os(t,s))||ls(t=s.valueOf)&&!us(i=os(t,s))||e!=="string"&&ls(t=s.toString)&&!us(i=os(t,s)))return i;throw Bl("Can't convert object to primitive value")},Sn={exports:{}},Ha=Ee,Vl=Object.defineProperty,Fl=function(s,e){try{Vl(Ha,s,{value:e,configurable:!0,writable:!0})}catch(t){Ha[s]=e}return e},Ul=Ee,jl=Fl,Ga="__core-js_shared__",Hl=Ul[Ga]||jl(Ga,{}),bn=Hl,Ya=bn;(Sn.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 gn=Sn.exports,Gl=sa,Yl=Object,Mi=function(s){return Yl(Gl(s))},ql=Ve,zl=Mi,Wl=ql({}.hasOwnProperty),Ue=Object.hasOwn||function(e,t){return Wl(zl(e),t)},Ql=Ve,Kl=0,Jl=Math.random(),Xl=Ql(1 .toString),yn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Xl(++Kl+Jl,36)},Zl=Ee,eu=gn,qa=Ue,tu=yn,iu=fn,su=mn,Tt=Zl.Symbol,ds=eu("wks"),au=su?Tt.for||Tt:Tt&&Tt.withoutSetter||tu,$e=function(s){return qa(ds,s)||(ds[s]=iu&&qa(Tt,s)?Tt[s]:au("Symbol."+s)),ds[s]},ru=Fe,za=ot,Wa=vn,nu=Bi,ou=Ml,lu=$e,uu=TypeError,du=lu("toPrimitive"),cu=function(s,e){if(!za(s)||Wa(s))return s;var t=nu(s,du),i;if(t){if(e===void 0&&(e="default"),i=ru(t,s,e),!za(i)||Wa(i))return i;throw uu("Can't convert object to primitive value")}return e===void 0&&(e="number"),ou(s,e)},hu=cu,pu=vn,ua=function(s){var e=hu(s,"string");return pu(e)?e:e+""},fu=lt,mu=cn,vu=hn,ni=ut,Qa=ua,Su=TypeError,cs=Object.defineProperty,bu=Object.getOwnPropertyDescriptor,hs="enumerable",ps="configurable",fs="writable";Dt.f=fu?vu?function(e,t,i){if(ni(e),t=Qa(t),ni(i),typeof e=="function"&&t==="prototype"&&"value"in i&&fs in i&&!i[fs]){var a=bu(e,t);a&&a[fs]&&(e[t]=i.value,i={configurable:ps in i?i[ps]:a[ps],enumerable:hs in i?i[hs]:a[hs],writable:!1})}return cs(e,t,i)}:cs:function(e,t,i){if(ni(e),t=Qa(t),ni(i),mu)try{return cs(e,t,i)}catch(a){}if("get"in i||"set"in i)throw Su("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Vi=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},gu=lt,yu=Dt,Tu=Vi,Wt=gu?function(s,e,t){return yu.f(s,e,Tu(1,t))}:function(s,e,t){return s[e]=t,s},Eu=gn,$u=yn,Ka=Eu("keys"),da=function(s){return Ka[s]||(Ka[s]=$u(s))},ca={},ku=al,Tn=Ee,Pu=ot,Au=Wt,ms=Ue,vs=bn,wu=da,_u=ca,Ja="Object already initialized",Ys=Tn.TypeError,Du=Tn.WeakMap,wi,Gt,_i,Ru=function(s){return _i(s)?Gt(s):wi(s,{})},Cu=function(s){return function(e){var t;if(!Pu(e)||(t=Gt(e)).type!==s)throw Ys("Incompatible receiver, "+s+" required");return t}};if(ku||vs.state){var Pe=vs.state||(vs.state=new Du);Pe.get=Pe.get,Pe.has=Pe.has,Pe.set=Pe.set,wi=function(s,e){if(Pe.has(s))throw Ys(Ja);return e.facade=s,Pe.set(s,e),e},Gt=function(s){return Pe.get(s)||{}},_i=function(s){return Pe.has(s)}}else{var vt=wu("state");_u[vt]=!0,wi=function(s,e){if(ms(s,vt))throw Ys(Ja);return e.facade=s,Au(s,vt,e),e},Gt=function(s){return ms(s,vt)?s[vt]:{}},_i=function(s){return ms(s,vt)}}var Iu={set:wi,get:Gt,has:_i,enforce:Ru,getterFor:Cu},xu=Ni,En=Function.prototype,Xa=En.apply,Za=En.call,Nu=typeof Reflect=="object"&&Reflect.apply||(xu?Za.bind(Xa):function(){return Za.apply(Xa,arguments)}),Lu=Li,Ou=Ve,$n=function(s){if(Lu(s)==="Function")return Ou(s)},kn={},Pn={},An={}.propertyIsEnumerable,wn=Object.getOwnPropertyDescriptor,Bu=wn&&!An.call({1:2},1);Pn.f=Bu?function(e){var t=wn(this,e);return!!t&&t.enumerable}:An;var Mu=lt,Vu=Fe,Fu=Pn,Uu=Vi,ju=zt,Hu=ua,Gu=Ue,Yu=cn,er=Object.getOwnPropertyDescriptor;kn.f=Mu?er:function(e,t){if(e=ju(e),t=Hu(t),Yu)try{return er(e,t)}catch(i){}if(Gu(e,t))return Uu(!Vu(Fu.f,e,t),e[t])};var qu=Me,zu=ve,Wu=/#|\.prototype\./,Qt=function(s,e){var t=Ku[Qu(s)];return t==Xu?!0:t==Ju?!1:zu(e)?qu(e):!!e},Qu=Qt.normalize=function(s){return String(s).replace(Wu,".").toLowerCase()},Ku=Qt.data={},Ju=Qt.NATIVE="N",Xu=Qt.POLYFILL="P",Zu=Qt,tr=$n,ed=la,td=Ni,id=tr(tr.bind),_n=function(s,e){return ed(s),e===void 0?s:td?id(s,e):function(){return s.apply(e,arguments)}},oi=Ee,sd=Nu,ad=$n,rd=ve,nd=kn.f,od=Zu,St=aa,ld=_n,bt=Wt,ir=Ue,ud=function(s){var e=function(t,i,a){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,a)}return sd(s,this,arguments)};return e.prototype=s.prototype,e},Fi=function(s,e){var t=s.target,i=s.global,a=s.stat,n=s.proto,o=i?oi:a?oi[t]:(oi[t]||{}).prototype,l=i?St:St[t]||bt(St,t,{})[t],d=l.prototype,u,c,h,p,f,m,S,g,E;for(p in e)u=od(i?p:t+(a?".":"#")+p,s.forced),c=!u&&o&&ir(o,p),m=l[p],c&&(s.dontCallGetSet?(E=nd(o,p),S=E&&E.value):S=o[p]),f=c&&S?S:e[p],!(c&&typeof m==typeof f)&&(s.bind&&c?g=ld(f,oi):s.wrap&&c?g=ud(f):n&&rd(f)?g=ad(f):g=f,(s.sham||f&&f.sham||m&&m.sham)&&bt(g,"sham",!0),bt(l,p,g),n&&(h=t+"Prototype",ir(St,h)||bt(St,h,{}),bt(St[h],p,f),s.real&&d&&(u||!d[p])&&bt(d,p,f)))},qs=lt,dd=Ue,Dn=Function.prototype,cd=qs&&Object.getOwnPropertyDescriptor,ha=dd(Dn,"name"),hd=ha&&function(){}.name==="something",pd=ha&&(!qs||qs&&cd(Dn,"name").configurable),fd={EXISTS:ha,PROPER:hd,CONFIGURABLE:pd},Rn={},md=Math.ceil,vd=Math.floor,Sd=Math.trunc||function(e){var t=+e;return(t>0?vd:md)(t)},bd=Sd,pa=function(s){var e=+s;return e!==e||e===0?0:bd(e)},gd=pa,yd=Math.max,Td=Math.min,Ed=function(s,e){var t=gd(s);return t<0?yd(t+e,0):Td(t,e)},$d=pa,kd=Math.min,Pd=function(s){return s>0?kd($d(s),9007199254740991):0},Ad=Pd,fa=function(s){return Ad(s.length)},wd=zt,_d=Ed,Dd=fa,sr=function(s){return function(e,t,i){var a=wd(e),n=Dd(a),o=_d(i,n),l;if(s&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in a)&&a[o]===t)return s||o||0;return!s&&-1}},Rd={includes:sr(!0),indexOf:sr(!1)},Cd=Ve,Ss=Ue,Id=zt,xd=Rd.indexOf,Nd=ca,ar=Cd([].push),Ld=function(s,e){var t=Id(s),i=0,a=[],n;for(n in t)!Ss(Nd,n)&&Ss(t,n)&&ar(a,n);for(;e.length>i;)Ss(t,n=e[i++])&&(~xd(a,n)||ar(a,n));return a},Cn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Od=Ld,Bd=Cn,Md=Object.keys||function(e){return Od(e,Bd)},Vd=lt,Fd=hn,Ud=Dt,jd=ut,Hd=zt,Gd=Md;Rn.f=Vd&&!Fd?Object.defineProperties:function(e,t){jd(e);for(var i=Hd(t),a=Gd(t),n=a.length,o=0,l;n>o;)Ud.f(e,l=a[o++],i[l]);return e};var Yd=ra,qd=Yd("document","documentElement"),zd=ut,Wd=Rn,rr=Cn,Qd=ca,Kd=qd,Jd=dn,Xd=da,nr=">",or="<",zs="prototype",Ws="script",In=Xd("IE_PROTO"),bs=function(){},xn=function(s){return or+Ws+nr+s+or+"/"+Ws+nr},lr=function(s){s.write(xn("")),s.close();var e=s.parentWindow.Object;return s=null,e},Zd=function(){var s=Jd("iframe"),e="java"+Ws+":",t;return s.style.display="none",Kd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(xn("document.F=Object")),t.close(),t.F},li,Ei=function(){try{li=new ActiveXObject("htmlfile")}catch(e){}Ei=typeof document!="undefined"?document.domain&&li?lr(li):Zd():lr(li);for(var s=rr.length;s--;)delete Ei[zs][rr[s]];return Ei()};Qd[In]=!0;var Nn=Object.create||function(e,t){var i;return e!==null?(bs[zs]=zd(e),i=new bs,bs[zs]=null,i[In]=e):i=Ei(),t===void 0?i:Wd.f(i,t)},ec=Me,tc=!ec(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),ic=Ue,sc=ve,ac=Mi,rc=da,nc=tc,ur=rc("IE_PROTO"),Qs=Object,oc=Qs.prototype,Ln=nc?Qs.getPrototypeOf:function(s){var e=ac(s);if(ic(e,ur))return e[ur];var t=e.constructor;return sc(t)&&e instanceof t?t.prototype:e instanceof Qs?oc:null},lc=Wt,On=function(s,e,t,i){return i&&i.enumerable?s[e]=t:lc(s,e,t),s},uc=Me,dc=ve,cc=ot,hc=Nn,dr=Ln,pc=On,fc=$e,Ks=fc("iterator"),Bn=!1,Le,gs,ys;[].keys&&(ys=[].keys(),"next"in ys?(gs=dr(dr(ys)),gs!==Object.prototype&&(Le=gs)):Bn=!0);var mc=!cc(Le)||uc(function(){var s={};return Le[Ks].call(s)!==s});mc?Le={}:Le=hc(Le);dc(Le[Ks])||pc(Le,Ks,function(){return this});var Mn={IteratorPrototype:Le,BUGGY_SAFARI_ITERATORS:Bn},vc=$e,Sc=vc("toStringTag"),Vn={};Vn[Sc]="z";var ma=String(Vn)==="[object z]",bc=ma,gc=ve,$i=Li,yc=$e,Tc=yc("toStringTag"),Ec=Object,$c=$i(function(){return arguments}())=="Arguments",kc=function(s,e){try{return s[e]}catch(t){}},Ui=bc?$i:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=kc(e=Ec(s),Tc))=="string"?t:$c?$i(e):(i=$i(e))=="Object"&&gc(e.callee)?"Arguments":i},Pc=ma,Ac=Ui,wc=Pc?{}.toString:function(){return"[object "+Ac(this)+"]"},_c=ma,Dc=Dt.f,Rc=Wt,Cc=Ue,Ic=wc,xc=$e,cr=xc("toStringTag"),Fn=function(s,e,t,i){if(s){var a=t?s:s.prototype;Cc(a,cr)||Dc(a,cr,{configurable:!0,value:e}),i&&!_c&&Rc(a,"toString",Ic)}},Nc=Mn.IteratorPrototype,Lc=Nn,Oc=Vi,Bc=Fn,Mc=_t,Vc=function(){return this},Fc=function(s,e,t,i){var a=e+" Iterator";return s.prototype=Lc(Nc,{next:Oc(+!i,t)}),Bc(s,a,!1,!0),Mc[a]=Vc,s},Uc=Fi,jc=Fe,Un=fd,Hc=Fc,Gc=Ln,Yc=Fn,hr=On,qc=$e,pr=_t,jn=Mn,zc=Un.PROPER;Un.CONFIGURABLE;jn.IteratorPrototype;var ui=jn.BUGGY_SAFARI_ITERATORS,Ts=qc("iterator"),fr="keys",di="values",mr="entries",Wc=function(){return this},Qc=function(s,e,t,i,a,n,o){Hc(t,e,i);var l=function(E){if(E===a&&p)return p;if(!ui&&E in c)return c[E];switch(E){case fr:return function(){return new t(this,E)};case di:return function(){return new t(this,E)};case mr:return function(){return new t(this,E)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[Ts]||c["@@iterator"]||a&&c[a],p=!ui&&h||l(a),f=e=="Array"&&c.entries||h,m,S,g;if(f&&(m=Gc(f.call(new s)),m!==Object.prototype&&m.next&&(Yc(m,d,!0,!0),pr[d]=Wc)),zc&&a==di&&h&&h.name!==di&&(u=!0,p=function(){return jc(h,this)}),a)if(S={values:l(di),keys:n?p:l(fr),entries:l(mr)},o)for(g in S)(ui||u||!(g in c))&&hr(c,g,S[g]);else Uc({target:e,proto:!0,forced:ui||u},S);return o&&c[Ts]!==p&&hr(c,Ts,p,{name:a}),pr[e]=p,S},Kc=function(s,e){return{value:s,done:e}},Jc=zt,vr=_t,Hn=Iu;Dt.f;var Xc=Qc,ci=Kc,Gn="Array Iterator",Zc=Hn.set,eh=Hn.getterFor(Gn);Xc(Array,"Array",function(s,e){Zc(this,{type:Gn,target:Jc(s),index:0,kind:e})},function(){var s=eh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ci(void 0,!0)):t=="keys"?ci(i,!1):t=="values"?ci(e[i],!1):ci([i,e[i]],!1)},"values");vr.Arguments=vr.Array;var th=$e,ih=_t,sh=th("iterator"),ah=Array.prototype,rh=function(s){return s!==void 0&&(ih.Array===s||ah[sh]===s)},nh=Ui,Sr=Bi,oh=Oi,lh=_t,uh=$e,dh=uh("iterator"),Yn=function(s){if(!oh(s))return Sr(s,dh)||Sr(s,"@@iterator")||lh[nh(s)]},ch=Fe,hh=la,ph=ut,fh=oa,mh=Yn,vh=TypeError,Sh=function(s,e){var t=arguments.length<2?mh(s):e;if(hh(t))return ph(ch(t,s));throw vh(fh(s)+" is not iterable")},bh=Fe,br=ut,gh=Bi,yh=function(s,e,t){var i,a;br(s);try{if(i=gh(s,"return"),!i){if(e==="throw")throw t;return t}i=bh(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return br(i),t},Th=_n,Eh=Fe,$h=ut,kh=oa,Ph=rh,Ah=fa,gr=na,wh=Sh,_h=Yn,yr=yh,Dh=TypeError,ki=function(s,e){this.stopped=s,this.result=e},Tr=ki.prototype,Rh=function(s,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=Th(e,i),u,c,h,p,f,m,S,g=function(y){return u&&yr(u,"normal",y),new ki(!0,y)},E=function(y){return a?($h(y),l?d(y[0],y[1],g):d(y[0],y[1])):l?d(y,g):d(y)};if(n)u=s.iterator;else if(o)u=s;else{if(c=_h(s),!c)throw Dh(kh(s)+" is not iterable");if(Ph(c)){for(h=0,p=Ah(s);p>h;h++)if(f=E(s[h]),f&&gr(Tr,f))return f;return new ki(!1)}u=wh(s,c)}for(m=n?s.next:u.next;!(S=Eh(m,u)).done;){try{f=E(S.value)}catch(y){yr(u,"throw",y)}if(typeof f=="object"&&f&&gr(Tr,f))return f}return new ki(!1)},Ch=ua,Ih=Dt,xh=Vi,Nh=function(s,e,t){var i=Ch(e);i in s?Ih.f(s,i,xh(0,t)):s[i]=t},Lh=Fi,Oh=Rh,Bh=Nh;Lh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Oh(e,function(i,a){Bh(t,i,a)},{AS_ENTRIES:!0}),t}});var Mh=aa,Vh=Mh.Object.fromEntries,Fh={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},Uh=Fh,jh=Ee,Hh=Ui,Gh=Wt,Er=_t,Yh=$e,$r=Yh("toStringTag");for(var Es in Uh){var kr=jh[Es],$s=kr&&kr.prototype;$s&&Hh($s)!==$r&&Gh($s,$r,Es),Er[Es]=Er.Array}var qh=Vh,zh=qh,Wh=zh,Qh=Wh,kt=ia(Qh),se;(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"})(se||(se={}));var ye=(s,e=0,t=se.OFFSET_P)=>{switch(t){case se.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case se.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case se.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s};const Pr=(s,e)=>{var t;switch(e){case se.OFFSET_P:return NaN;case se.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:r.assertNever(e)}};var P=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class K{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.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||r.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 Kh=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 r.assertNever(s)}};var L;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(L||(L={}));const Jh=5,Xh=5,Zh=500,Ar=7e3;class ep{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new K(L.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),a=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(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&i!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}default:r.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(Kh(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 r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Zh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===B.Applying||Math.abs(l-n)>Jh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.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<Xh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),P(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:B.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)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,i;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(i=e.muted)!==null&&i!==void 0?i:a.muted};(n.volume!==a.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 a,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];r.assertNonNullable(c);const h=r.getHighestQuality(Object.keys(c));r.assertNonNullable(h);const p=c[h];r.assertNonNullable(p),a=p,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];r.assertNonNullable(c),a=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];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=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];r.assertNonNullable(c),a=ye(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:r.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 r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return r.isNonNullable(d)&&(l.metadata.title=d),r.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===B.Applying||i.state===B.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((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(Ar).subscribe(()=>n(`timeout(${Ar})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var tp=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},ip=s=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),a=new r.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,p,f,m,S;const g=kt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),b=parseInt((p=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&p!==void 0?p:"",10),T=(f=b!=null?b:v*1e3)!==null&&f!==void 0?f:NaN;r.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const E=(m=g["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(S={1:!0,0:!1}[g["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(E),a.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(p){if(p.request.type==="MPD"){const f=p.onload,m=p.progress;p.onload=function(...S){return d(this),f(...S)},p.progress=function(...S){return u(this),m(...S)},l()}return h(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},Pt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},sp=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Pt}),!0),ap=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Te=(s,e,t,{equal:i=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=s.getState(),l=e(),d=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.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},dt=(s,e,t)=>Te(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),je=(s,e,t,i)=>Te(e,()=>({muted:s.muted,volume:s.volume}),a=>{r.isNonNullable(a)&&(s.muted=a.muted,s.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),Xe=(s,e,t,i)=>Te(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),rp=s=>["__",s.language,s.label].join("|"),np=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class Ce{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.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(Te(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(Te(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(Te(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:a})),this.subscription.add(Te(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>{var a,n;return this.applyCueSettings((n=(a=i.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)===null||a===void 0||a.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,p;const f=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;f&&f.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(p=l.target)===null||p===void 0||p.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{var a;(a=i.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ce.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:a,label:n}=e,o=e.id?e.id:rp(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:a,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:a,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:a,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===a&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!np(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){r.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){r.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 va=s=>{s.removeAttribute("src"),s.load()},op=s=>{try{s.pause(),s.playbackRate=0,va(s),s.remove()}catch(e){console.error(e)}};class lp{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 Js=window.WeakMap?new WeakMap:new lp,He=s=>{let e=s.querySelector("video");const t=!!e;return e?va(e):(e=document.createElement("video"),s.appendChild(e)),Js.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ge=s=>{const e=Js.get(s);Js.delete(s),e?va(s):op(s)};class ji{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 qn=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},wr=s=>{const e=qn(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},up=s=>{const e=qn(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Xs=3;class dp{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 a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Xs&&(a=e),this._buffer.push({from:a,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||Xs))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:a,to:n})=>{const o=a>=e&&a<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var zn=(s,e,t=Xs)=>{let i=0,a=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,a=l,!t)return{from:i,to:a};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<=a&&(a=s.end(d))}}return{from:i,to:a}};const Ye=s=>{const e=v=>r.fromEvent(s,v).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(v=>r.fromEvent(s,v))).pipe(r.map(v=>v.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>zn(s.buffered,s.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),l=r.fromEvent(s,"volumechange").pipe(r.map(()=>({muted:s.muted,volume:s.volume}))),d=r.fromEvent(s,"ratechange").pipe(r.map(()=>s.playbackRate)),u=r.fromEvent(s,"error").pipe(r.filter(()=>!!(s.error||s.played.length)),r.map(()=>{var v;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),c=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),h=new r.Subject,p=.3;let f;c.subscribe(v=>{s.loop&&r.isNonNullable(f)&&r.isNonNullable(v)&&f>=s.duration-p&&v<=p&&h.next(f),f=v});const m=r.fromEvent(s,"enterpictureinpicture"),S=r.fromEvent(s,"leavepictureinpicture"),g=new r.ValueSubject(up(s));m.subscribe(()=>g.next(!0)),S.subscribe(()=>g.next(!1));const E=new r.ValueSubject(wr(s));return r.fromEvent(s,"fullscreenchange").pipe(r.map(()=>wr(s))).subscribe(E),{playing$:o,pause$:e("pause").pipe(r.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$:r.fromEvent(s,"durationchange").pipe(r.map(()=>s.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:l,playbackRateState$:d,inPiP$:g,inFullscreen$:E}},Sa=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var cp=Fi,hp=Mi,pp=fa,fp=pa;cp({target:"Array",proto:!0},{at:function(e){var t=hp(this),i=pp(t),a=fp(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var mp=ra,Wn=mp,vp=Wn,Sp=vp("Array","at"),bp=Sp,gp=bp,yp=gp,Tp=yp,we=ia(Tp);let ba=!1,Ne={};const Ep=s=>{ba=s},$p=()=>{Ne={}},kp=s=>{s(Ne)},hi=(s,e)=>{var t;ba&&(Ne.meta=(t=Ne.meta)!==null&&t!==void 0?t:{},Ne.meta[s]=e)};class _e{constructor(e){this.name=e}next(e){var t,i;if(!ba)return;Ne.series=(t=Ne.series)!==null&&t!==void 0?t:{};const a=(i=Ne.series[this.name])!==null&&i!==void 0?i:[];a.push([Date.now(),e]),Ne.series[this.name]=a}}var rt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(rt||(rt={}));const Pp=new _e("best_bitrate"),Ap=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class wp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Rt=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var p,f,m,S,g;const E=i.usePixelRatio&&(p=window.devicePixelRatio)!==null&&p!==void 0?p:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*E*i.containerSizeFactor,height:e.height*E*i.containerSizeFactor},v=y&&r.videoSizeToQuality(y),b=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,T=s.filter(C=>!r.isInvariantQuality(C.quality)).sort((C,A)=>r.isHigher(C.quality,A.quality)?-1:1),k=(f=we(T,-1))===null||f===void 0?void 0:f.quality,N=(m=we(T,0))===null||m===void 0?void 0:m.quality,U=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&r.isLower(a.max,a.min)||r.isNonNullable(a.min)&&N&&r.isHigher(a.min,N)||r.isNonNullable(a.max)&&k&&r.isLower(a.max,k),R=b*Ap(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},_=T.filter(C=>(v?r.isLower(C.quality,v):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(C.bitrate)?t-n>=C.bitrate*R:!0)?i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!r.isInvariantQuality(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&r.isHigher(C.quality,d.quality)?(x[C.quality]=rt.Buffer,!1):!!c&&r.isHigherOrEqual(C.quality,c)?(x[C.quality]=rt.DroppedFramesLimit,!1):U||(r.isNullable(a.max)||r.isLowerOrEqual(C.quality,a.max))&&(r.isNullable(a.min)||r.isHigherOrEqual(C.quality,a.min))?!0:(x[C.quality]=rt.FitsQualityLimits,!1):(x[C.quality]=rt.FitsThroughput,!1):(x[C.quality]=rt.FitsContainer,!1))[0];_&&_.bitrate&&Pp.next(_.bitrate);const I=(S=_!=null?_:T[Math.ceil((T.length-1)/2)])!==null&&S!==void 0?S:s[0];I.quality!==((g=u==null?void 0:u.last)===null||g===void 0?void 0:g.quality)&&h({message:`
|
|
6
|
+
"use strict";var Co=Object.create;var Ia=Object.defineProperty;var Io=Object.getOwnPropertyDescriptor;var xo=Object.getOwnPropertyNames;var No=Object.getPrototypeOf,Lo=Object.prototype.hasOwnProperty;var Oo=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of xo(e))!Lo.call(s,a)&&a!==t&&Ia(s,a,{get:()=>e[a],enumerable:!(i=Io(e,a))||i.enumerable});return s};var xa=(s,e,t)=>(t=s!=null?Co(No(s)):{},Oo(e||!s||!s.__esModule?Ia(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Bo=require("lodash/debounce.js");const sn="2.0.96";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 re;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(re||(re={}));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 B;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(B||(B={}));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 Mo=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 Vo{constructor(e){var t;this.connection$=new r.ValueSubject(void 0),this.castState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new r.Subject,this.realCastState$=new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new r.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 a=r.isNonNullable((t=window.chrome)===null||t===void 0?void 0:t.cast),n=!!window.__onGCastApiAvailable;a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||Mo("https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1").catch(()=>this.errorEvent$.next({id:"ChromecastLoading",category:r.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,a,n;(n=(a=(i=cast.framework.CastContext.getInstance())===null||i===void 0?void 0:i.getCurrentSession())===null||a===void 0?void 0:a.getMediaSession())===null||n===void 0||n.stop(new chrome.cast.media.StopRequest,e,t)})}toggleConnection(){r.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const t=this.connection$.getValue();r.isNullable(t)||(t.remotePlayer.volumeLevel=e,t.remotePlayerController.setVolumeLevel())}setMuted(e){const t=this.connection$.getValue();r.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(r.fromEvent(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe(a=>{var n,o;switch(a.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 r.assertNever(a.sessionState)}})).add(r.merge(r.fromEvent(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(r.tap(a=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(a)}`})}),r.map(a=>a.castState)),r.observableFrom([i.getCastState()])).pipe(r.filterChanged(),r.map(Fo),r.tap(a=>{this.log({message:`realCastState$: ${a}`})})).subscribe(this.realCastState$)).add(this.realCastState$.subscribe(a=>{var n;const o=a===exports.ChromecastState.CONNECTED,l=r.isNonNullable(this.connection$.getValue());if(o&&!l){const d=i.getCurrentSession();r.assertNonNullable(d);const u=d.getCastDevice(),c=(n=d.getMediaSession())===null||n===void 0?void 0:n.media.contentId;(r.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(a===exports.ChromecastState.CONNECTED?r.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:a)}))}initializeCastApi(){var e;let t,i,a;try{t=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,a=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(n){return}try{t.setOptions({receiverApplicationId:(e=this.params.receiverApplicationId)!==null&&e!==void 0?e:i,autoJoinPolicy:a}),this.initListeners()}catch(n){this.errorEvent$.next({id:"ChromecastInitializer",category:r.ErrorCategory.EXTERNAL_API,message:"[initializeCastApi] failed",thrown:n})}}}const Fo=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 r.assertNever(s)}};var is=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ia(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Me=function(s){try{return!!s()}catch(e){return!0}},Uo=Me,Ni=!Uo(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),an=Ni,rn=Function.prototype,js=rn.call,jo=an&&rn.bind.bind(js,js),Ve=an?jo:function(s){return function(){return js.apply(s,arguments)}},nn=Ve,Ho=nn({}.toString),Go=nn("".slice),Li=function(s){return Go(Ho(s),8,-1)},Yo=Ve,qo=Me,zo=Li,ss=Object,Wo=Yo("".split),Qo=qo(function(){return!ss("z").propertyIsEnumerable(0)})?function(s){return zo(s)=="String"?Wo(s,""):ss(s)}:ss,Oi=function(s){return s==null},Ko=Oi,Jo=TypeError,sa=function(s){if(Ko(s))throw Jo("Can't call method on "+s);return s},Xo=Qo,Zo=sa,zt=function(s){return Xo(Zo(s))},_t={},ai=function(s){return s&&s.Math==Math&&s},Ee=ai(typeof globalThis=="object"&&globalThis)||ai(typeof window=="object"&&window)||ai(typeof self=="object"&&self)||ai(typeof is=="object"&&is)||function(){return this}()||is||Function("return this")(),Hs=typeof document=="object"&&document.all,el=typeof Hs=="undefined"&&Hs!==void 0,on={all:Hs,IS_HTMLDDA:el},ln=on,tl=ln.all,ve=ln.IS_HTMLDDA?function(s){return typeof s=="function"||s===tl}:function(s){return typeof s=="function"},il=Ee,sl=ve,Na=il.WeakMap,al=sl(Na)&&/native code/.test(String(Na)),La=ve,un=on,rl=un.all,ot=un.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:La(s)||s===rl}:function(s){return typeof s=="object"?s!==null:La(s)},nl=Me,lt=!nl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Dt={},ol=Ee,Oa=ot,Gs=ol.document,ll=Oa(Gs)&&Oa(Gs.createElement),dn=function(s){return ll?Gs.createElement(s):{}},ul=lt,dl=Me,cl=dn,cn=!ul&&!dl(function(){return Object.defineProperty(cl("div"),"a",{get:function(){return 7}}).a!=7}),hl=lt,pl=Me,hn=hl&&pl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),fl=ot,ml=String,vl=TypeError,ut=function(s){if(fl(s))return s;throw vl(ml(s)+" is not an object")},Sl=Ni,ri=Function.prototype.call,Fe=Sl?ri.bind(ri):function(){return ri.apply(ri,arguments)},aa={},as=aa,rs=Ee,bl=ve,Ba=function(s){return bl(s)?s:void 0},ra=function(s,e){return arguments.length<2?Ba(as[s])||Ba(rs[s]):as[s]&&as[s][e]||rs[s]&&rs[s][e]},gl=Ve,na=gl({}.isPrototypeOf),yl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",pn=Ee,ns=yl,Ma=pn.process,Va=pn.Deno,Fa=Ma&&Ma.versions||Va&&Va.version,Ua=Fa&&Fa.v8,ge,Ai;Ua&&(ge=Ua.split("."),Ai=ge[0]>0&&ge[0]<4?1:+(ge[0]+ge[1]));!Ai&&ns&&(ge=ns.match(/Edge\/(\d+)/),(!ge||ge[1]>=74)&&(ge=ns.match(/Chrome\/(\d+)/),ge&&(Ai=+ge[1])));var Tl=Ai,ja=Tl,El=Me,$l=Ee,kl=$l.String,fn=!!Object.getOwnPropertySymbols&&!El(function(){var s=Symbol();return!kl(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&ja&&ja<41}),Pl=fn,mn=Pl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Al=ra,wl=ve,_l=na,Dl=mn,Rl=Object,vn=Dl?function(s){return typeof s=="symbol"}:function(s){var e=Al("Symbol");return wl(e)&&_l(e.prototype,Rl(s))},Cl=String,oa=function(s){try{return Cl(s)}catch(e){return"Object"}},Il=ve,xl=oa,Nl=TypeError,la=function(s){if(Il(s))return s;throw Nl(xl(s)+" is not a function")},Ll=la,Ol=Oi,Bi=function(s,e){var t=s[e];return Ol(t)?void 0:Ll(t)},os=Fe,ls=ve,us=ot,Bl=TypeError,Ml=function(s,e){var t,i;if(e==="string"&&ls(t=s.toString)&&!us(i=os(t,s))||ls(t=s.valueOf)&&!us(i=os(t,s))||e!=="string"&&ls(t=s.toString)&&!us(i=os(t,s)))return i;throw Bl("Can't convert object to primitive value")},Sn={exports:{}},Ha=Ee,Vl=Object.defineProperty,Fl=function(s,e){try{Vl(Ha,s,{value:e,configurable:!0,writable:!0})}catch(t){Ha[s]=e}return e},Ul=Ee,jl=Fl,Ga="__core-js_shared__",Hl=Ul[Ga]||jl(Ga,{}),bn=Hl,Ya=bn;(Sn.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 gn=Sn.exports,Gl=sa,Yl=Object,Mi=function(s){return Yl(Gl(s))},ql=Ve,zl=Mi,Wl=ql({}.hasOwnProperty),Ue=Object.hasOwn||function(e,t){return Wl(zl(e),t)},Ql=Ve,Kl=0,Jl=Math.random(),Xl=Ql(1 .toString),yn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Xl(++Kl+Jl,36)},Zl=Ee,eu=gn,qa=Ue,tu=yn,iu=fn,su=mn,Tt=Zl.Symbol,ds=eu("wks"),au=su?Tt.for||Tt:Tt&&Tt.withoutSetter||tu,$e=function(s){return qa(ds,s)||(ds[s]=iu&&qa(Tt,s)?Tt[s]:au("Symbol."+s)),ds[s]},ru=Fe,za=ot,Wa=vn,nu=Bi,ou=Ml,lu=$e,uu=TypeError,du=lu("toPrimitive"),cu=function(s,e){if(!za(s)||Wa(s))return s;var t=nu(s,du),i;if(t){if(e===void 0&&(e="default"),i=ru(t,s,e),!za(i)||Wa(i))return i;throw uu("Can't convert object to primitive value")}return e===void 0&&(e="number"),ou(s,e)},hu=cu,pu=vn,ua=function(s){var e=hu(s,"string");return pu(e)?e:e+""},fu=lt,mu=cn,vu=hn,ni=ut,Qa=ua,Su=TypeError,cs=Object.defineProperty,bu=Object.getOwnPropertyDescriptor,hs="enumerable",ps="configurable",fs="writable";Dt.f=fu?vu?function(e,t,i){if(ni(e),t=Qa(t),ni(i),typeof e=="function"&&t==="prototype"&&"value"in i&&fs in i&&!i[fs]){var a=bu(e,t);a&&a[fs]&&(e[t]=i.value,i={configurable:ps in i?i[ps]:a[ps],enumerable:hs in i?i[hs]:a[hs],writable:!1})}return cs(e,t,i)}:cs:function(e,t,i){if(ni(e),t=Qa(t),ni(i),mu)try{return cs(e,t,i)}catch(a){}if("get"in i||"set"in i)throw Su("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Vi=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},gu=lt,yu=Dt,Tu=Vi,Wt=gu?function(s,e,t){return yu.f(s,e,Tu(1,t))}:function(s,e,t){return s[e]=t,s},Eu=gn,$u=yn,Ka=Eu("keys"),da=function(s){return Ka[s]||(Ka[s]=$u(s))},ca={},ku=al,Tn=Ee,Pu=ot,Au=Wt,ms=Ue,vs=bn,wu=da,_u=ca,Ja="Object already initialized",Ys=Tn.TypeError,Du=Tn.WeakMap,wi,Gt,_i,Ru=function(s){return _i(s)?Gt(s):wi(s,{})},Cu=function(s){return function(e){var t;if(!Pu(e)||(t=Gt(e)).type!==s)throw Ys("Incompatible receiver, "+s+" required");return t}};if(ku||vs.state){var Pe=vs.state||(vs.state=new Du);Pe.get=Pe.get,Pe.has=Pe.has,Pe.set=Pe.set,wi=function(s,e){if(Pe.has(s))throw Ys(Ja);return e.facade=s,Pe.set(s,e),e},Gt=function(s){return Pe.get(s)||{}},_i=function(s){return Pe.has(s)}}else{var vt=wu("state");_u[vt]=!0,wi=function(s,e){if(ms(s,vt))throw Ys(Ja);return e.facade=s,Au(s,vt,e),e},Gt=function(s){return ms(s,vt)?s[vt]:{}},_i=function(s){return ms(s,vt)}}var Iu={set:wi,get:Gt,has:_i,enforce:Ru,getterFor:Cu},xu=Ni,En=Function.prototype,Xa=En.apply,Za=En.call,Nu=typeof Reflect=="object"&&Reflect.apply||(xu?Za.bind(Xa):function(){return Za.apply(Xa,arguments)}),Lu=Li,Ou=Ve,$n=function(s){if(Lu(s)==="Function")return Ou(s)},kn={},Pn={},An={}.propertyIsEnumerable,wn=Object.getOwnPropertyDescriptor,Bu=wn&&!An.call({1:2},1);Pn.f=Bu?function(e){var t=wn(this,e);return!!t&&t.enumerable}:An;var Mu=lt,Vu=Fe,Fu=Pn,Uu=Vi,ju=zt,Hu=ua,Gu=Ue,Yu=cn,er=Object.getOwnPropertyDescriptor;kn.f=Mu?er:function(e,t){if(e=ju(e),t=Hu(t),Yu)try{return er(e,t)}catch(i){}if(Gu(e,t))return Uu(!Vu(Fu.f,e,t),e[t])};var qu=Me,zu=ve,Wu=/#|\.prototype\./,Qt=function(s,e){var t=Ku[Qu(s)];return t==Xu?!0:t==Ju?!1:zu(e)?qu(e):!!e},Qu=Qt.normalize=function(s){return String(s).replace(Wu,".").toLowerCase()},Ku=Qt.data={},Ju=Qt.NATIVE="N",Xu=Qt.POLYFILL="P",Zu=Qt,tr=$n,ed=la,td=Ni,id=tr(tr.bind),_n=function(s,e){return ed(s),e===void 0?s:td?id(s,e):function(){return s.apply(e,arguments)}},oi=Ee,sd=Nu,ad=$n,rd=ve,nd=kn.f,od=Zu,St=aa,ld=_n,bt=Wt,ir=Ue,ud=function(s){var e=function(t,i,a){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,a)}return sd(s,this,arguments)};return e.prototype=s.prototype,e},Fi=function(s,e){var t=s.target,i=s.global,a=s.stat,n=s.proto,o=i?oi:a?oi[t]:(oi[t]||{}).prototype,l=i?St:St[t]||bt(St,t,{})[t],d=l.prototype,u,c,h,p,f,m,S,g,E;for(p in e)u=od(i?p:t+(a?".":"#")+p,s.forced),c=!u&&o&&ir(o,p),m=l[p],c&&(s.dontCallGetSet?(E=nd(o,p),S=E&&E.value):S=o[p]),f=c&&S?S:e[p],!(c&&typeof m==typeof f)&&(s.bind&&c?g=ld(f,oi):s.wrap&&c?g=ud(f):n&&rd(f)?g=ad(f):g=f,(s.sham||f&&f.sham||m&&m.sham)&&bt(g,"sham",!0),bt(l,p,g),n&&(h=t+"Prototype",ir(St,h)||bt(St,h,{}),bt(St[h],p,f),s.real&&d&&(u||!d[p])&&bt(d,p,f)))},qs=lt,dd=Ue,Dn=Function.prototype,cd=qs&&Object.getOwnPropertyDescriptor,ha=dd(Dn,"name"),hd=ha&&function(){}.name==="something",pd=ha&&(!qs||qs&&cd(Dn,"name").configurable),fd={EXISTS:ha,PROPER:hd,CONFIGURABLE:pd},Rn={},md=Math.ceil,vd=Math.floor,Sd=Math.trunc||function(e){var t=+e;return(t>0?vd:md)(t)},bd=Sd,pa=function(s){var e=+s;return e!==e||e===0?0:bd(e)},gd=pa,yd=Math.max,Td=Math.min,Ed=function(s,e){var t=gd(s);return t<0?yd(t+e,0):Td(t,e)},$d=pa,kd=Math.min,Pd=function(s){return s>0?kd($d(s),9007199254740991):0},Ad=Pd,fa=function(s){return Ad(s.length)},wd=zt,_d=Ed,Dd=fa,sr=function(s){return function(e,t,i){var a=wd(e),n=Dd(a),o=_d(i,n),l;if(s&&t!=t){for(;n>o;)if(l=a[o++],l!=l)return!0}else for(;n>o;o++)if((s||o in a)&&a[o]===t)return s||o||0;return!s&&-1}},Rd={includes:sr(!0),indexOf:sr(!1)},Cd=Ve,Ss=Ue,Id=zt,xd=Rd.indexOf,Nd=ca,ar=Cd([].push),Ld=function(s,e){var t=Id(s),i=0,a=[],n;for(n in t)!Ss(Nd,n)&&Ss(t,n)&&ar(a,n);for(;e.length>i;)Ss(t,n=e[i++])&&(~xd(a,n)||ar(a,n));return a},Cn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Od=Ld,Bd=Cn,Md=Object.keys||function(e){return Od(e,Bd)},Vd=lt,Fd=hn,Ud=Dt,jd=ut,Hd=zt,Gd=Md;Rn.f=Vd&&!Fd?Object.defineProperties:function(e,t){jd(e);for(var i=Hd(t),a=Gd(t),n=a.length,o=0,l;n>o;)Ud.f(e,l=a[o++],i[l]);return e};var Yd=ra,qd=Yd("document","documentElement"),zd=ut,Wd=Rn,rr=Cn,Qd=ca,Kd=qd,Jd=dn,Xd=da,nr=">",or="<",zs="prototype",Ws="script",In=Xd("IE_PROTO"),bs=function(){},xn=function(s){return or+Ws+nr+s+or+"/"+Ws+nr},lr=function(s){s.write(xn("")),s.close();var e=s.parentWindow.Object;return s=null,e},Zd=function(){var s=Jd("iframe"),e="java"+Ws+":",t;return s.style.display="none",Kd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(xn("document.F=Object")),t.close(),t.F},li,Ei=function(){try{li=new ActiveXObject("htmlfile")}catch(e){}Ei=typeof document!="undefined"?document.domain&&li?lr(li):Zd():lr(li);for(var s=rr.length;s--;)delete Ei[zs][rr[s]];return Ei()};Qd[In]=!0;var Nn=Object.create||function(e,t){var i;return e!==null?(bs[zs]=zd(e),i=new bs,bs[zs]=null,i[In]=e):i=Ei(),t===void 0?i:Wd.f(i,t)},ec=Me,tc=!ec(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),ic=Ue,sc=ve,ac=Mi,rc=da,nc=tc,ur=rc("IE_PROTO"),Qs=Object,oc=Qs.prototype,Ln=nc?Qs.getPrototypeOf:function(s){var e=ac(s);if(ic(e,ur))return e[ur];var t=e.constructor;return sc(t)&&e instanceof t?t.prototype:e instanceof Qs?oc:null},lc=Wt,On=function(s,e,t,i){return i&&i.enumerable?s[e]=t:lc(s,e,t),s},uc=Me,dc=ve,cc=ot,hc=Nn,dr=Ln,pc=On,fc=$e,Ks=fc("iterator"),Bn=!1,Le,gs,ys;[].keys&&(ys=[].keys(),"next"in ys?(gs=dr(dr(ys)),gs!==Object.prototype&&(Le=gs)):Bn=!0);var mc=!cc(Le)||uc(function(){var s={};return Le[Ks].call(s)!==s});mc?Le={}:Le=hc(Le);dc(Le[Ks])||pc(Le,Ks,function(){return this});var Mn={IteratorPrototype:Le,BUGGY_SAFARI_ITERATORS:Bn},vc=$e,Sc=vc("toStringTag"),Vn={};Vn[Sc]="z";var ma=String(Vn)==="[object z]",bc=ma,gc=ve,$i=Li,yc=$e,Tc=yc("toStringTag"),Ec=Object,$c=$i(function(){return arguments}())=="Arguments",kc=function(s,e){try{return s[e]}catch(t){}},Ui=bc?$i:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=kc(e=Ec(s),Tc))=="string"?t:$c?$i(e):(i=$i(e))=="Object"&&gc(e.callee)?"Arguments":i},Pc=ma,Ac=Ui,wc=Pc?{}.toString:function(){return"[object "+Ac(this)+"]"},_c=ma,Dc=Dt.f,Rc=Wt,Cc=Ue,Ic=wc,xc=$e,cr=xc("toStringTag"),Fn=function(s,e,t,i){if(s){var a=t?s:s.prototype;Cc(a,cr)||Dc(a,cr,{configurable:!0,value:e}),i&&!_c&&Rc(a,"toString",Ic)}},Nc=Mn.IteratorPrototype,Lc=Nn,Oc=Vi,Bc=Fn,Mc=_t,Vc=function(){return this},Fc=function(s,e,t,i){var a=e+" Iterator";return s.prototype=Lc(Nc,{next:Oc(+!i,t)}),Bc(s,a,!1,!0),Mc[a]=Vc,s},Uc=Fi,jc=Fe,Un=fd,Hc=Fc,Gc=Ln,Yc=Fn,hr=On,qc=$e,pr=_t,jn=Mn,zc=Un.PROPER;Un.CONFIGURABLE;jn.IteratorPrototype;var ui=jn.BUGGY_SAFARI_ITERATORS,Ts=qc("iterator"),fr="keys",di="values",mr="entries",Wc=function(){return this},Qc=function(s,e,t,i,a,n,o){Hc(t,e,i);var l=function(E){if(E===a&&p)return p;if(!ui&&E in c)return c[E];switch(E){case fr:return function(){return new t(this,E)};case di:return function(){return new t(this,E)};case mr:return function(){return new t(this,E)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[Ts]||c["@@iterator"]||a&&c[a],p=!ui&&h||l(a),f=e=="Array"&&c.entries||h,m,S,g;if(f&&(m=Gc(f.call(new s)),m!==Object.prototype&&m.next&&(Yc(m,d,!0,!0),pr[d]=Wc)),zc&&a==di&&h&&h.name!==di&&(u=!0,p=function(){return jc(h,this)}),a)if(S={values:l(di),keys:n?p:l(fr),entries:l(mr)},o)for(g in S)(ui||u||!(g in c))&&hr(c,g,S[g]);else Uc({target:e,proto:!0,forced:ui||u},S);return o&&c[Ts]!==p&&hr(c,Ts,p,{name:a}),pr[e]=p,S},Kc=function(s,e){return{value:s,done:e}},Jc=zt,vr=_t,Hn=Iu;Dt.f;var Xc=Qc,ci=Kc,Gn="Array Iterator",Zc=Hn.set,eh=Hn.getterFor(Gn);Xc(Array,"Array",function(s,e){Zc(this,{type:Gn,target:Jc(s),index:0,kind:e})},function(){var s=eh(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ci(void 0,!0)):t=="keys"?ci(i,!1):t=="values"?ci(e[i],!1):ci([i,e[i]],!1)},"values");vr.Arguments=vr.Array;var th=$e,ih=_t,sh=th("iterator"),ah=Array.prototype,rh=function(s){return s!==void 0&&(ih.Array===s||ah[sh]===s)},nh=Ui,Sr=Bi,oh=Oi,lh=_t,uh=$e,dh=uh("iterator"),Yn=function(s){if(!oh(s))return Sr(s,dh)||Sr(s,"@@iterator")||lh[nh(s)]},ch=Fe,hh=la,ph=ut,fh=oa,mh=Yn,vh=TypeError,Sh=function(s,e){var t=arguments.length<2?mh(s):e;if(hh(t))return ph(ch(t,s));throw vh(fh(s)+" is not iterable")},bh=Fe,br=ut,gh=Bi,yh=function(s,e,t){var i,a;br(s);try{if(i=gh(s,"return"),!i){if(e==="throw")throw t;return t}i=bh(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return br(i),t},Th=_n,Eh=Fe,$h=ut,kh=oa,Ph=rh,Ah=fa,gr=na,wh=Sh,_h=Yn,yr=yh,Dh=TypeError,ki=function(s,e){this.stopped=s,this.result=e},Tr=ki.prototype,Rh=function(s,e,t){var i=t&&t.that,a=!!(t&&t.AS_ENTRIES),n=!!(t&&t.IS_RECORD),o=!!(t&&t.IS_ITERATOR),l=!!(t&&t.INTERRUPTED),d=Th(e,i),u,c,h,p,f,m,S,g=function(y){return u&&yr(u,"normal",y),new ki(!0,y)},E=function(y){return a?($h(y),l?d(y[0],y[1],g):d(y[0],y[1])):l?d(y,g):d(y)};if(n)u=s.iterator;else if(o)u=s;else{if(c=_h(s),!c)throw Dh(kh(s)+" is not iterable");if(Ph(c)){for(h=0,p=Ah(s);p>h;h++)if(f=E(s[h]),f&&gr(Tr,f))return f;return new ki(!1)}u=wh(s,c)}for(m=n?s.next:u.next;!(S=Eh(m,u)).done;){try{f=E(S.value)}catch(y){yr(u,"throw",y)}if(typeof f=="object"&&f&&gr(Tr,f))return f}return new ki(!1)},Ch=ua,Ih=Dt,xh=Vi,Nh=function(s,e,t){var i=Ch(e);i in s?Ih.f(s,i,xh(0,t)):s[i]=t},Lh=Fi,Oh=Rh,Bh=Nh;Lh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return Oh(e,function(i,a){Bh(t,i,a)},{AS_ENTRIES:!0}),t}});var Mh=aa,Vh=Mh.Object.fromEntries,Fh={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},Uh=Fh,jh=Ee,Hh=Ui,Gh=Wt,Er=_t,Yh=$e,$r=Yh("toStringTag");for(var Es in Uh){var kr=jh[Es],$s=kr&&kr.prototype;$s&&Hh($s)!==$r&&Gh($s,$r,Es),Er[Es]=Er.Array}var qh=Vh,zh=qh,Wh=zh,Qh=Wh,kt=ia(Qh),se;(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"})(se||(se={}));var ye=(s,e=0,t=se.OFFSET_P)=>{switch(t){case se.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case se.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}case se.DASH_CMAF_OFFSET_P:{if(e===0)return s;const i=new URL(s);return i.searchParams.set("offset_p",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s};const Pr=(s,e)=>{var t;switch(e){case se.OFFSET_P:return NaN;case se.PLAYBACK_SHIFT:{const i=new URL(s);return Number(i.searchParams.get("playback_shift"))}case se.DASH_CMAF_OFFSET_P:{const i=new URL(s);return Number((t=i.searchParams.get("offset_p"))!==null&&t!==void 0?t:0)}default:r.assertNever(e)}};var P=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};class K{constructor(e){this.transitionStarted$=new r.Subject,this.transitionEnded$=new r.Subject,this.transitionUpdated$=new r.Subject,this.forceChanged$=new r.Subject,this.stateChangeStarted$=r.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=r.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||r.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 Kh=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 r.assertNever(s)}};var L;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(L||(L={}));const Jh=5,Xh=5,Zh=500,Ar=7e3;class ep{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new K(L.STOPPED),this.syncPlayback=()=>{const i=this.videoState.getState(),a=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(a)}; desiredPlaybackState: ${n}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(l)};`}),n===exports.PlaybackState.STOPPED){i!==L.STOPPED&&(this.videoState.startTransitionTo(L.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===B.Requested&&i!==L.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case L.PLAYING:case L.PAUSED:case L.READY:break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case L.PLAYING:break;case L.PAUSED:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.READY:this.videoState.startTransitionTo(L.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case L.PLAYING:this.videoState.startTransitionTo(L.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case L.PAUSED:break;case L.READY:this.videoState.startTransitionTo(L.PAUSED),this.videoState.setState(L.PAUSED);break;case L.STOPPED:this.videoState.startTransitionTo(L.READY),this.prepare();break;default:r.assertNever(i)}break}default:r.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(Kh(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 r.Subscription;this.subscription.add(e),this.subscription.add(r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>`stateChangeStarted$ ${JSON.stringify(a)}`)),this.videoState.stateChangeEnded$.pipe(r.map(a=>`stateChangeEnded$ ${JSON.stringify(a)}`))).subscribe(a=>this.log({message:`[videoState] ${a}`})));const t=(a,n)=>this.subscription.add(a.subscribe(n));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const a=new r.Subject;e.add(a.pipe(r.debounce(Zh)).subscribe(()=>{this.params.output.seekedEvent$.next()}));let n=NaN;e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe(o=>{this.logRemoteEvent(o);const l=o.value;this.params.output.position$.next(l),(this.params.desiredState.seekState.getState().state===B.Applying||Math.abs(l-n)>Jh)&&a.next(l),n=l})),e.add(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe(o=>{this.logRemoteEvent(o),this.params.output.duration$.next(o.value)}))}t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),a=>{this.logRemoteEvent(a),a.value?this.handleRemotePause():this.handleRemotePlay()}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),a=>{this.logRemoteEvent(a);const{remotePlayer:n}=this.params.connection,o=a.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<Xh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:r.assertNever(o)}}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({volume:a.value})}),t(r.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),a=>{this.logRemoteEvent(a),this.handleRemoteVolumeChange({muted:a.value})});const i=r.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),P(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:B.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)===L.PAUSED||e===L.PLAYING)&&(this.videoState.setState(L.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===L.PLAYING||e===L.PAUSED)&&(this.videoState.setState(L.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===L.READY&&this.videoState.setState(L.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==L.STOPPED&&this.videoState.setState(L.STOPPED)}handleRemoteVolumeChange(e){var t,i;const a=this.params.output.volume$.getValue(),n={volume:(t=e.volume)!==null&&t!==void 0?t:a.volume,muted:(i=e.muted)!==null&&i!==void 0?i:a.muted};(n.volume!==a.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 a,n,o;switch(e){case exports.VideoFormat.MPEG:{const c=i[e];r.assertNonNullable(c);const h=r.getHighestQuality(Object.keys(c));r.assertNonNullable(h);const p=c[h];r.assertNonNullable(p),a=p,n="video/mp4",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const c=i[e];r.assertNonNullable(c),a=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];r.assertNonNullable(c),a=c.url,n="application/dash+xml",o=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_LIVE_CMAF:{const c=i[e];r.assertNonNullable(c),a=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];r.assertNonNullable(c),a=ye(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:r.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 r.assertNever(e)}const l=new chrome.cast.media.MediaInfo((t=this.params.meta.videoId)!==null&&t!==void 0?t:a,n);l.contentUrl=a,l.streamType=o,l.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:d,subtitle:u}=this.params.meta;return r.isNonNullable(d)&&(l.metadata.title=d),r.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===B.Applying||i.state===B.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((a,n)=>{this.loadMediaTimeoutSubscription.add(r.timeout(Ar).subscribe(()=>n(`timeout(${Ar})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()},a=>{const n=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${a}`;this.log({message:n}),this.params.output.error$.next({id:"ChromecastProvider.loadMedia",category:r.ErrorCategory.VIDEO_PIPELINE,message:n,thrown:a})}).finally(()=>{this.loadMediaTimeoutSubscription.unsubscribe()})}logRemoteEvent(e){this.log({message:`[remoteEvent] ${JSON.stringify(e)}`})}}var tp=s=>{let e,t=!1,i=!1;s.on("playbackTimeUpdated",({timeToEnd:a})=>{i=a<=3,t&&i&&(e==null||e())}),s.extend("MediaSourceController",function(){const{parent:a}=this,n=a.signalEndOfStream;return{signalEndOfStream:o=>{t=!0,e=()=>n(o),t&&i&&(e==null||e())}}},!0)},ip=s=>{const e=new r.ValueSubject(1/0),t=new r.Subject,i=new r.ValueSubject(void 0),a=new r.ValueSubject(void 0);let n=NaN,o=!1;const l=()=>{n=Date.now(),o=!1},d=c=>{var h,p,f,m,S;const g=kt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(v=>v.split(": ")));if("x-playback-duration"in g||"x-playback-duration-millis"in g){const v=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),b=parseInt((p=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&p!==void 0?p:"",10),T=(f=b!=null?b:v*1e3)!==null&&f!==void 0?f:NaN;r.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const E=(m=g["x-delivery-type"])!==null&&m!==void 0?m:exports.HttpConnectionType.HTTP1,y=(S={1:!0,0:!1}[g["x-reused"]])!==null&&S!==void 0?S:void 0;i.next(E),a.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(p){if(p.request.type==="MPD"){const f=p.onload,m=p.progress;p.onload=function(...S){return d(this),f(...S)},p.progress=function(...S){return u(this),m(...S)},l()}return h(p)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},Pt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},sp=s=>s.extend("RequestModifier",()=>({modifyRequestURL:Pt}),!0),ap=s=>{s.extend("HTTPLoader",function(){const{parent:e}=this,t=e.load;return{load:i=>{if(i.request&&i.request.range){const[a,n]=i.request.range.split("-").map(l=>parseInt(l,10)),o=new URL(i.request.url,location.href);o.searchParams.append("bytes",`${a}-${n}`),i.request.url=o.toString(),i.request.range=void 0}t(i)}}},!0)};const Te=(s,e,t,{equal:i=(o,l)=>o===l,changed$:a,onError:n}={})=>{const o=s.getState(),l=e(),d=r.isNullable(a),u=new r.Subscription;return a&&u.add(a.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},dt=(s,e,t)=>Te(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),je=(s,e,t,i)=>Te(e,()=>({muted:s.muted,volume:s.volume}),a=>{r.isNonNullable(a)&&(s.muted=a.muted,s.volume=a.volume)},{equal:(a,n)=>a===n||(a==null?void 0:a.muted)===(n==null?void 0:n.muted)&&(a==null?void 0:a.volume)===(n==null?void 0:n.volume),changed$:t,onError:i}),Xe=(s,e,t,i)=>Te(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),rp=s=>["__",s.language,s.label].join("|"),np=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class Ce{constructor(){this.available$=new r.Subject,this.current$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.subscription=new r.Subscription,this.externalTracks=new Map,this.internalTracks=new Map}connect(e,t,i){this.video=e,this.cueSettings=t.textTrackCuesSettings,this.subscribe();const a=n=>{this.error$.next({id:"TextTracksManager",category:r.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(Te(t.internalTextTracks,()=>Object.values(this.internalTracks),n=>{r.isNonNullable(n)&&this.setInternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="internal"))),onError:a})),this.subscription.add(Te(t.externalTextTracks,()=>Object.values(this.externalTracks),n=>{r.isNonNullable(n)&&this.setExternal(n)},{equal:(n,o)=>r.isNonNullable(n)&&r.isNonNullable(o)&&n.length===o.length&&n.every(({id:l},d)=>l===o[d].id),changed$:this.available$.pipe(r.map(n=>n.filter(({type:o})=>o==="external"))),onError:a})),this.subscription.add(Te(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:a})),this.subscription.add(Te(t.textTrackCuesSettings,()=>({}),()=>{if(this.video)for(const n of this.htmlTextTracksAsArray())this.applyCueSettings(n.cues),this.applyCueSettings(n.activeCues)}))}subscribe(){r.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(r.fromEvent(e,"addtrack").subscribe(()=>{const i=this.current$.getValue();i&&this.select(i)})),this.subscription.add(r.merge(r.fromEvent(e,"addtrack"),r.fromEvent(e,"removetrack"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().map(i=>this.htmlTextTrackToITextTrack(i))),r.filterChanged((i,a)=>i.length===a.length&&i.every(({id:n},o)=>n===a[o].id))).subscribe(this.available$)),this.subscription.add(r.merge(r.fromEvent(e,"change"),r.observableFrom(["init"])).pipe(r.map(()=>this.htmlTextTracksAsArray().find(({mode:i})=>i==="showing")),r.map(i=>i&&this.htmlTextTrackToITextTrack(i).id),r.filterChanged()).subscribe(this.current$));const t=i=>{var a,n;return this.applyCueSettings((n=(a=i.target)===null||a===void 0?void 0:a.activeCues)!==null&&n!==void 0?n:null)};this.subscription.add(r.fromEvent(e,"addtrack").subscribe(i=>{var a,n;(a=i.track)===null||a===void 0||a.addEventListener("cuechange",t);const o=l=>{var d,u,c,h,p;const f=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;f&&f.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(p=l.target)===null||p===void 0||p.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(r.fromEvent(e,"removetrack").subscribe(i=>{var a;(a=i.track)===null||a===void 0||a.removeEventListener("cuechange",t)}))}applyCueSettings(e){if(!e||!e.length)return;const t=this.cueSettings.getState();for(const i of Array.from(e)){const a=i;r.isNonNullable(t.align)&&(a.align=t.align),r.isNonNullable(t.position)&&(a.position=t.position),r.isNonNullable(t.size)&&(a.size=t.size),r.isNonNullable(t.line)&&(a.line=t.line)}}htmlTextTracksAsArray(e=!1){r.assertNonNullable(this.video);const t=[...this.video.textTracks];return e?t:t.filter(Ce.isHealthyTrack)}htmlTextTrackToITextTrack(e){var t,i;const{language:a,label:n}=e,o=e.id?e.id:rp(e),l=this.externalTracks.has(o),d=o.includes("auto");return l?{id:o,type:"external",isAuto:d,language:a,label:n,url:(t=this.externalTracks.get(o))===null||t===void 0?void 0:t.url}:{id:o,type:"internal",isAuto:d,language:a,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:a,isAuto:n})=>!this.internalTracks.has(i)&&!t.some(([,o])=>o.language===a&&o.isAuto===n)).forEach(i=>this.attach(i)),Array.from(this.internalTracks).filter(([i])=>!e.find(a=>a.id===i)).forEach(([,i])=>this.detach(i))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))t.mode="showing";for(const t of this.htmlTextTracksAsArray(!0))(r.isNullable(e)||!np(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){r.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){r.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 va=s=>{s.removeAttribute("src"),s.load()},op=s=>{try{s.pause(),s.playbackRate=0,va(s),s.remove()}catch(e){console.error(e)}};class lp{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 Js=window.WeakMap?new WeakMap:new lp,He=s=>{let e=s.querySelector("video");const t=!!e;return e?va(e):(e=document.createElement("video"),s.appendChild(e)),Js.set(e,t),e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.controls=!1,e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),e},Ge=s=>{const e=Js.get(s);Js.delete(s),e?va(s):op(s)};class ji{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 qn=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},wr=s=>{const e=qn(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},up=s=>{const e=qn(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Xs=3;class dp{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 a=this._source.buffered.start(t);const n=this._source.buffered.end(t);a>e&&a-e<Xs&&(a=e),this._buffer.push({from:a,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||Xs))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:a,to:n})=>{const o=a>=e&&a<t,l=n>=e&&n<t;o&&l||(o?i(t,n):l?i(a,e):a<e&&n>t?(i(t,n),i(a,e)):i(a,n))})}destroy(){this._buffer=[]}}var zn=(s,e,t=Xs)=>{let i=0,a=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,a=l,!t)return{from:i,to:a};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<=a&&(a=s.end(d))}}return{from:i,to:a}};const Ye=s=>{const e=v=>r.fromEvent(s,v).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(v=>r.fromEvent(s,v))).pipe(r.map(v=>v.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>zn(s.buffered,s.currentTime))),o=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),l=r.fromEvent(s,"volumechange").pipe(r.map(()=>({muted:s.muted,volume:s.volume}))),d=r.fromEvent(s,"ratechange").pipe(r.map(()=>s.playbackRate)),u=r.fromEvent(s,"error").pipe(r.filter(()=>!!(s.error||s.played.length)),r.map(()=>{var v;const b=s.error;return{id:b?`MediaError#${b.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:b?b.message:"Error event from HTML video element",thrown:(v=s.error)!==null&&v!==void 0?v:void 0}})),c=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),h=new r.Subject,p=.3;let f;c.subscribe(v=>{s.loop&&r.isNonNullable(f)&&r.isNonNullable(v)&&f>=s.duration-p&&v<=p&&h.next(f),f=v});const m=r.fromEvent(s,"enterpictureinpicture"),S=r.fromEvent(s,"leavepictureinpicture"),g=new r.ValueSubject(up(s));m.subscribe(()=>g.next(!0)),S.subscribe(()=>g.next(!1));const E=new r.ValueSubject(wr(s));return r.fromEvent(s,"fullscreenchange").pipe(r.map(()=>wr(s))).subscribe(E),{playing$:o,pause$:e("pause").pipe(r.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$:r.fromEvent(s,"durationchange").pipe(r.map(()=>s.duration)),isBuffering$:i,currentBuffer$:a,volumeState$:l,playbackRateState$:d,inPiP$:g,inFullscreen$:E}},Sa=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var cp=Fi,hp=Mi,pp=fa,fp=pa;cp({target:"Array",proto:!0},{at:function(e){var t=hp(this),i=pp(t),a=fp(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var mp=ra,Wn=mp,vp=Wn,Sp=vp("Array","at"),bp=Sp,gp=bp,yp=gp,Tp=yp,we=ia(Tp);let ba=!1,Ne={};const Ep=s=>{ba=s},$p=()=>{Ne={}},kp=s=>{s(Ne)},hi=(s,e)=>{var t;ba&&(Ne.meta=(t=Ne.meta)!==null&&t!==void 0?t:{},Ne.meta[s]=e)};class _e{constructor(e){this.name=e}next(e){var t,i;if(!ba)return;Ne.series=(t=Ne.series)!==null&&t!==void 0?t:{};const a=(i=Ne.series[this.name])!==null&&i!==void 0?i:[];a.push([Date.now(),e]),Ne.series[this.name]=a}}var rt;(function(s){s.FitsContainer="FitsContainer",s.FitsThroughput="FitsThroughput",s.Buffer="Buffer",s.DroppedFramesLimit="DroppedFramesLimit",s.FitsQualityLimits="FitsQualityLimits"})(rt||(rt={}));const Pp=new _e("best_bitrate"),Ap=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class wp{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Rt=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u,droppedVideoMaxQualityLimit:c,abrLogger:h})=>{var p,f,m,S,g;const E=i.usePixelRatio&&(p=window.devicePixelRatio)!==null&&p!==void 0?p:1,y=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*E*i.containerSizeFactor,height:e.height*E*i.containerSizeFactor},v=y&&r.videoSizeToQuality(y),b=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,T=s.filter(C=>!r.isInvariantQuality(C.quality)).sort((C,A)=>r.isHigher(C.quality,A.quality)?-1:1),k=(f=we(T,-1))===null||f===void 0?void 0:f.quality,N=(m=we(T,0))===null||m===void 0?void 0:m.quality,U=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&r.isLower(a.max,a.min)||r.isNonNullable(a.min)&&N&&r.isHigher(a.min,N)||r.isNonNullable(a.max)&&k&&r.isLower(a.max,k),R=b*Ap(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),x={},_=T.filter(C=>(v?r.isLower(C.quality,v):!0)?(r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(C.bitrate)?t-n>=C.bitrate*R:!0)?i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!r.isInvariantQuality(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&r.isHigher(C.quality,d.quality)?(x[C.quality]=rt.Buffer,!1):!!c&&r.isHigherOrEqual(C.quality,c)?(x[C.quality]=rt.DroppedFramesLimit,!1):U||(r.isNullable(a.max)||r.isLowerOrEqual(C.quality,a.max))&&(r.isNullable(a.min)||r.isHigherOrEqual(C.quality,a.min))?!0:(x[C.quality]=rt.FitsQualityLimits,!1):(x[C.quality]=rt.FitsThroughput,!1):(x[C.quality]=rt.FitsContainer,!1))[0];_&&_.bitrate&&Pp.next(_.bitrate);const I=(S=_!=null?_:T[Math.ceil((T.length-1)/2)])!==null&&S!==void 0?S:s[0];I.quality!==((g=u==null?void 0:u.last)===null||g===void 0?void 0:g.quality)&&h({message:`
|
|
7
7
|
[available tracks] ${s.map(C=>C.quality).join(", ")}
|
|
8
8
|
|
|
9
9
|
[limit params]
|
|
@@ -26,7 +26,7 @@
|
|
|
26
26
|
[selected track] ${I.quality}
|
|
27
27
|
`});const q=I&&u&&u.history[I.id]&&r.now()-u.history[I.id]<=i.trackCooldown&&(!u.last||I.id!==u.last.id);if(I!=null&&I.id&&u&&!q&&u.recordSelection(I),q&&(u!=null&&u.last)){const C=u.last;return u==null||u.recordSwitch(C),h({message:`
|
|
28
28
|
[last selected] ${C.quality}
|
|
29
|
-
`}),C}return u==null||u.recordSwitch(I),I};var le=s=>new URL(s).hostname;const _p=300,Di=(s,e=_p)=>new r.Observable(t=>{const{width:i,height:a}=s.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(Bo(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),r.isNonNullable(d)&&r.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(s),()=>n.disconnect()});class Hi{constructor(){this.onDroopedVideoFramesLimit$=new r.Subject,this.subscription=new r.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new r.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&&!r.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality(),a=t-this.prevTotalVideoFrames,n=i-this.prevDroppedVideoFrames,o=1-(a-n)/a;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&r.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(r.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=r.interval(this.droppedFramesChecker.checkTime).pipe(r.filter(()=>this.playing),r.filter(()=>{const a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(r.debounce(this.droppedFramesChecker.checkTime)),i=r.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 a=(i=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>r.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:a}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 Mt={};var M;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(M||(M={}));const ie=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class _r{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(M.DOWNLOADING_LIB),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.videoTracks$=new r.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new r.ValueSubject(void 0),this.maxSeekBackTime$=new r.ValueSubject(1/0),this.availableFrom$=new r.ValueSubject(void 0),this.elementSize$=new r.ValueSubject(void 0),this.liveOffset=new ji,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===M.DOWNLOADING_LIB||t===M.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&t!==M.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 M.STOPPED:break;case M.PLAYING:case M.PAUSED:case M.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case M.STOPPED:this.prepare();break;case M.PLAYING:case M.PAUSED:case M.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case M.PLAYING:break;case M.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case M.READY:this.play();break;case M.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case M.PLAYING:this.pause(),this.liveOffset.pause();break;case M.PAUSED:break;case M.READY:this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=He(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(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=a=>{var n;e||this.params.output.error$.next({id:a==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=a==null?void 0:a.toString)===null||n===void 0?void 0:n.call(a)}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(Mt.MediaPlayer=a.MediaPlayer,Mt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Mt.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Mt.Debug,"dashjs not loaded"),this.player=Mt.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?Sa(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&ap(this.player),tp(this.player),this.params.tuning.requestQuick&&sp(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=v=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},a=(v,b)=>this.subscription.add(v.subscribe(b,i));a(Di(this.video),this.elementSize$),a(ie(this.player,"error").pipe(r.map(v=>{const b=typeof v.error=="object"?v.error.code:v.error,T=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:T}})),e.error$),a(ie(this.player,"playbackError").pipe(r.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=ie(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:v})=>v==="video"),r.map(({newQuality:v})=>{var b;return(b=this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===v))===null||b===void 0?void 0:b.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:v})=>v===M.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(Te(t.videoTrack,()=>{var v,b;const T=this.player.getQualityFor("video");return(b=(v=this.videoTracks$.getValue().find(({bitrateInfo:k})=>k.qualityIndex===T))===null||v===void 0?void 0:v.track)===null||b===void 0?void 0:b.id},v=>{var b;if(r.isNullable(v))return;const T=(b=this.videoTracks$.getValue().find(({track:k})=>k.id===v))===null||b===void 0?void 0:b.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:n.pipe(r.map(v=>v==null?void 0:v.id)),onError:i}))},i)),this.subscription.add(Te(t.autoVideoTrackSwitching,()=>{var v,b,T;return(T=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||T===void 0?void 0:T.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:i})),a(ie(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:v})=>v==="video"),r.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),a(ie(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:b}})=>{var T,k;const N=this.player.getDashMetrics(),U=N.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),R=(T=N.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&T!==void 0?T:exports.HttpConnectionType.HTTP1,x=(k={1:!0,0:!1}[U])!==null&&k!==void 0?k:void 0;this.params.output.httpConnectionType$.next(R),this.params.output.httpConnectionReused$.next(x),e.hostname$.next(le(b))}),a(ie(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:T}}})=>{this.isLive$.next(b),this.availableFrom$.next(T.getTime()),b||e.duration$.next(v);const k=[],N=this.player.getQualityFor("video");let U;for(const R of this.player.getBitrateInfoListFor("video")){const x=R.qualityIndex.toString(10),V=r.videoSizeToQuality(R),_=R.bitrate/1e3,I={width:R.width,height:R.height},q=this.frameRatesByFrameHeight[R.height];if(V){const C={id:x,quality:V,bitrate:_,size:I,fps:q};k.push({track:C,bitrateInfo:R}),R.qualityIndex===N&&(U=C)}}this.videoTracks$.next(k),e.availableVideoTracks$.next(k.map(({track:R})=>R)),U&&e.currentVideoTrack$.next(U),this.videoState.setState(M.STREAM_INITIALIZED),this.videoState.startTransitionTo(M.READY)}),a(ie(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),T=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(T,b)}),a(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=Rt(this.videoTracks$.getValue().map(({track:N})=>N),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to);const k=this.videoTracks$.getValue().find(({track:N})=>N===b);k!=null&&k.bitrateInfo&&this.player.setQualityFor("video",k==null?void 0:k.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:v})=>v),r.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=ie(this.player,"playbackTimeUpdated").pipe(r.map(({time:v})=>v!=null?v:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:b})=>this.params.output.liveTime$.next(v+b*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(ie(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(ie(this.player,"playbackEnded"),e.endedEvent$),a(ie(this.player,"playbackProgress").pipe(r.map(()=>zn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(ie(this.player,"playbackPlaying"),()=>{this.videoState.setState(M.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),a(ie(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(ie(this.player,"playbackPaused"),()=>{this.videoState.setState(M.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),a(ie(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===M.READY&&this.videoState.setState(M.READY)}),a(this.isLive$,e.isLive$),a(Di(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));a(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=ip(this.player);a(c,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(r.once()),e.firstBytesEvent$),a(ie(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(v=>v<60))}),({isLive:v,isShort:b})=>{const T=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:T}}})}),a(o.pipe(r.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(ie(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(ie(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),a(ie(this.player,"manifestLoaded"),v=>{var b,T,k,N,U,R,x;if(!((T=(b=v.data)===null||b===void 0?void 0:b.Period)===null||T===void 0)&&T.AdaptationSet){const V=[];for(const _ of(N=(k=v.data)===null||k===void 0?void 0:k.Period)===null||N===void 0?void 0:N.AdaptationSet)if(_.contentType==="text"){const I=(U=_.Representation)===null||U===void 0?void 0:U.id,q=new URL((R=_.Representation)===null||R===void 0?void 0:R.BaseURL,(x=v.data)===null||x===void 0?void 0:x.baseUri).toString(),C="internal",A=_.lang;V.push({id:I,url:q,type:C,language:A})}t.internalTextTracks.startTransitionTo(V)}}),this.subscription.add(dt(this.video,t.isLooped,i));const{volumeState$:p,looped$:f,playbackRateState$:m,inPiP$:S,inFullscreen$:g,pause$:E,playing$:y}=Ye(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$:E,tracks$:this.videoTracks$.pipe(r.map(v=>v.map(({track:b})=>b)))}),this.subscription.add(je(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Xe(this.video,t.playbackRate,m,i)),this.subscription.add(S.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(M.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=ye(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,se.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(M.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(M.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}Ge(this.video),this.params.output.element$.next(void 0)}}var Kt=s=>{switch(s){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}};const Dr=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 Ze=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!Dr(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return Dr(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function ne(){return r.now()}function Qn(s){return ne()-s}function Rr(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,l,d=!1)=>{a(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 Dp(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Pi(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,p=!1,f="arraybuffer",m=7e3,S=2e3,g=()=>{if(d)return;r.assertNonNullable(c);const _=Qn(c);let I;if(_<S){I=S-_,setTimeout(g,I);return}S*=2,S>m&&(S=m),o&&o.abort(),o=new a,k()};const E=_=>(n=_,V),y=_=>(h=_,V),v=()=>(f="json",V),b=()=>{if(!d){if(--u>=0){g(),i&&i();return}d=!0,h&&h(),t&&t()}},T=_=>(p=_,V),k=()=>{c=ne(),o=new a,o.open("get",s);let _=0,I,q=0;const C=()=>(r.assertNonNullable(c),Math.max(c,Math.max(I||0,q||0)));if(n&&o.addEventListener("progress",A=>{const D=ne();n.updateChunk&&A.loaded>_&&(n.updateChunk(C(),A.loaded-_),_=A.loaded,I=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>b())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const A=o.status;if(A>=200&&A<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(C(),D)}h&&h(),o&&e(o.response)}else b()}),o.addEventListener("error",()=>{b()}),p){const A=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=ne(),o.removeEventListener("readystatechange",A))};o.addEventListener("readystatechange",A)}return o.responseType=f,o.send(),V},V={withBitrateReporting:E,withParallel:T,withJSONResponse:v,withRetryCount:_=>(u=_,V),withRetryInterval:(_,I)=>(r.isNonNullable(_)&&(S=_),r.isNonNullable(I)&&(m=I),V),withTimeout:_=>(l=_,V),withFinally:y,send:k,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return V}const Rp=100,Cp=2e3,Ip=500;let xp=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-Ip;if(t-e>Cp){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=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;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*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(a)}/${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>Rp&&(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 Np{constructor(e,t,i,a,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=a,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=ne(),a=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=ne()-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=Pi(t,n,()=>a("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=ne()}_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=ne();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,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=a,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=a,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 pi=1e4,fi=3,Lp=300,Op=2e3,Bp=6e4,Mp=10,Vp=1,Fp=500;class Up{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 xp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Rr(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=Rr(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 a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,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)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{Dp(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 Np(fi,pi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const b=n&&(!c||c===this.rep);return b||t("Not running!"),b},p=(b,T,k)=>{d&&d.abort(),d=Pi(this.urlResolver.resolve(b,!1),T,k,()=>this._retryCallback()).withTimeout(pi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fi).withFinally(()=>{d=null}).send()},f=(b,T,k)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),T,k,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=b=>{const T=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${T}=>${b}`),i.playbackRate=b)},S=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const k=ne()-1e4;let N=0;for(let R=0;R<this.bufferStates.length;R++){const x=this.bufferStates[R];b=Math.min(b,x.buf),x.ts<k&&N++}this.bufferStates.splice(0,N),t(`update playback rate; minBuffer=${b} drop=${N} jitter=${this.sourceJitter}`);let U=b-Vp;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?m(1.15):U>1?m(1.1):U>.3?m(1.05):m(1)}},E=b=>{let T;const k=()=>T&&T.start?T.start.length:0,N=A=>T.start[A]/1e3,U=A=>T.dur[A]/1e3,R=A=>T.fragIndex+A,x=(A,D)=>({chunkIdx:R(A),startTS:N(A),dur:U(A),discontinuity:D}),V=()=>{let A=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,j=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=D;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ee=T.dur.length-1;for(;ee>=0&&(Z-=T.dur[ee],!(Z<=0));--ee);A=Math.min(ee,T.dur.length-1-j),A=Math.max(A,0)}return x(A,!0)},_=A=>{const D=k();if(!(D<=0)){if(r.isNonNullable(A)){for(let j=0;j<D;j++)if(N(j)>A)return x(j)}return V()}},I=A=>{const D=k(),j=A?A.chunkIdx+1:0,Z=j-T.fragIndex;if(!(D<=0)){if(!A||Z<0||Z-D>Mp)return t(`Resync: offset=${Z} bChunks=${D} chunk=`+JSON.stringify(A)),V();if(!(Z>=D))return x(j-T.fragIndex,!1)}},q=(A,D,j)=>{u&&u.abort(),u=Pi(this.urlResolver.resolve(A,!0,this.lowLatency),D,j,()=>this._retryCallback()).withTimeout(pi).withRetryCount(fi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,D)=>{q(b,j=>{if(!h())return;T=j;const Z=!!T.lowLatency;Z!==this.lowLatency&&S(Z);let ee=0;for(let ue=0;ue<T.dur.length;++ue)ee+=T.dur[ue];ee>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(_(D))},()=>this._handleNetworkError())},nextChunk:I}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:b=>{const{videoElement:T,logger:k}=this.params;let N=E(e.jidxUrl),U,R,x,V,_=0,I,q,C;const A=()=>{I&&(clearTimeout(I),I=void 0);const H=Math.max(Fp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),oe=_+H,he=ne(),de=Math.min(1e4,oe-he);_=he;const pe=()=>{u||h()&&N.seek(()=>{h()&&(_=ne(),D(),A())})};de>0?I=window.setTimeout(()=>{this.paused?A():pe()},de):pe()},D=()=>{let H;for(;H=N.nextChunk(V);)V=H,ke(H);const oe=N.nextChunk(x);if(oe){if(x&&oe.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?A():(y(),this._initPlayerWith(e));return}ue(oe)}else A()},j=(H,oe)=>{if(!h()||!this.sourceBuffer)return;let he,de,pe;const ct=et=>{window.setTimeout(()=>{h()&&j(H,oe)},et)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),ct(100);else{const et=ne(),ht=T.currentTime;!this.paused&&T.buffered.length>1&&q===ht&&et-C>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),q!==ht&&(q=ht,C=et);const pt=this._getBufferSizeSec();if(pt>30)k(`Buffered ${pt} seconds; delaying appendBuffer`),ct(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:pt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),oe&&oe()}catch(Xt){if(Xt.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),pe=this.sourceBuffer.buffered.length,pe!==0&&(he=this.sourceBuffer.buffered.start(0),de=ht,de-he>4&&this.sourceBuffer.remove(he,de-3)),ct(1e3);else throw Xt}}},Z=()=>{R&&U&&(k([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(x)]),j(R,function(){R=null,D()}))},ee=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),ue=H=>{h()&&f(ee(H),(oe,he)=>{if(h()){if(he/=1e3,R=oe,x=H,o=H.startTS,he){const de=Math.min(10,H.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*de:de}Z()}},()=>this._handleNetworkError())},ke=H=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(H),!1)))},qe=H=>{h()&&(e.cachedHeader=H,j(H,()=>{U=!0,Z()}))};n=!0,N.seek(H=>{if(h()){if(_=ne(),!H){A();return}V=H,!r.isNullable(b)||H.startTS>b?ue(H):(x=H,D())}},b),e.cachedHeader?qe(e.cachedHeader):p(e.headerUrl,qe,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.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,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let p,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(f=this._getBufferSizeSec(),m=h/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}p=this._selectQuality(h),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(p,f)=>{const m=ne();if(this.chunkRateEstimator.addInterval(p,m,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-p,speed:g}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Qn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,p)=>{const f=n.updateChunk(h,p);return f&&u(),f},notifySwitch:h=>{const p=ne();h<l&&(o=p),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=Pi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(pi).withRetryCount(fi).withRetryInterval(Lp,Op).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Ze(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&a.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))},Bp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var O;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(O||(O={}));const jp=[O.PAUSED,O.PLAYING,O.READY],Hp=[O.PAUSED,O.PLAYING,O.READY];class Gp{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(O.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new ji,this._dashCb=a=>{var n,o,l,d;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,c=[];for(const h of u){const p=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),f=(o=Kt(h.name))!==null&&o!==void 0?o:r.videoSizeToQuality(h.video),m=h.bitrate/1e3,S={...h.video};if(!f)continue;const g={id:p,quality:f,bitrate:m,size:S};c.push({track:g,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===O.MANIFEST_READY&&this.videoState.setState(O.MANIFEST_READY);break}case"qualitySwitch":{const u=a.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),r.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{const a=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: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){a!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(O.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Hp.includes(a)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===B.Requested&&jp.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case O.STOPPED:this.videoState.startTransitionTo(O.MANIFEST_READY),this.dash.attachSource(ye(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(O.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);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(ye(this.params.source.url,h))}return;default:return r.assertNever(a)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=He(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(le(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=Ye(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(r.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===O.READY&&this.videoState.setState(O.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(O.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(O.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Xe(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:a}})=>{const n=a&&r.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case O.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case O.MANIFEST_READY:case O.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case O.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case O.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.observableFrom(["init"])).pipe(r.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),Ge(this.video)}createLiveDashPlayer(){const e=new Up({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,a,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=(a=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&r.isNonNullable(d)?d:(n=Rt(l.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||n===void 0?void 0:n.id,h=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.videoTrack.getState(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((h&&c||c!==p)&&this.setVideoTrack(c),f&&this.setAutoQuality(u),h||f||c!==p){const m=(o=l.find(({track:S})=>S.id===c))===null||o===void 0?void 0:o.representation;r.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:a})=>a.id===e))===null||t===void 0?void 0:t.representation;r.assertNonNullable(i,`No such representation ${e}`),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(),a=t===exports.PlaybackState.PAUSED&&i===O.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ye(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var Kn=s=>{var e,t;const i=s.get("X-Delivery-Type"),a=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Ke=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const a=s.start(i)*1e3,n=s.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Yp=s=>{const e=document.createElement("a");return e.href=s,e.origin},qp=s=>{const e=document.createElement("a");return e.href=s,e.host};class Jn{constructor(e,t=[],i,a,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=a,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,a,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${(a=this._xhr)===null||a===void 0?void 0:a.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(p=>p.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 a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(qp(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",a,!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 Ri{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 a=this._sourceBuffer.buffered;let n=0;for(let o=0,l=a.length;o<l;o++)n+=a.end(o)-a.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,a,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,p=0;const f=S=>{a(Ri._str2ua(S.substr(d))),d=S.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=Pt(m)),this._lastXhr=new Jn(m,e.failoverHosts,S=>{this._lastXhr=void 0,f(S);const g=Date.now()-u;this._params.onBandwidthChange({size:S.length,duration:g,speed:8*S.length/(g/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),n==null||n()},S=>{if(S.length-d>l&&f(S),h===0){h=Date.now();return}p=S.length-c;const g=Date.now()-h;p>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:p,duration:g,speed:8*p/(g/1e3)}),p=0,c=S.length,h=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},o,(S,g,E)=>this._params.onError(S,g,E))})}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=Ri._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 zp{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},a=t.exec(e),n=(a==null?void 0:a[1])==="-"?-1:1,o={years:i(a==null?void 0:a[2],n),months:i(a==null?void 0:a[3],n),weeks:i(a==null?void 0:a[4],n),days:i(a==null?void 0:a[5],n),hours:i(a==null?void 0:a[6],n),minutes:i(a==null?void 0:a[7],n),seconds:i(a==null?void 0:a[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=Pt(i)),new Jn(i,t,a=>{this.attachManifest(a,t,Yp(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,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,p,f,m,S,g,E,y,v,b,T,k,N,U,R,x,V,_;const I=u.getElementsByTagName("SegmentBase")[0],q=I&&o(I,"indexRange").split("-"),C=I&&I.getElementsByTagName("Initialization")[0],A=C&&o(C,"range").split("-");if(!A||!q){const ke=u.parentElement;if((ke==null?void 0:ke.getAttribute("contentType"))==="text"){const qe=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,H=(i?i+"/":"")+((m=(f=(p=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||p===void 0?void 0:p.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),oe=(S=ke.getAttribute("lang"))!==null&&S!==void 0?S:void 0;H&&d.push({id:qe,url:H,language:oe})}return}const D=.1,j=Number((g=u.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),Z=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const ue=(y=(E=u.attributes.getNamedItem("frameRate"))===null||E===void 0?void 0:E.value)!==null&&y!==void 0?y:void 0;ee=ue?Sa(ue):void 0,l.push({width:Number((v=u.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((b=u.attributes.getNamedItem("height"))===null||b===void 0?void 0:b.value),bandwidth:j,baseURL:Z,failoverHosts:t,indexFrom:Number(q[0]),indexTo:Number(q[1]),initFrom:Number(A[0]),initTo:Number(A[1]),codecs:(k=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&k!==void 0?k:void 0,mimeType:(U=(N=u.attributes.getNamedItem("mimeType"))===null||N===void 0?void 0:N.value)!==null&&U!==void 0?U:void 0,fps:ee,bufferSize:D*j/8,bufferLength:D,name:(x=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&x!==void 0?x:void 0,id:(_=(V=u.attributes.getNamedItem("id"))===null||V===void 0?void 0:V.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 p=document.createElement("track");h&&p.setAttribute("src",h),u&&p.setAttribute("id",u),c&&p.setAttribute("srclang",c),this._video.appendChild(p)}),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,a=>{let n=e.initTo-e.initFrom+1;if(!a.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(a.buffer,0,n);const o=new DataView(a.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 p=0;p<c;p+=1){const f=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:f-1}),u=f,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,a=>{this._params.onResponseHeaders(a),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 a,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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const c=this._appendVector[String(u.fromTime)];c!==a&&(a=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}h=f.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==f.to&&(n=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);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 Ri({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,a=!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=a||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),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,a.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||r.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 a;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!a||o.fromTime<a.fromTime)&&(a=o)}if(!a){const n=i[i.length-1];if(e>n.toTime)return n}return a}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const a=i[i.length-1];return e.fromTime===a.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var F;(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"})(F||(F={}));const Wp=[F.PAUSED,F.PLAYING];class Qp{constructor(e){this.videoState=new K(F.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.elementSize$=new r.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var a,n,o;const l=[];for(const d of t){const u=(n=(a=d.name)!==null&&a!==void 0?a:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Kt(d.name))!==null&&o!==void 0?o:r.videoSizeToQuality(d),h=d.bandwidth/1e3,p={width:d.width,height:d.height},f=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:p,fps:f};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(F.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const a=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return r.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),a=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: ${a}; seekState: ${JSON.stringify(o)};`}),a===exports.PlaybackState.STOPPED){t!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(F.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===B.Requested&&Wp.includes(t)&&this.seek(o.position,o.forcePrecise),t){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_LOADED),this.prepare();return;case F.MANIFEST_LOADED:this.videoState.startTransitionTo(F.INITIAL_REPRESENTATION_SELECTED);return;case F.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(F.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case F.METADATA_LOADED:this.videoState.startTransitionTo(F.READY),this.dash.updateRefsForCurrentTime();return;case F.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(F.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed());return;case F.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(F.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case F.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=He(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(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new dp(this.video),this.dash=new zp({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,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:r.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:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},a=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Ye(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(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===F.PLAYING||this.videoState.getState()===F.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Xe(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(r.map(l=>l.map(({track:d})=>d)))}),o(Di(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===F.READY&&this.videoState.setState(F.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(F.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(F.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:r.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(r.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$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),g=a();p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to);let E;if(!g&&r.isNonNullable(f))E=f;else{const y=Ke(this.video.buffered,this.video.currentTime*1e3),v=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(y/v,1);E=(d=Rt(h.map(({track:k})=>k),{container:S,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:b,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:k})=>k===c))===null||l===void 0?void 0:l.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||d===void 0?void 0:d.id;const T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to)}return r.isNonNullable(E)?(u=h.find(({track:y})=>y.id===E))===null||u===void 0?void 0:u.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(l=>l.to===F.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(F.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?l.height<=d.height:l===d)).subscribe(l=>{const d=Ke(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(le(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Kn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.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(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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),Ge(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 r.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Ze(this.video).then(e=>{e||(this.videoState.setState(F.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}var ae;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(ae||(ae={}));var Ci;(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"})(Ci||(Ci={}));var me;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(me||(me={}));var G;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(G||(G={}));var At;(function(s){s.MP4="mp4",s.WEBM="webm"})(At||(At={}));var Ii;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Ii||(Ii={}));var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));class Cr{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 a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];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 Xn extends Cr{constructor(){super(),this.listeners||Cr.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 Zn=class{constructor(){Object.defineProperty(this,"signal",{value:new Xn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){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(a){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&&(Zn.prototype[Symbol.toStringTag]="AbortController",Xn.prototype[Symbol.toStringTag]="AbortSignal");function eo(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 Kp(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!eo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const p=new t(u,c);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},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(f){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const p=new Promise((f,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,o(d,u)])}return o(d,u)},Request:n}}const Gi=eo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),to=Gi?Kp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Yt=Gi?to.fetch:window.fetch;Gi?to.Request:window.Request;const $t=Gi?Zn:window.AbortController;var Zs=(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 Jp=(s,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Xp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ir=Xp?Jp:window.requestIdleCallback;var ks,Ps;let io=!1;try{io=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt((Ps=(ks=navigator.userAgent.match(/Version\/(\d+)/))===null||ks===void 0?void 0:ks[1])!==null&&Ps!==void 0?Ps:"",10)<16}catch(s){console.error(s)}class Zp{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.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:r.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 a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;io&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!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:r.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:r.assertNever(t)}}}var xr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class Ie{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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 so extends Ie{}class ef extends Ie{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 tf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class sf extends Ie{constructor(e){super(e),this.data=this.content}}class Jt extends Ie{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class af extends Jt{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 a=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class rf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class nf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}var nt;(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"})(nt||(nt={}));class of extends Jt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=nt.MONOSCOPIC;break;case 1:this.stereoMode=nt.TOP_BOTTOM;break;case 2:this.stereoMode=nt.LEFT_RIGHT;break;case 3:this.stereoMode=nt.STEREO_CUSTOM;break;case 4:this.stereoMode=nt.RIGHT_LEFT;break}this.cursor+=1}}class lf extends Jt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class uf extends Jt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class df extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class cf extends Jt{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 hf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class pf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}const ff={ftyp:ef,moov:tf,mdat:sf,sidx:af,trak:rf,mdia:df,tkhd:cf,minf:hf,sv3d:nf,st3d:of,prhd:lf,proj:pf,equi:uf,unknown:so};class mf{createBox(e,t){const i=ff[e];return i?new i(t):new so(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Yi.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Yi=new mf;function jt(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,a=[];for(;i<s.byteLength;){const n=t.decode(new DataView(s.buffer,i,1));if(n===e[a.length]?a.push(n):a=[],a.length===4&&a.join("")===e){const l=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+l>s.byteLength?null:Yi.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function vf(s,e){const t=[];let i=0;for(;i<s.byteLength;){const a=jt(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(a)t.push(a),i+=a.size+a.source.byteOffset;else break}return t}function Ct(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Yi.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Sf=new TextDecoder("ascii"),bf=s=>Sf.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",gf=s=>{const e=Yi.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:G.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},yf=s=>{const e=vf(s,"mdat");if(e.length){const t=e.reduce((i,a)=>i+a.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},Tf=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Ii.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(jt(s,"sv3d")){e.is3dVideo=!0;const i=jt(s,"st3d");i&&(e.stereoMode=i.stereoMode);const a=jt(s,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=jt(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},Ef={validateData:bf,parseInit:Tf,getIndexRange:()=>{},parseSegments:gf,parseFeedableSegmentChunk:yf};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 w;(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"})(w||(w={}));const Nr={[$.EBML]:{type:w.Master},[$.EBMLVersion]:{type:w.UnsignedInteger},[$.EBMLReadVersion]:{type:w.UnsignedInteger},[$.EBMLMaxIDLength]:{type:w.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[$.DocType]:{type:w.String},[$.DocTypeVersion]:{type:w.UnsignedInteger},[$.DocTypeReadVersion]:{type:w.UnsignedInteger},[$.Void]:{type:w.Binary},[$.Segment]:{type:w.Master},[$.SeekHead]:{type:w.Master},[$.Seek]:{type:w.Master},[$.SeekID]:{type:w.Binary},[$.SeekPosition]:{type:w.UnsignedInteger},[$.Info]:{type:w.Master},[$.TimestampScale]:{type:w.UnsignedInteger},[$.Duration]:{type:w.Float},[$.Tracks]:{type:w.Master},[$.TrackEntry]:{type:w.Master},[$.Video]:{type:w.Master},[$.Projection]:{type:w.Master},[$.ProjectionType]:{type:w.UnsignedInteger},[$.ProjectionPrivate]:{type:w.Master},[$.Chapters]:{type:w.Master},[$.Cluster]:{type:w.Master},[$.Timestamp]:{type:w.UnsignedInteger},[$.SilentTracks]:{type:w.Master},[$.SilentTrackNumber]:{type:w.UnsignedInteger},[$.Position]:{type:w.UnsignedInteger},[$.PrevSize]:{type:w.UnsignedInteger},[$.SimpleBlock]:{type:w.Binary},[$.BlockGroup]:{type:w.Master},[$.EncryptedBlock]:{type:w.Binary},[$.Attachments]:{type:w.Master},[$.Tags]:{type:w.Master},[$.Cues]:{type:w.Master},[$.CuePoint]:{type:w.Master},[$.CueTime]:{type:w.UnsignedInteger},[$.CueTrackPositions]:{type:w.Master},[$.CueTrack]:{type:w.UnsignedInteger},[$.CueClusterPosition]:{type:w.UnsignedInteger},[$.CueRelativePosition]:{type:w.UnsignedInteger},[$.CueDuration]:{type:w.UnsignedInteger},[$.CueBlockNumber]:{type:w.UnsignedInteger},[$.CueCodecState]:{type:w.UnsignedInteger},[$.CueReference]:{type:w.Master},[$.CueRefTime]:{type:w.UnsignedInteger}},ao=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=xi(s,t),a=i in Nr,n=a?Nr[i].type:w.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=xi(d),h=u*2**((l-1)*8)+c,p=t+l;let f;return p+h>s.byteLength?f=new DataView(s.buffer,s.byteOffset+p):f=new DataView(s.buffer,s.byteOffset+p,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:p,tagSize:p+h,value:f,valueSize:h}},xi=(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},De=(s,e)=>{switch(e){case w.SignedInteger:return s.getInt8(0);case w.UnsignedInteger:return xi(s);case w.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(s);case w.UTF8:return new TextDecoder("utf-8").decode(s);case w.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case w.Master:return s;case w.Binary:return s;default:r.assertNever(e)}},wt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=ao(i);if(!e(a))return;a.type===w.Master&&wt(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},$f=s=>{if(s.getUint32(0)!==$.EBML)return!1;let e,t,i;const a=ao(s);return wt(a.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=De(l,o):n===$.DocType?t=De(l,o):n===$.DocTypeReadVersion&&(i=De(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},ro=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],kf=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],Pf=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return wt(s,({tag:p,type:f,value:m,valueSize:S})=>{if(p===$.SeekID){const g=De(m,f);u=xi(g)}else p!==$.SeekPosition&&(u=void 0);return p===$.Segment?(e=m.byteOffset,t=m.byteOffset+S):p===$.Info?n=!0:p===$.SeekHead?o=!0:p===$.TimestampScale?i=De(m,f):p===$.Duration?a=De(m,f):p===$.SeekPosition&&u===$.Cues?d=De(m,f):p===$.Tracks?wt(m,({tag:g,type:E,value:y})=>g===$.ProjectionType?(c=De(y,E)===1,!1):!0):n&&o&&ro.includes(p)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"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(a/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:Ii.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Af=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},wf=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return wt(s,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&a(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=De(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=De(u,d));break;default:t&&ro.includes(l)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:G.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},_f=s=>{let e=0,t=!1;try{wt(s,i=>i.tag===$.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):kf.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},Df={validateData:$f,parseInit:Pf,getIndexRange:Af,parseSegments:wf,parseFeedableSegmentChunk:_f},no=1e4,Rf=3e4,Cf=5e3,If=no,xf=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?Kt(n):void 0)!==null&&o!==void 0?o:r.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},Nf=({id:s,bitrate:e})=>({id:s,bitrate:e}),Lf=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=we(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:we(s,-1)},Of=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),mi=s=>{const e=[];let t=0,i=s.length-1;for(;t<no&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class Lr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.playingRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.isSeekingLive=!1,this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new $t,this.destroyAbortController=new $t,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(c){const h=this.representations.get(c);r.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(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.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,xr(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(h,"high",!0);const p=this.initData.get(h.id),f=this.segments.get(h.id),m=this.parsedInitData.get(h.id);r.assertNonNullable(p,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),p instanceof ArrayBuffer&&(this.searchGaps(f,h),yield this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;this.switchingToRepresentationId=c;const h=this.representations.get(c);r.assertNonNullable(h,`No such representation ${c}`);let p=this.segments.get(c),f=this.initData.get(c);if(r.isNullable(f)||r.isNullable(p)?yield this.loadInit(h,"high",!1):f instanceof Promise&&(yield f),p=this.segments.get(c),r.assertNonNullable(p,"No segments for starting representation"),f=this.initData.get(c),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal);const m=this.getCurrentPosition();r.isNonNullable(m)&&(this.searchGaps(p,h),this.maintain(m))}.bind(this)),this.seekLive=r.abortable(this.destroyAbortController.signal,async function*(c){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const g of this.representations.keys()){const E=c.find(b=>b.id===g);E&&this.representations.set(g,E);const y=this.representations.get(g);if(!y)return;const v=mi(y.segmentReference.segments);this.segments.set(y.id,v)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,p=this.representations.get(h);r.assertNonNullable(p);const f=mi(p.segmentReference.segments),m=this.initData.get(p.id);if(r.assertNonNullable(m,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(m instanceof ArrayBuffer))return;const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal)),this.searchGaps(f,p),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 At.MP4:this.containerParser=Ef;break;case At.WEBM:this.containerParser=Df;break;default:r.assertNever(i)}this.initData=new Map(a.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.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 $t,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Ke(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&c>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&xr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ke(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&&a)if(l.includes(a))u="high";else{const c=we(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===G.FED&&!l.length&&Ke(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=we(i,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const a of e)a.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from}),i=a.time.to;r.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(a=>a.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,a,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:G.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(a=we(d,-1))===null||a===void 0?void 0:a.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=mi(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,a;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(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a: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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{const S=p<=i&&f>=i,g=p>i||S||m===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+E||f<=i+E;return(h===G.NONE||h===G.PARTIALLY_EJECTED&&g&&y&&this.sourceBuffer&&!Zs(this.sourceBuffer.buffered,i))&&g&&y});if(a===-1)return[];if(t!==me.BYTE_RANGE)return e.slice(a,a+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=a;h<n.length&&(o<=u||l<=c);h++){const p=n[h];if(o+=p.byte.to+1-p.byte.from,l+=p.time.to+1-p.time.from,p.status===G.NONE||p.status===G.PARTIALLY_EJECTED)d.push(p);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:l}=t.segmentReference;switch(l){case me.BYTE_RANGE:{a=t.segmentReference.url,n={from:we(e,0).byte.from,to:we(e,-1).byte.to};break}case me.TEMPLATE:{const u=we(e,0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:r.assertNever(l)}for(const u of o)u.status=G.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await r.abortable(d,async function*(){const u=r.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(a,{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:r.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 a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(i=Ke((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var p;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=G.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(p=this.segments.get(f.id))!==null&&p!==void 0?p:[])m.status===G.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=G.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:p}=h,f=u===me.BYTE_RANGE,m=f?p.byte.to-p.byte.from+1:c;if(h.representationId!==t||!(!f||p.byte.from>=i&&p.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const g=f?p.byte.from-i:0,E=f?p.byte.to-i:e.byteLength,y=g<a,v=E<=a;if(p.status===G.DOWNLOADING&&y&&v){p.status=G.DOWNLOADED,this.activeSegments.delete(h);const b=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(b,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(m,a-g),h.loadedBytes>h.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?b:this.containerParser.parseFeedableSegmentChunk(b);T!=null&&T.byteLength&&(p.status=G.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(k=>{if(n.aborted)o();else if(k)h.fedBytes+=T.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ir(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.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,a)).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?mi(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:r.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||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=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;a+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status===G.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){a=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)||a>t)break;c.status===G.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===G.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===G.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let a={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){a=void 0;break}l>i.time.from&&l<i.time.to&&(a.from=l),o<i.time.to&&o>i.time.from&&(a.to=o)}}a&&a.to-a.from>1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ir(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==G.FED&&n!==G.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.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?a.status=G.PARTIALLY_EJECTED:a.status=G.NONE)}}}var Et;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Et||(Et={}));class Bf{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new $t,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=Pt(n));const o=yield Yt(n,{signal:this.abortAllController.signal}).catch(Vt);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?Et.HEADER:Et.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,p,f,m;let S=a;const g=new Headers;if(o)switch(n){case Et.HEADER:{g.append("Range",`bytes=${o.from}-${o.to}`);break}case Et.PARAM:{const D=new URL(S,location.href);D.searchParams.append("bytes",`${o.from}-${o.to}`),S=D.toString();break}default:r.assertNever(n)}this.requestQuic&&(S=Pt(S));let E=this.abortAllController.signal,y;if(u){const D=new $t;if(y=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{D.abort()}catch(j){Vt(j)}}),this.abortAllController.signal.aborted||u.aborted)try{D.abort()}catch(j){Vt(j)}E=D.signal}const v=r.now(),b=yield Yt(S,{priority:d,headers:g,signal:E}).catch(Vt),T=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-v),!b)return y==null||y.unsubscribe(),null;if(!b.ok||!b.body)return y==null||y.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const k=parseInt((p=b.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||o&&o.to-o.from+1||NaN;if(!k){const D=yield b.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(D.byteLength,r.now()-T),l==null||l(new DataView(D),D.byteLength),y==null||y.unsubscribe(),D}if(!l&&!c)return y==null||y.unsubscribe(),b.arrayBuffer();const[N,U]=b.body.tee(),R=N.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(U));let x=0;const V=new ArrayBuffer(k),_=new Uint8Array(V),I=new DataView(V);let q=!1;const C=D=>{y==null||y.unsubscribe(),q=!0,Vt(D)},A=r.abortable(E,async function*({done:D,value:j}){if(x===0&&this.lastRequestFirstBytes$.next(r.now()-v),E.aborted){y==null||y.unsubscribe();return}!D&&j&&(_.set(j,x),x+=j.byteLength,l==null||l(I,x),yield R==null?void 0:R.read().then(A,C))}.bind(this));return yield R==null?void 0:R.read().then(A,C),y==null||y.unsubscribe(),q?null:V}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==me.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,p=!1,f,m;a.indexRange&&(f=a.indexRange.from,m=a.indexRange.to,p=u+1===f,p&&(c=Math.min(f,d),h=Math.max(m,u))),c=Math.min(c,0);const S=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!S)return null;const g=new DataView(S,d-c,u-c+1);if(!n.validateData(g))throw new Error("Invalid media file");const E=n.parseInit(g),y=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(E);if(!y)throw new ReferenceError("No way to load representation index");let v;if(p)v=new DataView(S,y.from-c,y.to-y.from+1);else{const T=yield this.fetch(a.url,{range:y,priority:o,measureThroughput:!1});if(!T)return null;v=new DataView(T)}const b=n.parseSegments(v,E,y);return{init:E,dataView:new DataView(S),segments:b}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==me.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:a.segments.map(u=>({...u,status:G.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}=Kn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;const{type:o}=e;switch(o){case me.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case me.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Vt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Mf=ot,Vf=Li,Ff=$e,Uf=Ff("match"),jf=function(s){var e;return Mf(s)&&((e=s[Uf])!==void 0?!!e:Vf(s)=="RegExp")},Hf=Ui,Gf=String,Yf=function(s){if(Hf(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Gf(s)},qf=ut,zf=function(){var s=qf(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},Wf=Fe,Qf=Ue,Kf=na,Jf=zf,Or=RegExp.prototype,Xf=function(s){var e=s.flags;return e===void 0&&!("flags"in Or)&&!Qf(s,"flags")&&Kf(Or,s)?Wf(Jf,s):e},ga=Ve,Zf=Mi,em=Math.floor,As=ga("".charAt),tm=ga("".replace),ws=ga("".slice),im=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sm=/\$([$&'`]|\d{1,2})/g,am=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=sm;return a!==void 0&&(a=Zf(a),d=im),tm(n,d,function(u,c){var h;switch(As(c,0)){case"$":return"$";case"&":return s;case"`":return ws(e,0,t);case"'":return ws(e,o);case"<":h=a[ws(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>l){var f=em(p/10);return f===0?u:f<=l?i[f-1]===void 0?As(c,1):i[f-1]+As(c,1):u}h=i[p-1]}return h===void 0?"":h})},rm=Fi,nm=Fe,ya=Ve,Br=sa,om=ve,lm=Oi,um=jf,gt=Yf,dm=Bi,cm=Xf,hm=am,pm=$e,fm=pm("replace"),mm=TypeError,oo=ya("".indexOf),vm=ya("".replace),Mr=ya("".slice),Sm=Math.max,Vr=function(s,e,t){return t>s.length?-1:e===""?t:oo(s,e,t)};rm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Br(this),a,n,o,l,d,u,c,h,p,f=0,m=0,S="";if(!lm(e)){if(a=um(e),a&&(n=gt(Br(cm(e))),!~oo(n,"g")))throw mm("`.replaceAll` does not allow non-global regexes");if(o=dm(e,fm),o)return nm(o,e,i,t);if(a)return vm(gt(i),e,t)}for(l=gt(i),d=gt(e),u=om(t),u||(t=gt(t)),c=d.length,h=Sm(1,c),f=Vr(l,d,0);f!==-1;)p=u?gt(t(d,f,l)):hm(d,l,f,[],void 0,t),S+=Mr(l,m,f)+p,m=f+c,f=Vr(l,d,f+h);return m<l.length&&(S+=Mr(l,m)),S}});var bm=Wn,gm=bm("String","replaceAll"),ym=gm,Tm=ym,Em=Tm,$m=Em,Fr=ia($m);const Ur=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),a=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],a),hours:e(i==null?void 0:i[6],a),minutes:e(i==null?void 0:i[7],a),seconds:e(i==null?void 0:i[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},_s=(s,e)=>{let t=s;t=Fr(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=Fr(t,o,(l,d)=>r.isNullable(n)?l:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},km=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,p,f,m,S,g,E,y,v,b,T,k,N,U,R,x,V,_,I,q,C,A,D,j,Z,ee,ue,ke,qe,H;const he=new DOMParser().parseFromString(s,"application/xml"),de={video:[],audio:[],text:[]},pe=he.children[0],ct=pe.getElementsByTagName("Period")[0],et=ct.children,ht=pe.getAttribute("type")==="dynamic",pt=pe.getAttribute("availabilityStartTime"),Xt=pt?new Date(pt).getTime():void 0;let tt;const Ta=pe.getAttribute("mediaPresentationDuration"),Ea=ct.getAttribute("duration"),qi=pe.getElementsByTagName("vk:Attrs")[0],$a=qi==null?void 0:qi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Ta)tt=Ur(Ta);else if(Ea){const Se=Ur(Ea);r.isNonNullable(Se)&&(tt=Se)}else $a&&(tt=parseInt($a,10));let vo=0;const zi=(i=(t=pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],So=zi.includes(Ci.WEBM_AS_IN_FFMPEG)||zi.includes(Ci.WEBM_AS_IN_SPEC)?At.WEBM:At.MP4;for(const Se of et){const Zt=Se.getAttribute("mimeType"),bo=Se.getAttribute("codecs"),ka=(a=Se.getAttribute("contentType"))!==null&&a!==void 0?a:Zt==null?void 0:Zt.split("/")[0],go=(o=(n=Se.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Pa=Se.querySelectorAll("Representation"),yo=Se.querySelector("SegmentTemplate");if(ka===ae.TEXT){for(const te of Pa){const ze=te.getAttribute("id")||"",ei=Se.getAttribute("lang"),ft=(u=(d=(l=te.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Wi=new URL(ft,e).toString(),Qi=ze.includes("_auto");de[ae.TEXT].push({id:ze,lang:ei,isAuto:Qi,kind:ae.TEXT,url:Wi})}continue}for(const te of Pa){const ze=(c=te.getAttribute("mimeType"))!==null&&c!==void 0?c:Zt,ei=(p=(h=te.getAttribute("codecs"))!==null&&h!==void 0?h:bo)!==null&&p!==void 0?p:"",ft=(m=(f=te.getAttribute("contentType"))!==null&&f!==void 0?f:ze==null?void 0:ze.split("/")[0])!==null&&m!==void 0?m:ka,Wi=(g=(S=Se.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&g!==void 0?g:[],Qi=parseInt((E=te.getAttribute("width"))!==null&&E!==void 0?E:"",10),Aa=parseInt((y=te.getAttribute("height"))!==null&&y!==void 0?y:"",10),wa=parseInt((v=te.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,_a=(b=te.getAttribute("frameRate"))!==null&&b!==void 0?b:"",To=(T=te.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Eo=_a?Sa(_a):void 0,$o=(k=te.getAttribute("id"))!==null&&k!==void 0?k:(vo++).toString(10),ko=ft==="video"?`${Aa}p`:ft==="audio"?`${wa}Kbps`:ei,Po=`${$o}@${ko}`,Ao=(R=(U=(N=te.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||U===void 0?void 0:U.trim())!==null&&R!==void 0?R:"",Da=new URL(Ao,e).toString(),wo=[...zi,...go,...Wi];let Ki;const _o=te.querySelector("SegmentBase"),it=(x=te.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:yo;if(_o){const It=(_=(V=te.querySelector("SegmentBase Initialization"))===null||V===void 0?void 0:V.getAttribute("range"))!==null&&_!==void 0?_:"",[xt,Xi]=It.split("-").map(mt=>parseInt(mt,10)),Nt={from:xt,to:Xi},Lt=(I=te.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Zi,ti]=Lt?Lt.split("-").map(mt=>parseInt(mt,10)):[],Ot=Lt?{from:Zi,to:ti}:void 0;Ki={type:me.BYTE_RANGE,url:Da,initRange:Nt,indexRange:Ot}}else if(it){const It={representationId:(q=te.getAttribute("id"))!==null&&q!==void 0?q:void 0,bandwidth:(C=te.getAttribute("bandwidth"))!==null&&C!==void 0?C:void 0},xt=parseInt((A=it.getAttribute("timescale"))!==null&&A!==void 0?A:"",10),Xi=(D=it.getAttribute("initialization"))!==null&&D!==void 0?D:"",Nt=it.getAttribute("media"),Lt=(Z=parseInt((j=it.getAttribute("startNumber"))!==null&&j!==void 0?j:"",10))!==null&&Z!==void 0?Z:1,Zi=_s(Xi,It);if(!Nt)throw new ReferenceError("No media attribute in SegmentTemplate");const ti=(ee=it.querySelectorAll("SegmentTimeline S"))!==null&&ee!==void 0?ee:[],Ot=[];let mt=0;if(ti.length){let es=Lt,xe=0;for(const Bt of ti){const We=parseInt((ue=Bt.getAttribute("d"))!==null&&ue!==void 0?ue:"",10),st=parseInt((ke=Bt.getAttribute("r"))!==null&&ke!==void 0?ke:"",10)||0,ii=parseInt((qe=Bt.getAttribute("t"))!==null&&qe!==void 0?qe:"",10);xe=Number.isFinite(ii)?ii:xe;const ts=We/xt*1e3,Ra=xe/xt*1e3;for(let si=0;si<st+1;si++){const Do=_s(Nt,{...It,segmentNumber:es.toString(10),segmentTime:(xe+si*We).toString(10)}),Ca=(Ra||0)+si*ts,Ro=Ca+ts;es++,Ot.push({time:{from:Ca,to:Ro},url:Do})}xe+=(st+1)*We,mt+=(st+1)*ts}}else if(r.isNonNullable(tt)){const xe=parseInt((H=it.getAttribute("duration"))!==null&&H!==void 0?H:"",10)/xt*1e3,Bt=Math.ceil(tt/xe);let We=0;for(let st=1;st<Bt;st++){const ii=_s(Nt,{...It,segmentNumber:st.toString(10),segmentTime:We.toString(10)});Ot.push({time:{from:We,to:We+xe},url:ii}),We+=xe}}Ki={type:me.TEMPLATE,baseUrl:Da,initUrl:Zi,totalSegmentsDurationMs:mt,segments:Ot}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ft||!ze)continue;const Ji={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[ft];Ji&&de[Ji].push({id:Po,kind:Ji,segmentReference:Ki,profiles:wo,duration:tt,bitrate:wa,mime:ze,codecs:ei,width:Qi,height:Aa,fps:Eo,quality:To})}}return{dynamic:ht,liveAvailabilityStartTime:Xt,duration:tt,container:So,representations:de}},ea=1e3,jr=["timeupdate","progress","play","seeked","stalled","waiting"];var fe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(fe||(fe={}));let Pm=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.representationSubscription=new r.Subscription,this.state$=new K(fe.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.currentVideoRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.isLive$=new r.ValueSubject(!1),this.liveDuration$=new r.ValueSubject(0),this.liveAvailabilityStartTime$=new r.ValueSubject(void 0),this.bufferLength$=new r.ValueSubject(0),this.liveLoadBufferLength$=new r.ValueSubject(0),this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new $t,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i,a){var n;this.element=t,this.manifestUrlString=ye(i,a,se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(fe.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(fe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=r.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:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!i)return this.manifest;let a;try{a=km(i!=null?i:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return null;const n=({kind:o,mime:l,codecs:d})=>{var u,c,h,p;return!!(!((c=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||c===void 0)&&c.call(u,l)&&(!((p=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||p===void 0)&&p.call(h,`${l}; codecs="${d}"`))||o===ae.TEXT)};return this.isLive$.getValue()!==a.dynamic&&(this.isLive$.next(a.dynamic),this.liveDuration$.getValue()!==a.duration&&this.liveDuration$.next(-1*((t=a.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==a.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(a.liveAvailabilityStartTime)),{...a,representations:kt(Object.entries(a.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(fe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Lr(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new Lr(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),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(r.interval(ea).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=Pr(this.manifestUrlString,se.DASH_CMAF_OFFSET_P);this.manifestUrlString=ye(this.manifestUrlString,u+1e3,se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...jr.map(l=>r.fromEvent(this.element,l))).pipe(r.throttle(ea),r.map(l=>this.element?Ke(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 p=((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 S,g;return(g=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&g!==void 0?g:0}))-p}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async d=>{r.assertNonNullable(this.element);const u=this.element.playbackRate,c=Pr(this.manifestUrlString,se.DASH_CMAF_OFFSET_P),h=Rf*u,p=If*u,f=Cf*u;l=d>l?d:l;const m=c===0&&d<f,S=c!==0&&d<h+f&&d>=h,g=c!==0&&d<h;if(g||S){const E=l-(h+p),y=Math.trunc(c+E/u);let v;d?y>0?v=y:v=0:v=c,this.manifestUrlString=ye(this.manifestUrlString,v,se.DASH_CMAF_OFFSET_P)}(m||g||S)&&(await this.updateLive(),l=0)}))}const n=r.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=r.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:n,someBufferEnded:o}).pipe(r.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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(r.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)})),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(fe.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Bf({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async seekLive(e){var t,i,a,n;r.assertNonNullable(this.element),this.manifestUrlString=ye(this.manifestUrlString,e,se.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((a=this.audioBufferManager)===null||a===void 0?void 0:a.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio))}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(fe.RUNNING),this.subscription.add(r.merge(...jr.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Zs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,a,n,o,l;r.assertNonNullable(this.element),r.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=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Zs(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(fe.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 a of this.bufferManagers)for(const n of a.gaps)a.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 a=Math.max(...i);a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class Am{constructor(e,t){this.fov=e,this.orientation=t}}class wm{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 a=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:a,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 a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 _m=`#define GLSLIFY 1
|
|
29
|
+
`}),C}return u==null||u.recordSwitch(I),I};var le=s=>new URL(s).hostname;const _p=300,Di=(s,e=_p)=>new r.Observable(t=>{const{width:i,height:a}=s.getBoundingClientRect();if(t.next({width:i,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(Bo(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),r.isNonNullable(d)&&r.isNonNullable(u)&&t.next({width:d,height:u})},e));return n.observe(s),()=>n.disconnect()});class Hi{constructor(){this.onDroopedVideoFramesLimit$=new r.Subject,this.subscription=new r.Subscription,this.playing=!1,this.tracks=[],this.forceChecker$=new r.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&&!r.isInvariantQuality(e.quality)&&this.onChangeQuality(e.quality)},this.checkDroppedFrames=()=>{var e;const{totalVideoFrames:t,droppedVideoFrames:i}=this.video.getVideoPlaybackQuality(),a=t-this.prevTotalVideoFrames,n=i-this.prevDroppedVideoFrames,o=1-(a-n)/a;!isNaN(o)&&o>0&&this.log({message:`[dropped]. current dropped percent: ${o}, limit: ${this.droppedFramesChecker.percentLimit}`}),!isNaN(o)&&o>=this.droppedFramesChecker.percentLimit&&r.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(r.fromEvent(this.video,"resize").subscribe(this.handleChangeVideoQuality));const e=r.interval(this.droppedFramesChecker.checkTime).pipe(r.filter(()=>this.playing),r.filter(()=>{const a=!!this.isForceCheckCounter;return a&&(this.isForceCheckCounter-=1),!a})),t=this.forceChecker$.pipe(r.debounce(this.droppedFramesChecker.checkTime)),i=r.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 a=(i=(t=Object.entries(this.limitCounts).filter(([,n])=>n>=this.droppedFramesChecker.countLimit).sort(([n],[o])=>r.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:a}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 Mt={};var M;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(M||(M={}));const ie=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class _r{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(M.DOWNLOADING_LIB),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.videoTracks$=new r.ValueSubject([]),this.frameRatesByFrameHeight={},this.isLive$=new r.ValueSubject(void 0),this.maxSeekBackTime$=new r.ValueSubject(1/0),this.availableFrom$=new r.ValueSubject(void 0),this.elementSize$=new r.ValueSubject(void 0),this.liveOffset=new ji,this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState(),o=this.isLive$.getValue();if(!this.videoState.getTransition()&&!(t===M.DOWNLOADING_LIB||t===M.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&t!==M.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 M.STOPPED:break;case M.PLAYING:case M.PAUSED:case M.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case M.STOPPED:this.prepare();break;case M.PLAYING:case M.PAUSED:case M.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case M.PLAYING:break;case M.PAUSED:o&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())),this.play();break;case M.READY:this.play();break;case M.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case M.PLAYING:this.pause(),this.liveOffset.pause();break;case M.PAUSED:break;case M.READY:this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=He(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(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let e=!1;const t=a=>{var n;e||this.params.output.error$.next({id:a==="timeout"?"DashJSTimedOut":"DashJSLoadingError",category:r.ErrorCategory.NETWORK,message:`Dash.js failed to load: ${(n=a==null?void 0:a.toString)===null||n===void 0?void 0:n.call(a)}`,thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(Mt.MediaPlayer=a.MediaPlayer,Mt.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Mt.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Mt.Debug,"dashjs not loaded"),this.player=Mt.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?Sa(e.frameRate+""):void 0),!0)),this.params.tuning.stripRangeHeader&&ap(this.player),tp(this.player),this.params.tuning.requestQuick&&sp(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=v=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:v})},a=(v,b)=>this.subscription.add(v.subscribe(b,i));a(Di(this.video),this.elementSize$),a(ie(this.player,"error").pipe(r.map(v=>{const b=typeof v.error=="object"?v.error.code:v.error,T=typeof v.error=="object"?v.error.message:void 0;return{id:`DashJS#${b}`,message:T}})),e.error$),a(ie(this.player,"playbackError").pipe(r.map(v=>({id:"DashJSPlayback",message:v.error}))),e.error$);const n=ie(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:v})=>v==="video"),r.map(({newQuality:v})=>{var b;return(b=this.videoTracks$.getValue().find(({bitrateInfo:T})=>T.qualityIndex===v))===null||b===void 0?void 0:b.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:v})=>v===M.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(Te(t.videoTrack,()=>{var v,b;const T=this.player.getQualityFor("video");return(b=(v=this.videoTracks$.getValue().find(({bitrateInfo:k})=>k.qualityIndex===T))===null||v===void 0?void 0:v.track)===null||b===void 0?void 0:b.id},v=>{var b;if(r.isNullable(v))return;const T=(b=this.videoTracks$.getValue().find(({track:k})=>k.id===v))===null||b===void 0?void 0:b.bitrateInfo;T&&this.player.setQualityFor("video",T.qualityIndex)},{changed$:n.pipe(r.map(v=>v==null?void 0:v.id)),onError:i}))},i)),this.subscription.add(Te(t.autoVideoTrackSwitching,()=>{var v,b,T;return(T=(b=(v=this.player.getSettings().streaming)===null||v===void 0?void 0:v.abr)===null||b===void 0?void 0:b.autoSwitchBitrate)===null||T===void 0?void 0:T.video},v=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:v}}}}),{onError:i})),a(ie(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:v})=>v==="video"),r.map(({state:v})=>v==="bufferStalled")),e.isBuffering$),a(ie(this.player,"fragmentLoadingStarted"),({mediaType:v,request:{url:b}})=>{var T,k;const N=this.player.getDashMetrics(),U=N.getLatestFragmentRequestHeaderValueByID(v,"X-Reused"),R=(T=N.getLatestFragmentRequestHeaderValueByID(v,"X-Delivery-Type"))!==null&&T!==void 0?T:exports.HttpConnectionType.HTTP1,x=(k={1:!0,0:!1}[U])!==null&&k!==void 0?k:void 0;this.params.output.httpConnectionType$.next(R),this.params.output.httpConnectionReused$.next(x),e.hostname$.next(le(b))}),a(ie(this.player,"streamInitialized"),({streamInfo:{duration:v,manifestInfo:{isDynamic:b,availableFrom:T}}})=>{this.isLive$.next(b),this.availableFrom$.next(T.getTime()),b||e.duration$.next(v);const k=[],N=this.player.getQualityFor("video");let U;for(const R of this.player.getBitrateInfoListFor("video")){const x=R.qualityIndex.toString(10),V=r.videoSizeToQuality(R),_=R.bitrate/1e3,I={width:R.width,height:R.height},q=this.frameRatesByFrameHeight[R.height];if(V){const C={id:x,quality:V,bitrate:_,size:I,fps:q};k.push({track:C,bitrateInfo:R}),R.qualityIndex===N&&(U=C)}}this.videoTracks$.next(k),e.availableVideoTracks$.next(k.map(({track:R})=>R)),U&&e.currentVideoTrack$.next(U),this.videoState.setState(M.STREAM_INITIALIZED),this.videoState.startTransitionTo(M.READY)}),a(ie(this.player,"fragmentLoadingCompleted"),({request:v})=>{if(!v.requestEndDate||!v.firstByteDate||!v.bytesLoaded)return;const b=v.requestEndDate.getTime()-v.firstByteDate.getTime(),T=v.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(T,b)}),a(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeStarted$,this.droppedFramesManager.onDroopedVideoFramesLimit$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks$.getValue().length)return;const v=this.params.dependencies.throughputEstimator.throughput$.getValue(),b=Rt(this.videoTracks$.getValue().map(({track:N})=>N),{container:this.elementSize$.getValue(),throughput:v,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to);const k=this.videoTracks$.getValue().find(({track:N})=>N===b);k!=null&&k.bitrateInfo&&this.player.setQualityFor("video",k==null?void 0:k.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:v})=>v),r.map(({maxSeekBackTime:v})=>-v/1e3)),this.params.output.duration$);const o=ie(this.player,"playbackTimeUpdated").pipe(r.map(({time:v})=>v!=null?v:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:v,currentTime:b})=>this.params.output.liveTime$.next(v+b*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(ie(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(ie(this.player,"playbackEnded"),e.endedEvent$),a(ie(this.player,"playbackProgress").pipe(r.map(()=>zn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(ie(this.player,"playbackPlaying"),()=>{this.videoState.setState(M.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)}),a(ie(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(M.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(ie(this.player,"playbackPaused"),()=>{this.videoState.setState(M.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)}),a(ie(this.player,"canPlay"),()=>{var v;((v=this.videoState.getTransition())===null||v===void 0?void 0:v.to)===M.READY&&this.videoState.setState(M.READY)}),a(this.isLive$,e.isLive$),a(Di(this.video),()=>{this.player.isReady()&&this.player.updatePortalSize()});const l=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));a(l,this.syncPlayback);const{playbackDuration$:d,ping$:u,connectionType$:c,connectionReused$:h}=ip(this.player);a(c,this.params.output.httpConnectionType$),a(h,this.params.output.httpConnectionReused$),a(d,this.maxSeekBackTime$),a(u.pipe(r.once()),e.firstBytesEvent$),a(ie(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(v=>v<60))}),({isLive:v,isShort:b})=>{const T=!v&&b;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:T}}})}),a(o.pipe(r.filter(v=>v>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(ie(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(ie(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),a(ie(this.player,"manifestLoaded"),v=>{var b,T,k,N,U,R,x;if(!((T=(b=v.data)===null||b===void 0?void 0:b.Period)===null||T===void 0)&&T.AdaptationSet){const V=[];for(const _ of(N=(k=v.data)===null||k===void 0?void 0:k.Period)===null||N===void 0?void 0:N.AdaptationSet)if(_.contentType==="text"){const I=(U=_.Representation)===null||U===void 0?void 0:U.id,q=new URL((R=_.Representation)===null||R===void 0?void 0:R.BaseURL,(x=v.data)===null||x===void 0?void 0:x.baseUri).toString(),C="internal",A=_.lang;V.push({id:I,url:q,type:C,language:A})}t.internalTextTracks.startTransitionTo(V)}}),this.subscription.add(dt(this.video,t.isLooped,i));const{volumeState$:p,looped$:f,playbackRateState$:m,inPiP$:S,inFullscreen$:g,pause$:E,playing$:y}=Ye(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$:E,tracks$:this.videoTracks$.pipe(r.map(v=>v.map(({track:b})=>b)))}),this.subscription.add(je(this.video,t.volume,p,i)),this.subscription.add(p.subscribe(e.volume$,i)),this.subscription.add(f.subscribe(e.loopedEvent$)),this.subscription.add(Xe(this.video,t.playbackRate,m,i)),this.subscription.add(S.subscribe(e.inPiP$)),this.subscription.add(g.subscribe(e.inFullscreen$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(M.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(M.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(e){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const a=ye(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,se.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(M.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(M.PAUSED),this.video.pause()}destroy(){var e;this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.droppedFramesManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(t){}Ge(this.video),this.params.output.element$.next(void 0)}}var Kt=s=>{switch(s){case"mobile":return r.VideoQuality.Q_144P;case"lowest":return r.VideoQuality.Q_240P;case"low":return r.VideoQuality.Q_360P;case"sd":case"medium":return r.VideoQuality.Q_480P;case"hd":case"high":return r.VideoQuality.Q_720P;case"fullhd":case"full":return r.VideoQuality.Q_1080P;case"quadhd":case"quad":return r.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return r.VideoQuality.Q_2160P}};const Dr=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 Ze=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!Dr(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return Dr(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function ne(){return r.now()}function Qn(s){return ne()-s}function Rr(s){const e=s.split("/"),t=e.slice(0,e.length-1).join("/"),i=/^([a-z]+:)?\/\//i,a=o=>i.test(o);return{resolve:(o,l,d=!1)=>{a(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 Dp(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Pi(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,p=!1,f="arraybuffer",m=7e3,S=2e3,g=()=>{if(d)return;r.assertNonNullable(c);const _=Qn(c);let I;if(_<S){I=S-_,setTimeout(g,I);return}S*=2,S>m&&(S=m),o&&o.abort(),o=new a,k()};const E=_=>(n=_,V),y=_=>(h=_,V),v=()=>(f="json",V),b=()=>{if(!d){if(--u>=0){g(),i&&i();return}d=!0,h&&h(),t&&t()}},T=_=>(p=_,V),k=()=>{c=ne(),o=new a,o.open("get",s);let _=0,I,q=0;const C=()=>(r.assertNonNullable(c),Math.max(c,Math.max(I||0,q||0)));if(n&&o.addEventListener("progress",A=>{const D=ne();n.updateChunk&&A.loaded>_&&(n.updateChunk(C(),A.loaded-_),_=A.loaded,I=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>b())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const A=o.status;if(A>=200&&A<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(C(),D)}h&&h(),o&&e(o.response)}else b()}),o.addEventListener("error",()=>{b()}),p){const A=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(q=ne(),o.removeEventListener("readystatechange",A))};o.addEventListener("readystatechange",A)}return o.responseType=f,o.send(),V},V={withBitrateReporting:E,withParallel:T,withJSONResponse:v,withRetryCount:_=>(u=_,V),withRetryInterval:(_,I)=>(r.isNonNullable(_)&&(S=_),r.isNonNullable(I)&&(m=I),V),withTimeout:_=>(l=_,V),withFinally:y,send:k,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return V}const Rp=100,Cp=2e3,Ip=500;let xp=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-Ip;if(t-e>Cp){let i=0,a=0;for(;this.intervals.length>0;){const n=this.intervals[0];if(n.end<=t)i+=n.end-n.start,a+=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;a+=d,n.start=t,n.bytes-=d}}}if(a>0&&i>0){const n=a*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(a)}/${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>Rp&&(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 Np{constructor(e,t,i,a,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=a,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=ne(),a=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=ne()-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=Pi(t,n,()=>a("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=ne()}_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=ne();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,a){const n={};return n.send=()=>{const o=this.activeRequests[e]||this.completeRequests[e];if(o)o._cb=t,o._errorCB=i,o._retryCB=a,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=a,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 pi=1e4,fi=3,Lp=300,Op=2e3,Bp=6e4,Mp=10,Vp=1,Fp=500;class Up{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 xp(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=Rr(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=Rr(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 a;i!==0&&(a=t.buffered.start(i-1),t.currentTime<a&&(e("Fixup stall"),t.currentTime=a))}_selectQuality(e){const{videoElement:t}=this.params;let i,a,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)?(!a||n.bitrate>a.bitrate)&&(a=n):(!i||i.bitrate>n.bitrate)&&(i=n));return a||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||r.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(e,t){const{logger:i,videoElement:a,playerCallback:n}=this.params;this.mediaSource=new window.MediaSource,i("setting video src"),a.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener("sourceopen",()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(e.codecs),this.bufferStates=[],t())}),this.videoPlayStarted=!1,a.addEventListener("canplay",()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())});const o=()=>{Dp(a,"progress",()=>{a.buffered.length?(a.currentTime=a.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 Np(fi,pi,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(e,()=>this._switchToQuality(e))}_representation(e){const{logger:t,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,l=null,d=null,u=null,c=!1;const h=()=>{const b=n&&(!c||c===this.rep);return b||t("Not running!"),b},p=(b,T,k)=>{d&&d.abort(),d=Pi(this.urlResolver.resolve(b,!1),T,k,()=>this._retryCallback()).withTimeout(pi).withBitrateReporting(this.bitrateSwitcher).withRetryCount(fi).withFinally(()=>{d=null}).send()},f=(b,T,k)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(b,!1),T,k,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},m=b=>{const T=i.playbackRate;i.playbackRate!==b&&(t(`Playback rate switch: ${T}=>${b}`),i.playbackRate=b)},S=b=>{this.lowLatency=b,t(`lowLatency changed to ${b}`),g()},g=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)m(1);else{let b=this._getBufferSizeSec();if(this.bufferStates.length<5){m(1);return}const k=ne()-1e4;let N=0;for(let R=0;R<this.bufferStates.length;R++){const x=this.bufferStates[R];b=Math.min(b,x.buf),x.ts<k&&N++}this.bufferStates.splice(0,N),t(`update playback rate; minBuffer=${b} drop=${N} jitter=${this.sourceJitter}`);let U=b-Vp;this.sourceJitter>=0?U-=this.sourceJitter/2:this.sourceJitter-=1,U>3?m(1.15):U>1?m(1.1):U>.3?m(1.05):m(1)}},E=b=>{let T;const k=()=>T&&T.start?T.start.length:0,N=A=>T.start[A]/1e3,U=A=>T.dur[A]/1e3,R=A=>T.fragIndex+A,x=(A,D)=>({chunkIdx:R(A),startTS:N(A),dur:U(A),discontinuity:D}),V=()=>{let A=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,j=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,Z=D;this.sourceJitter>1&&(Z+=this.sourceJitter-1);let ee=T.dur.length-1;for(;ee>=0&&(Z-=T.dur[ee],!(Z<=0));--ee);A=Math.min(ee,T.dur.length-1-j),A=Math.max(A,0)}return x(A,!0)},_=A=>{const D=k();if(!(D<=0)){if(r.isNonNullable(A)){for(let j=0;j<D;j++)if(N(j)>A)return x(j)}return V()}},I=A=>{const D=k(),j=A?A.chunkIdx+1:0,Z=j-T.fragIndex;if(!(D<=0)){if(!A||Z<0||Z-D>Mp)return t(`Resync: offset=${Z} bChunks=${D} chunk=`+JSON.stringify(A)),V();if(!(Z>=D))return x(j-T.fragIndex,!1)}},q=(A,D,j)=>{u&&u.abort(),u=Pi(this.urlResolver.resolve(A,!0,this.lowLatency),D,j,()=>this._retryCallback()).withTimeout(pi).withRetryCount(fi).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:(A,D)=>{q(b,j=>{if(!h())return;T=j;const Z=!!T.lowLatency;Z!==this.lowLatency&&S(Z);let ee=0;for(let ue=0;ue<T.dur.length;++ue)ee+=T.dur[ue];ee>0&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(ee/T.dur.length)),a({name:"index",zeroTime:T.zeroTime,shiftDuration:T.shiftDuration}),this.sourceJitter=T.hasOwnProperty("jitter")?Math.min(10,Math.max(.01,T.jitter/1e3)):1,A(_(D))},()=>this._handleNetworkError())},nextChunk:I}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:b=>{const{videoElement:T,logger:k}=this.params;let N=E(e.jidxUrl),U,R,x,V,_=0,I,q,C;const A=()=>{I&&(clearTimeout(I),I=void 0);const H=Math.max(Fp,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),oe=_+H,he=ne(),de=Math.min(1e4,oe-he);_=he;const pe=()=>{u||h()&&N.seek(()=>{h()&&(_=ne(),D(),A())})};de>0?I=window.setTimeout(()=>{this.paused?A():pe()},de):pe()},D=()=>{let H;for(;H=N.nextChunk(V);)V=H,ke(H);const oe=N.nextChunk(x);if(oe){if(x&&oe.discontinuity){k("Detected discontinuity; restarting playback"),this.paused?A():(y(),this._initPlayerWith(e));return}ue(oe)}else A()},j=(H,oe)=>{if(!h()||!this.sourceBuffer)return;let he,de,pe;const ct=et=>{window.setTimeout(()=>{h()&&j(H,oe)},et)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),ct(100);else{const et=ne(),ht=T.currentTime;!this.paused&&T.buffered.length>1&&q===ht&&et-C>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),q!==ht&&(q=ht,C=et);const pt=this._getBufferSizeSec();if(pt>30)k(`Buffered ${pt} seconds; delaying appendBuffer`),ct(2e3);else try{this.sourceBuffer.appendBuffer(H),this.videoPlayStarted?(this.bufferStates.push({ts:et,buf:pt}),g(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),oe&&oe()}catch(Xt){if(Xt.name==="QuotaExceededError")k("QuotaExceededError; delaying appendBuffer"),pe=this.sourceBuffer.buffered.length,pe!==0&&(he=this.sourceBuffer.buffered.start(0),de=ht,de-he>4&&this.sourceBuffer.remove(he,de-3)),ct(1e3);else throw Xt}}},Z=()=>{R&&U&&(k([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(x)]),j(R,function(){R=null,D()}))},ee=H=>e.fragUrlTemplate.replace("%%id%%",H.chunkIdx),ue=H=>{h()&&f(ee(H),(oe,he)=>{if(h()){if(he/=1e3,R=oe,x=H,o=H.startTS,he){const de=Math.min(10,H.dur/he);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*de:de}Z()}},()=>this._handleNetworkError())},ke=H=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(H),!1)))},qe=H=>{h()&&(e.cachedHeader=H,j(H,()=>{U=!0,Z()}))};n=!0,N.seek(H=>{if(h()){if(_=ne(),!H){A();return}V=H,!r.isNullable(b)||H.startTS>b?ue(H):(x=H,D())}},b),e.cachedHeader?qe(e.cachedHeader):p(e.headerUrl,qe,()=>this._handleNetworkError())},stop:y,getTimestampSec:()=>o},c}_switchToQuality(e){const{logger:t,playerCallback:i}=this.params;let a;e.bitrate!==this.bitrate&&(this.rep&&(a=this.rep.getTimestampSec(),r.isNonNullable(a)&&(a+=.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,r.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(a),i({name:"qualitySwitch",quality:e}))}_qualityAvailable(e){return r.isNonNullable(this.manifest.find(t=>t.name===e))}_initBitrateSwitcher(){const{logger:e,playerCallback:t}=this.params,i=h=>{if(!this.autoQuality)return;let p,f,m;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(f=this._getBufferSizeSec(),m=h/this.bitrate,f>10&&m>.8||f>15&&m>.5||f>20&&m>.3)){e(`Not switching: buffer=${Math.floor(f)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}p=this._selectQuality(h),p?this._switchToQuality(p):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(p,f)=>{const m=ne();if(this.chunkRateEstimator.addInterval(p,m,f)){const g=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:f,duration:m-p,speed:g}),!0}},get:()=>{const p=this.chunkRateEstimator.getBitRate();return p?p*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Qn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,p)=>{const f=n.updateChunk(h,p);return f&&u(),f},notifySwitch:h=>{const p=ne();h<l&&(o=p),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=Pi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(pi).withRetryCount(fi).withRetryInterval(Lp,Op).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;Ze(t).then(i=>{i||e==null||e()})}_handleManifestUpdate(e){const{logger:t,playerCallback:i,videoElement:a}=this.params,n=o=>{const l=[];return o!=null&&o.length?(o.forEach((d,u)=>{d.video&&a.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))},Bp))}_initManifest(){this._fetchManifest(this.manifestUrl,e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(this.manifestUrl))},()=>this._handleNetworkError())}}var O;(function(s){s.STOPPED="stopped",s.MANIFEST_READY="manifest_ready",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(O||(O={}));const jp=[O.PAUSED,O.PLAYING,O.READY],Hp=[O.PAUSED,O.PLAYING,O.READY];class Gp{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(O.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new ji,this._dashCb=a=>{var n,o,l,d;switch(a.name){case"buffering":{const u=a.isBuffering;this.params.output.isBuffering$.next(u);break}case"error":{this.params.output.error$.next({id:`DashLiveProviderInternal:${a.type}`,category:r.ErrorCategory.WTF,message:"LiveDashPlayer reported error"});break}case"manifest":{const u=a.manifest,c=[];for(const h of u){const p=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),f=(o=Kt(h.name))!==null&&o!==void 0?o:r.videoSizeToQuality(h.video),m=h.bitrate/1e3,S={...h.video};if(!f)continue;const g={id:p,quality:f,bitrate:m,size:S};c.push({track:g,representation:h})}this.representations$.next(c),this.params.output.availableVideoTracks$.next(c.map(({track:h})=>h)),((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===O.MANIFEST_READY&&this.videoState.setState(O.MANIFEST_READY);break}case"qualitySwitch":{const u=a.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),r.isNonNullable(c)&&this.params.output.currentVideoTrack$.next(c);break}case"bandwidth":{const{size:u,duration:c}=a;this.params.dependencies.throughputEstimator.addRawSpeed(u,c);break}case"index":{this.maxSeekBackTime$.next(a.shiftDuration||0),this.zeroTime$.next(a.zeroTime);break}}},this.syncPlayback=()=>{const a=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: ${a}; videoTransition: ${JSON.stringify(n)}; desiredPlaybackState: ${o}; seekState: ${JSON.stringify(d)};`}),o===exports.PlaybackState.STOPPED){a!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(O.STOPPED));return}if(n)return;const u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(Hp.includes(a)&&(u||c)){this.prepare();return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&d.state===B.Requested&&jp.includes(a)){this.seek(d.position-this.liveOffset.getTotalPausedTime());return}switch(a){case O.STOPPED:this.videoState.startTransitionTo(O.MANIFEST_READY),this.dash.attachSource(ye(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:if(o===exports.PlaybackState.PLAYING)if(this.videoState.startTransitionTo(O.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue())this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3);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(ye(this.params.source.url,h))}return;default:return r.assertNever(a)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashLiveProvider");const t=a=>{e.output.error$.next({id:"DashLiveProvider",category:r.ErrorCategory.WTF,message:"DashLiveProvider internal logic error",thrown:a})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(a=>({transition:a,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(a=>({transition:a,type:"end"})))).subscribe(({transition:a,type:n})=>{this.log({message:`[videoState change] ${n}: ${JSON.stringify(a)}`})}),this.video=He(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(le(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=Ye(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(r.map(a=>a.map(({track:n})=>n)))}),this.subscription.add(i.canplay$.subscribe(()=>{var a;((a=this.videoState.getTransition())===null||a===void 0?void 0:a.to)===O.READY&&this.videoState.setState(O.READY)},t)).add(i.pause$.subscribe(()=>{this.videoState.setState(O.PAUSED)},t)).add(i.playing$.subscribe(()=>{this.params.desiredState.seekState.getState().state===B.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(O.PLAYING)},t)).add(i.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(a=>-a/1e3)).subscribe(this.params.output.duration$)).add(r.combine({zeroTime:this.zeroTime$.pipe(r.filter(r.isNonNullable)),position:i.timeUpdate$}).subscribe(({zeroTime:a,position:n})=>this.params.output.liveTime$.next(a+n*1e3),t)).add(dt(this.video,this.params.desiredState.isLooped,t)).add(je(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Xe(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:a}})=>{const n=a&&r.videoQualityToHeight(a);this.dash.setMaxAutoQuality(n),this.params.output.autoVideoTrackLimits$.next({max:a})})).add(this.videoState.stateChangeEnded$.subscribe(a=>{var n;switch(a.to){case O.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case O.MANIFEST_READY:case O.READY:((n=this.params.desiredState.playbackState.getTransition())===null||n===void 0?void 0:n.to)===exports.PlaybackState.READY&&this.params.desiredState.playbackState.setState(exports.PlaybackState.READY);break;case O.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case O.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(a.to)}},t)).add(r.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.observableFrom(["init"])).pipe(r.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),Ge(this.video)}createLiveDashPlayer(){const e=new Up({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,a,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=(a=(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())===null||i===void 0?void 0:i.to)!==null&&a!==void 0?a:this.params.desiredState.autoVideoTrackSwitching.getState(),c=!u&&r.isNonNullable(d)?d:(n=Rt(l.map(({track:m})=>m),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||n===void 0?void 0:n.id,h=this.params.desiredState.videoTrack.getTransition(),p=this.params.desiredState.videoTrack.getState(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition();if((h&&c||c!==p)&&this.setVideoTrack(c),f&&this.setAutoQuality(u),h||f||c!==p){const m=(o=l.find(({track:S})=>S.id===c))===null||o===void 0?void 0:o.representation;r.assertNonNullable(m,"Representations missing"),this.dash.startPlay(m,u)}}setVideoTrack(e){var t;const i=(t=this.representations$.getValue().find(({track:a})=>a.id===e))===null||t===void 0?void 0:t.representation;r.assertNonNullable(i,`No such representation ${e}`),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(),a=t===exports.PlaybackState.PAUSED&&i===O.PAUSED,n=-e,o=n<=this.maxSeekBackTime$.getValue()?n:0;this.params.output.position$.next(e/1e3),this.dash.reinit(ye(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var Kn=s=>{var e,t;const i=s.get("X-Delivery-Type"),a=s.get("X-Reused"),n=i===null?exports.HttpConnectionType.HTTP1:(e=i)!==null&&e!==void 0?e:void 0,o=a===null?void 0:(t={1:!0,0:!1}[a])!==null&&t!==void 0?t:void 0;return{type:n,reused:o}},Ke=(s,e)=>{let t=0;for(let i=0;i<s.length;i++){const a=s.start(i)*1e3,n=s.end(i)*1e3;a<=e&&e<=n&&(t=n)}return Math.max(t-e,0)};const Yp=s=>{const e=document.createElement("a");return e.href=s,e.origin},qp=s=>{const e=document.createElement("a");return e.href=s,e.host};class Jn{constructor(e,t=[],i,a,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=a,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,a,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${(a=this._xhr)===null||a===void 0?void 0:a.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(p=>p.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 a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(qp(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open("GET",a,!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 Ri{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 a=this._sourceBuffer.buffered;let n=0;for(let o=0,l=a.length;o<l;o++)n+=a.end(o)-a.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,a,n,o,l){this.abort(()=>{let d=0;const u=Date.now();let c=0,h=0,p=0;const f=S=>{a(Ri._str2ua(S.substr(d))),d=S.length};let m=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(m=Pt(m)),this._lastXhr=new Jn(m,e.failoverHosts,S=>{this._lastXhr=void 0,f(S);const g=Date.now()-u;this._params.onBandwidthChange({size:S.length,duration:g,speed:8*S.length/(g/1e3)}),this._onDashCallback("loading",{size:S.length,done:!0}),n==null||n()},S=>{if(S.length-d>l&&f(S),h===0){h=Date.now();return}p=S.length-c;const g=Date.now()-h;p>=100*1024&&g>=1e3&&(this._params.onBandwidthChange({size:p,duration:g,speed:8*p/(g/1e3)}),p=0,c=S.length,h=Date.now()),this._onDashCallback("loading",{size:S.length,done:!1})},o,(S,g,E)=>this._params.onError(S,g,E))})}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=Ri._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 zp{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},a=t.exec(e),n=(a==null?void 0:a[1])==="-"?-1:1,o={years:i(a==null?void 0:a[2],n),months:i(a==null?void 0:a[3],n),weeks:i(a==null?void 0:a[4],n),days:i(a==null?void 0:a[5],n),hours:i(a==null?void 0:a[6],n),minutes:i(a==null?void 0:a[7],n),seconds:i(a==null?void 0:a[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=Pt(i)),new Jn(i,t,a=>{this.attachManifest(a,t,Yp(i))},void 0,a=>{this._params.onResponseHeaders(a)},(a,n,o)=>this._params.onError(a,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,p,f,m,S,g,E,y,v,b,T,k,N,U,R,x,V,_;const I=u.getElementsByTagName("SegmentBase")[0],q=I&&o(I,"indexRange").split("-"),C=I&&I.getElementsByTagName("Initialization")[0],A=C&&o(C,"range").split("-");if(!A||!q){const ke=u.parentElement;if((ke==null?void 0:ke.getAttribute("contentType"))==="text"){const qe=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,H=(i?i+"/":"")+((m=(f=(p=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||p===void 0?void 0:p.childNodes)===null||f===void 0?void 0:f[0])===null||m===void 0?void 0:m.data),oe=(S=ke.getAttribute("lang"))!==null&&S!==void 0?S:void 0;H&&d.push({id:qe,url:H,language:oe})}return}const D=.1,j=Number((g=u.attributes.getNamedItem("bandwidth"))===null||g===void 0?void 0:g.value),Z=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const ue=(y=(E=u.attributes.getNamedItem("frameRate"))===null||E===void 0?void 0:E.value)!==null&&y!==void 0?y:void 0;ee=ue?Sa(ue):void 0,l.push({width:Number((v=u.attributes.getNamedItem("width"))===null||v===void 0?void 0:v.value),height:Number((b=u.attributes.getNamedItem("height"))===null||b===void 0?void 0:b.value),bandwidth:j,baseURL:Z,failoverHosts:t,indexFrom:Number(q[0]),indexTo:Number(q[1]),initFrom:Number(A[0]),initTo:Number(A[1]),codecs:(k=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&k!==void 0?k:void 0,mimeType:(U=(N=u.attributes.getNamedItem("mimeType"))===null||N===void 0?void 0:N.value)!==null&&U!==void 0?U:void 0,fps:ee,bufferSize:D*j/8,bufferLength:D,name:(x=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&x!==void 0?x:void 0,id:(_=(V=u.attributes.getNamedItem("id"))===null||V===void 0?void 0:V.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 p=document.createElement("track");h&&p.setAttribute("src",h),u&&p.setAttribute("id",u),c&&p.setAttribute("srclang",c),this._video.appendChild(p)}),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,a=>{let n=e.initTo-e.initFrom+1;if(!a.byteLength){this._params.onError("EmptyResponse","Empty response");return}e.initMessage=new Uint8Array(a.buffer,0,n);const o=new DataView(a.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 p=0;p<c;p+=1){const f=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:f-1}),u=f,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,a=>{this._params.onResponseHeaders(a),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 a,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 f=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),f)}const c=this._appendVector[String(u.fromTime)];c!==a&&(a=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const f=this._buffer.getByTime(this._video.currentTime);if(!f){this._onDashCallback("buffering");return}h=f.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==f.to&&(n=f.to,window.setTimeout(()=>{try{const m=this._buffer.getNextWithGap(f);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 Ri({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,a=!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=a||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),a=this._findRef(this._video.currentTime);if(!i||!a){this._video.currentTime&&t&&this._loadRef(e,this._video.currentTime);return}const n=.1;if(a.toTime<i.to+n){const o=this._findRef(a.toTime);o&&o.toTime<i.to+n?(this._buffer.smartRemove(a.fromTime-n,o.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,o.toTime)):(this._buffer.smartRemove(a.fromTime-n,a.toTime+n,(l,d)=>this._stream.remove(l,d)),this._loadRef(e,a.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||r.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 a;for(let n=0;n<i.length;n++){const o=i[n];if(o.fromTime<=e&&o.toTime>e)return o;o.fromTime>e&&(!a||o.fromTime<a.fromTime)&&(a=o)}if(!a){const n=i[i.length-1];if(e>n.toTime)return n}return a}_isLastRef(e){var t;const i=(t=this._currentRepresentation)===null||t===void 0?void 0:t.refs;if(!i)return!1;const a=i[i.length-1];return e.fromTime===a.fromTime}_findBufferRangeEnd(e){let t=this._video.buffered.length;for(;t-- >0;){const i=this._video.buffered.start(t),a=this._video.buffered.end(t);if(e>i&&e<a)return Math.round(a*10)/10}return e}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var F;(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"})(F||(F={}));const Wp=[F.PAUSED,F.PLAYING];class Qp{constructor(e){this.videoState=new K(F.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.elementSize$=new r.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new r.Subject,responseHeaders$:new r.Subject,manifestReady$:new r.Subject,representationPlay$:new r.Subject,error$:new r.Subject},this.handleManifestReady=({representations:t,textRepresentations:i})=>{var a,n,o;const l=[];for(const d of t){const u=(n=(a=d.name)!==null&&a!==void 0?a:d.id)!==null&&n!==void 0?n:d.height.toString(10),c=(o=d.name&&Kt(d.name))!==null&&o!==void 0?o:r.videoSizeToQuality(d),h=d.bandwidth/1e3,p={width:d.width,height:d.height},f=d.fps;if(!c)continue;const m={id:u,quality:c,bitrate:h,size:p,fps:f};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(F.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var i;const a=(i=this.representations$.getValue().find(({representation:n})=>n===t))===null||i===void 0?void 0:i.track;a&&(this.params.output.currentVideoTrack$.next(a),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(a.id))},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return r.assertNonNullable(t,"Can't select representation. something went wrong"),t},this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.videoState.getTransition(),a=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: ${a}; seekState: ${JSON.stringify(o)};`}),a===exports.PlaybackState.STOPPED){t!==F.STOPPED&&(this.videoState.startTransitionTo(F.STOPPED),this.dash.destroy(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(F.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===B.Requested&&Wp.includes(t)&&this.seek(o.position,o.forcePrecise),t){case F.STOPPED:this.videoState.startTransitionTo(F.MANIFEST_LOADED),this.prepare();return;case F.MANIFEST_LOADED:this.videoState.startTransitionTo(F.INITIAL_REPRESENTATION_SELECTED);return;case F.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(F.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case F.METADATA_LOADED:this.videoState.startTransitionTo(F.READY),this.dash.updateRefsForCurrentTime();return;case F.READY:a===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(F.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed());return;case F.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(F.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case F.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(F.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog("DashProvider"),r.merge(this.videoState.stateChangeStarted$.pipe(r.map(t=>({transition:t,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(t=>({transition:t,type:"end"})))).subscribe(({transition:t,type:i})=>{this.log({message:`[videoState change] ${i}: ${JSON.stringify(t)}`})}),this.video=He(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(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new dp(this.video),this.dash=new zp({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,a)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:i,thrown:a,category:r.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:r.ErrorCategory.WTF,message:"DashProvider internal logic error",thrown:l})},a=()=>{const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();return d?d.to:l},n=Ye(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(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==B.Applying)&&(this.videoState.getState()===F.PLAYING||this.videoState.getState()===F.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Xe(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(r.map(l=>l.map(({track:d})=>d)))}),o(Di(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===F.READY&&this.videoState.setState(F.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(F.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(F.PLAYING),P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(F.METADATA_LOADED)},i)).add(n.currentBuffer$.subscribe(l=>{this.buffer.fill(),e.currentBuffer$.next(l)},i)).add(this.dashLiteEvents.error$.pipe(r.map(({id:l,message:d,thrown:u})=>({id:`DashLite_${l}`,category:r.ErrorCategory.WTF,message:d,thrown:u}))).subscribe(this.params.output.error$)).add(r.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$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),p=this.params.desiredState.autoVideoTrackSwitching.getTransition(),f=this.params.desiredState.videoTrack.getState(),m=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),S=this.elementSize$.getValue(),g=a();p&&this.params.desiredState.autoVideoTrackSwitching.setState(p.to);let E;if(!g&&r.isNonNullable(f))E=f;else{const y=Ke(this.video.buffered,this.video.currentTime*1e3),v=g?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,b=Math.min(y/v,1);E=(d=Rt(h.map(({track:k})=>k),{container:S,throughput:m,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:b,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:k})=>k===c))===null||l===void 0?void 0:l.track,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}))===null||d===void 0?void 0:d.id;const T=t.autoVideoTrackLimits.getTransition();T&&e.autoVideoTrackLimits$.next(T.to)}return r.isNonNullable(E)?(u=h.find(({track:y})=>y.id===E))===null||u===void 0?void 0:u.representation:void 0}),r.filterChanged()).subscribe(this.currentRepresentation$,i)).add(r.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(r.filter(l=>l.to===F.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(F.INITIAL_REPRESENTATION_SELECTED),i)).add(this.currentRepresentation$.pipe(r.filter(r.isNonNullable),r.filterChanged((l,d)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&a()?l.height<=d.height:l===d)).subscribe(l=>{const d=Ke(this.video.buffered,this.video.currentTime*1e3),u=Math.min(d/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||u<=.5||!a())&&(this.dash.setQualityByRepresentation(l,!0),this.params.output.hostname$.next(le(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Kn(l);this.params.output.httpConnectionType$.next(d),this.params.output.httpConnectionReused$.next(u)})).add(this.dashLiteEvents.idxRequestPing$.pipe(r.once(),r.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(r.filter(r.isNonNullable)).subscribe(this.handleRepresentationPlay,i)).add(r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.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),Ge(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 r.assertNever(e)}}seek(e,t=!1){this.log({message:`[seek] position: ${e}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(e/1e3,t)}playIfAllowed(){Ze(this.video).then(e=>{e||(this.videoState.setState(F.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))},e=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:e}))}}var ae;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(ae||(ae={}));var Ci;(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"})(Ci||(Ci={}));var me;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(me||(me={}));var G;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(G||(G={}));var At;(function(s){s.MP4="mp4",s.WEBM="webm"})(At||(At={}));var Ii;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Ii||(Ii={}));var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));class Cr{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 a=0,n=i.length;a<n;a++)if(i[a].callback===t){i.splice(a,1);return}}dispatchEvent(e){if(!(e.type in this.listeners))return;const i=this.listeners[e.type].slice();for(let a=0,n=i.length;a<n;a++){const o=i[a];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 Xn extends Cr{constructor(){super(),this.listeners||Cr.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 Zn=class{constructor(){Object.defineProperty(this,"signal",{value:new Xn,writable:!0,configurable:!0})}abort(e){let t;try{t=new Event("abort")}catch(a){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(a){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&&(Zn.prototype[Symbol.toStringTag]="AbortController",Xn.prototype[Symbol.toStringTag]="AbortSignal");function eo(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 Kp(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!eo({fetch:e,Request:t,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a}))return{fetch:e,Request:n};let n=t;(n&&!n.prototype.hasOwnProperty("signal")||a)&&(n=function(u,c){let h;c&&c.signal&&(h=c.signal,delete c.signal);const p=new t(u,c);return h&&Object.defineProperty(p,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),p},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(f){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const p=new Promise((f,m)=>{c.addEventListener("abort",()=>m(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([p,o(d,u)])}return o(d,u)},Request:n}}const Gi=eo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),to=Gi?Kp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Yt=Gi?to.fetch:window.fetch;Gi?to.Request:window.Request;const $t=Gi?Zn:window.AbortController;var Zs=(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 Jp=(s,e={})=>{const i=e.timeout||1,a=performance.now();return window.setTimeout(()=>{s({get didTimeout(){return e.timeout?!1:performance.now()-a-1>i},timeRemaining(){return Math.max(0,1+(performance.now()-a))}})},1)},Xp=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",Ir=Xp?Jp:window.requestIdleCallback;var ks,Ps;let io=!1;try{io=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt((Ps=(ks=navigator.userAgent.match(/Version\/(\d+)/))===null||ks===void 0?void 0:ks[1])!==null&&Ps!==void 0?Ps:"",10)<16}catch(s){console.error(s)}class Zp{constructor(e){this.bufferFull$=new r.Subject,this.error$=new r.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:r.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 a={operation:"append",data:e,signal:t,callback:i};this.queue.push(a),this.pull()})}async remove(e,t,i){return i&&i.aborted?!1:new Promise(a=>{const n={operation:"remove",from:e,to:t,signal:i,callback:a};this.queue.unshift(n),this.pull()})}async abort(e){return new Promise(t=>{let i;io&&e?i={operation:"safariAbort",init:e,callback:t}:i={operation:"abort",callback:t};for(const{callback:a}of this.queue)a(!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:r.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:r.assertNever(t)}}}var xr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class Ie{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 a=new TextDecoder(t).decode(new DataView(this.source.buffer,this.source.byteOffset+this.cursor,e));return this.cursor+=e,a}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 so extends Ie{}class ef extends Ie{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 tf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class sf extends Ie{constructor(e){super(e),this.data=this.content}}class Jt extends Ie{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class af extends Jt{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 a=i>>>31,n=i<<1>>>1,o=this.readUint32();i=this.readUint32();const l=i>>>28,d=i<<3>>>3;this.segments.push({referenceType:a,referencedSize:n,subsegmentDuration:o,SAPType:l,SAPDeltaTime:d})}}}class rf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class nf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}var nt;(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"})(nt||(nt={}));class of extends Jt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=nt.MONOSCOPIC;break;case 1:this.stereoMode=nt.TOP_BOTTOM;break;case 2:this.stereoMode=nt.LEFT_RIGHT;break;case 3:this.stereoMode=nt.STEREO_CUSTOM;break;case 4:this.stereoMode=nt.RIGHT_LEFT;break}this.cursor+=1}}class lf extends Jt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class uf extends Jt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class df extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class cf extends Jt{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 hf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}class pf extends Ie{parseChildrenBoxes(){return Ct(this.content)}}const ff={ftyp:ef,moov:tf,mdat:sf,sidx:af,trak:rf,mdia:df,tkhd:cf,minf:hf,sv3d:nf,st3d:of,prhd:lf,proj:pf,equi:uf,unknown:so};class mf{createBox(e,t){const i=ff[e];return i?new i(t):new so(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return Yi.createBox(i,new DataView(e.buffer,e.byteOffset))}}const Yi=new mf;function jt(s,e){const t=new TextDecoder("ascii");let i=s.byteOffset,a=[];for(;i<s.byteLength;){const n=t.decode(new DataView(s.buffer,i,1));if(n===e[a.length]?a.push(n):a=[],a.length===4&&a.join("")===e){const l=new DataView(s.buffer,i-7,4).getUint32(0);return i-7+l>s.byteLength?null:Yi.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function vf(s,e){const t=[];let i=0;for(;i<s.byteLength;){const a=jt(new DataView(s.buffer,s.byteOffset+i,s.byteLength-i),e);if(a)t.push(a),i+=a.size+a.source.byteOffset;else break}return t}function Ct(s){const e=[];let t=0;for(;t<s.byteLength;){const i=Yi.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const Sf=new TextDecoder("ascii"),bf=s=>Sf.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",gf=s=>{const e=Yi.createFromView(s);let t=e.earliestPresentationTime/e.timescale*1e3,i=s.byteOffset+s.byteLength+e.firstOffset;return e.segments.map(n=>{if(n.referenceType!==0)throw new Error("Unsupported multilevel sidx");const o=n.subsegmentDuration/e.timescale*1e3,l={status:G.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},yf=s=>{const e=vf(s,"mdat");if(e.length){const t=e.reduce((i,a)=>i+a.size,0);return new DataView(s.buffer,s.byteOffset,t)}return null},Tf=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Ii.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(jt(s,"sv3d")){e.is3dVideo=!0;const i=jt(s,"st3d");i&&(e.stereoMode=i.stereoMode);const a=jt(s,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=jt(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},Ef={validateData:bf,parseInit:Tf,getIndexRange:()=>{},parseSegments:gf,parseFeedableSegmentChunk:yf};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 w;(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"})(w||(w={}));const Nr={[$.EBML]:{type:w.Master},[$.EBMLVersion]:{type:w.UnsignedInteger},[$.EBMLReadVersion]:{type:w.UnsignedInteger},[$.EBMLMaxIDLength]:{type:w.UnsignedInteger},[$.EBMLMaxSizeLength]:{type:w.UnsignedInteger},[$.DocType]:{type:w.String},[$.DocTypeVersion]:{type:w.UnsignedInteger},[$.DocTypeReadVersion]:{type:w.UnsignedInteger},[$.Void]:{type:w.Binary},[$.Segment]:{type:w.Master},[$.SeekHead]:{type:w.Master},[$.Seek]:{type:w.Master},[$.SeekID]:{type:w.Binary},[$.SeekPosition]:{type:w.UnsignedInteger},[$.Info]:{type:w.Master},[$.TimestampScale]:{type:w.UnsignedInteger},[$.Duration]:{type:w.Float},[$.Tracks]:{type:w.Master},[$.TrackEntry]:{type:w.Master},[$.Video]:{type:w.Master},[$.Projection]:{type:w.Master},[$.ProjectionType]:{type:w.UnsignedInteger},[$.ProjectionPrivate]:{type:w.Master},[$.Chapters]:{type:w.Master},[$.Cluster]:{type:w.Master},[$.Timestamp]:{type:w.UnsignedInteger},[$.SilentTracks]:{type:w.Master},[$.SilentTrackNumber]:{type:w.UnsignedInteger},[$.Position]:{type:w.UnsignedInteger},[$.PrevSize]:{type:w.UnsignedInteger},[$.SimpleBlock]:{type:w.Binary},[$.BlockGroup]:{type:w.Master},[$.EncryptedBlock]:{type:w.Binary},[$.Attachments]:{type:w.Master},[$.Tags]:{type:w.Master},[$.Cues]:{type:w.Master},[$.CuePoint]:{type:w.Master},[$.CueTime]:{type:w.UnsignedInteger},[$.CueTrackPositions]:{type:w.Master},[$.CueTrack]:{type:w.UnsignedInteger},[$.CueClusterPosition]:{type:w.UnsignedInteger},[$.CueRelativePosition]:{type:w.UnsignedInteger},[$.CueDuration]:{type:w.UnsignedInteger},[$.CueBlockNumber]:{type:w.UnsignedInteger},[$.CueCodecState]:{type:w.UnsignedInteger},[$.CueReference]:{type:w.Master},[$.CueRefTime]:{type:w.UnsignedInteger}},ao=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=xi(s,t),a=i in Nr,n=a?Nr[i].type:w.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=xi(d),h=u*2**((l-1)*8)+c,p=t+l;let f;return p+h>s.byteLength?f=new DataView(s.buffer,s.byteOffset+p):f=new DataView(s.buffer,s.byteOffset+p,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:p,tagSize:p+h,value:f,valueSize:h}},xi=(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},De=(s,e)=>{switch(e){case w.SignedInteger:return s.getInt8(0);case w.UnsignedInteger:return xi(s);case w.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case w.String:return new TextDecoder("ascii").decode(s);case w.UTF8:return new TextDecoder("utf-8").decode(s);case w.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case w.Master:return s;case w.Binary:return s;default:r.assertNever(e)}},wt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=ao(i);if(!e(a))return;a.type===w.Master&&wt(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},$f=s=>{if(s.getUint32(0)!==$.EBML)return!1;let e,t,i;const a=ao(s);return wt(a.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=De(l,o):n===$.DocType?t=De(l,o):n===$.DocTypeReadVersion&&(i=De(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},ro=[$.Info,$.SeekHead,$.Tracks,$.TrackEntry,$.Video,$.Projection,$.ProjectionType,$.ProjectionPrivate,$.Chapters,$.Cluster,$.Cues,$.Attachments,$.Tags],kf=[$.Timestamp,$.SilentTracks,$.SilentTrackNumber,$.Position,$.PrevSize,$.SimpleBlock,$.BlockGroup,$.EncryptedBlock],Pf=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return wt(s,({tag:p,type:f,value:m,valueSize:S})=>{if(p===$.SeekID){const g=De(m,f);u=xi(g)}else p!==$.SeekPosition&&(u=void 0);return p===$.Segment?(e=m.byteOffset,t=m.byteOffset+S):p===$.Info?n=!0:p===$.SeekHead?o=!0:p===$.TimestampScale?i=De(m,f):p===$.Duration?a=De(m,f):p===$.SeekPosition&&u===$.Cues?d=De(m,f):p===$.Tracks?wt(m,({tag:g,type:E,value:y})=>g===$.ProjectionType?(c=De(y,E)===1,!1):!0):n&&o&&ro.includes(p)&&(l=!0),!l}),r.assertNonNullable(e,"Failed to parse webm Segment start"),r.assertNonNullable(t,"Failed to parse webm Segment end"),r.assertNonNullable(a,"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(a/1e9*i*1e3),cuesSeekPosition:d,is3dVideo:c,stereoMode:h,projectionType:Ii.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Af=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},wf=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return wt(s,({tag:l,type:d,value:u})=>{switch(l){case $.Cues:t=!0;break;case $.CuePoint:o&&a(o)&&n.push(o),o={};break;case $.CueTime:o&&(o.time=De(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=De(u,d));break;default:t&&ro.includes(l)&&(i=!0)}return!(t&&i)}),o&&a(o)&&n.push(o),n.map((l,d)=>{const{time:u,position:c}=l,h=n[d+1];return{status:G.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},_f=s=>{let e=0,t=!1;try{wt(s,i=>i.tag===$.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):kf.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},Df={validateData:$f,parseInit:Pf,getIndexRange:Af,parseSegments:wf,parseFeedableSegmentChunk:_f},no=1e4,Rf=3e4,Cf=5e3,If=no,xf=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?Kt(n):void 0)!==null&&o!==void 0?o:r.videoSizeToQuality({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},Nf=({id:s,bitrate:e})=>({id:s,bitrate:e}),Lf=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=we(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:we(s,-1)},Of=({id:s,lang:e,url:t,isAuto:i})=>({id:s,url:t,isAuto:i,type:"internal",language:e}),mi=s=>{const e=[];let t=0,i=s.length-1;for(;t<no&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class Lr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1,manifest:u}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.playingRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.isSeekingLive=!1,this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new $t,this.destroyAbortController=new $t,this.bufferLimit=1/0,this.failedDownloads=0,this.isLive=!1,this.liveUpdateSegmentIndex=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(c){const h=this.representations.get(c);r.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(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},S=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:S}))),this.subscription.add(r.fromEvent(this.sourceBuffer,"error").subscribe(()=>this.error$.next({id:"SourceBuffer",category:r.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,xr(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(h,"high",!0);const p=this.initData.get(h.id),f=this.segments.get(h.id),m=this.parsedInitData.get(h.id);r.assertNonNullable(p,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),p instanceof ArrayBuffer&&(this.searchGaps(f,h),yield this.sourceBufferTaskQueue.append(p,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m))}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(c){if(c===this.downloadingRepresentationId||c===this.switchingToRepresentationId)return;this.switchingToRepresentationId=c;const h=this.representations.get(c);r.assertNonNullable(h,`No such representation ${c}`);let p=this.segments.get(c),f=this.initData.get(c);if(r.isNullable(f)||r.isNullable(p)?yield this.loadInit(h,"high",!1):f instanceof Promise&&(yield f),p=this.segments.get(c),r.assertNonNullable(p,"No segments for starting representation"),f=this.initData.get(c),!f||!(f instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=c,this.abort(),yield this.sourceBufferTaskQueue.append(f,this.downloadAbortController.signal);const m=this.getCurrentPosition();r.isNonNullable(m)&&(this.searchGaps(p,h),this.maintain(m))}.bind(this)),this.seekLive=r.abortable(this.destroyAbortController.signal,async function*(c){if(this.isSeekingLive=!0,!this.downloadingRepresentationId||!c)return;for(const g of this.representations.keys()){const E=c.find(b=>b.id===g);E&&this.representations.set(g,E);const y=this.representations.get(g);if(!y)return;const v=mi(y.segmentReference.segments);this.segments.set(y.id,v)}const h=this.switchingToRepresentationId?this.switchingToRepresentationId:this.downloadingRepresentationId,p=this.representations.get(h);r.assertNonNullable(p);const f=mi(p.segmentReference.segments),m=this.initData.get(p.id);if(r.assertNonNullable(m,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(m instanceof ArrayBuffer))return;const S=this.getDebugBufferState();this.liveUpdateSegmentIndex=0,this.abort(),S&&(yield this.sourceBufferTaskQueue.remove(S.from*1e3,S.to*1e3,this.destroyAbortController.signal)),this.searchGaps(f,p),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 At.MP4:this.containerParser=Ef;break;case At.WEBM:this.containerParser=Df;break;default:r.assertNever(i)}this.initData=new Map(a.map(c=>[c.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.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 $t,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer)||this.isSeekingLive)return;const t=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(r.assertNonNullable(t,`No such representation ${this.downloadingRepresentationId}`),!i)return;const a=i.find(u=>e>=u.time.from&&e<u.time.to);let n=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const c=Ke(this.sourceBuffer.buffered,e),h=a?a.time.to+100:-1/0;a&&c>=a.time.to-e+100&&(n=h)}if(isFinite(this.bufferLimit)&&xr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Ke(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&&a)if(l.includes(a))u="high";else{const c=we(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.isLive&&!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===G.FED&&!l.length&&Ke(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=we(i,-1);d&&d.status===G.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}searchGaps(e,t){this.gaps=[];let i=0;for(const a of e)a.time.from-i>0&&this.gaps.push({representation:t.id,from:i,to:a.time.from}),i=a.time.to;r.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(a=>a.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,a,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:G.NONE,size:void 0})),d=(i=this.segments.get(o.id))!==null&&i!==void 0?i:[],u=(n=(a=we(d,-1))===null||a===void 0?void 0:a.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=mi(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,a;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(a=l==null?void 0:l.time.from)!==null&&a!==void 0?a: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(a=>t>=a.time.from&&t<a.time.to);return this.playingRepresentationId!==this.downloadingRepresentationId&&(this.liveUpdateSegmentIndex=i),this.liveUpdateSegmentIndex<e.length?e.slice(this.liveUpdateSegmentIndex++):[]}selectForwardBufferSegmentsRecord(e,t,i){const a=e.findIndex(({status:h,time:{from:p,to:f}},m)=>{const S=p<=i&&f>=i,g=p>i||S||m===0&&i===0,E=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&p<=i+E||f<=i+E;return(h===G.NONE||h===G.PARTIALLY_EJECTED&&g&&y&&this.sourceBuffer&&!Zs(this.sourceBuffer.buffered,i))&&g&&y});if(a===-1)return[];if(t!==me.BYTE_RANGE)return e.slice(a,a+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=a;h<n.length&&(o<=u||l<=c);h++){const p=n[h];if(o+=p.byte.to+1-p.byte.from,l+=p.time.to+1-p.time.from,p.status===G.NONE||p.status===G.PARTIALLY_EJECTED)d.push(p);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:l}=t.segmentReference;switch(l){case me.BYTE_RANGE:{a=t.segmentReference.url,n={from:we(e,0).byte.from,to:we(e,-1).byte.to};break}case me.TEMPLATE:{const u=we(e,0);a=new URL(u.url,t.segmentReference.baseUrl).toString(),o=[u];break}default:r.assertNever(l)}for(const u of o)u.status=G.DOWNLOADING,this.activeSegments.add({segment:u,loadedBytes:0,feedingBytes:0,fedBytes:0,representationId:t.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(await r.abortable(d,async function*(){const u=r.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(a,{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:r.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 a=this.getCurrentPosition();this.sourceBuffer&&r.isNonNullable(a)&&(i=Ke((t=this.sourceBuffer)===null||t===void 0?void 0:t.buffered,a)>=this.tuning.downloadBackoff.bufferThreshold),this.failedDownloads++,i||this.error$.next({id:"SegmentDownload",category:r.ErrorCategory.NETWORK,message:"Error when fetching segments",thrown:e})}onSomeDataLoaded(e,t,i,a,n){if(!this.activeSegments.size)return;const o=()=>{this.abort()},l=h=>{var p;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=G.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const f of this.representations.values())if(f.id!==t)for(const m of(p=this.segments.get(f.id))!==null&&p!==void 0?p:[])m.status===G.FED&&m.time.from===h.segment.time.from&&m.time.to===h.segment.time.to&&(m.status=G.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:p}=h,f=u===me.BYTE_RANGE,m=f?p.byte.to-p.byte.from+1:c;if(h.representationId!==t||!(!f||p.byte.from>=i&&p.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const g=f?p.byte.from-i:0,E=f?p.byte.to-i:e.byteLength,y=g<a,v=E<=a;if(p.status===G.DOWNLOADING&&y&&v){p.status=G.DOWNLOADED,this.activeSegments.delete(h);const b=new DataView(e.buffer,e.byteOffset+g,m);this.sourceBufferTaskQueue.append(b,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(m,a-g),h.loadedBytes>h.feedingBytes)){const b=new DataView(e.buffer,e.byteOffset+g+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===m?b:this.containerParser.parseFeedableSegmentChunk(b);T!=null&&T.byteLength&&(p.status=G.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(k=>{if(n.aborted)o();else if(k)h.fedBytes+=T.byteLength,h.fedBytes===m&&l(h);else{if(h.feedingBytes<m)return;o()}}))}}}abortSegment(e){this.tuning.useDashAbortPartiallyFedSegment&&e.status===G.PARTIALLY_FED||e.status===G.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=G.NONE),e.status=G.PARTIALLY_EJECTED):e.status=G.NONE;for(const i of this.activeSegments.values())if(i.segment===e){this.activeSegments.delete(i);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let e=null,t=!1;for(const[a,n]of this.initData.entries()){const o=n instanceof Promise;t||(t=o),n===null&&(e=a)}if(!e){this.allInitsLoaded=!0;return}if(t)return;const i=this.representations.get(e);i&&(this.initLoadIdleCallback=Ir(()=>this.loadInit(i,"low",!1).finally(()=>this.initLoadIdleCallback=null)))}async loadInit(e,t="auto",i=!1){const a=this.tuning.dash.useFetchPriorityHints?t:"auto",o=(!i&&this.failedDownloads>0?r.abortable(this.destroyAbortController.signal,async function*(){const l=r.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,a)).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?mi(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:r.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||r.isNullable(e)||this.sourceBuffer.updating)return!1;let a=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;a+=h};for(const u of this.segments.values())for(const c of u){if(c.time.to>=e-this.tuning.dash.bufferPruningSafeZone||a>=t)break;c.status===G.FED&&d(c)}if(l=isFinite(n)&&isFinite(o),!l){a=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)||a>t)break;c.status===G.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const p of this.segments.values())for(const f of p)if(f.status===G.NONE&&Math.round(f.time.from)<=Math.round(c)&&Math.round(f.time.to)>=Math.round(h)){n=c,o=h;break}}if(l=isFinite(n)&&isFinite(o),!l&&i){a=0,n=1/0,o=-1/0;const u=Math.min(this.forwardBufferTarget,this.bufferLimit)*this.tuning.dash.minSafeBufferThreshold;for(const c of this.segments.values())for(const h of c)h.time.from>e+u&&h.status===G.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}getDebugBufferState(){if(!(!this.sourceBuffer||!this.sourceBuffer.buffered.length))return{from:this.sourceBuffer.buffered.start(0),to:this.sourceBuffer.buffered.end(this.sourceBuffer.buffered.length-1)}}detectGaps(e,t){if(this.sourceBuffer)for(const i of t){let a={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){a=void 0;break}l>i.time.from&&l<i.time.to&&(a.from=l),o<i.time.to&&o>i.time.from&&(a.to=o)}}a&&a.to-a.from>1&&!this.gaps.some(n=>a&&n.from===a.from&&n.to===a.to)&&this.gaps.push(a)}}detectGapsWhenIdle(e,t){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ir(()=>{try{this.detectGaps(e,t)}catch(i){this.error$.next({id:"GapDetection",category:r.ErrorCategory.WTF,message:"detectGaps threw",thrown:i})}finally{this.gapDetectionIdleCallback=null}}))}checkEjectedSegments(){if(r.isNullable(this.sourceBuffer)||r.isNullable(this.playingRepresentationId))return;const e=[];for(let i=0;i<this.sourceBuffer.buffered.length;i++){const a=Math.round(this.sourceBuffer.buffered.start(i)*1e3),n=Math.round(this.sourceBuffer.buffered.end(i)*1e3);e.push({from:a,to:n})}const t=1;for(const i of this.segments.values())for(const a of i){const{status:n}=a;if(n!==G.FED&&n!==G.PARTIALLY_EJECTED)continue;const o=Math.floor(a.time.from),l=Math.ceil(a.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?a.status=G.PARTIALLY_EJECTED:a.status=G.NONE)}}}var Et;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(Et||(Et={}));class Bf{constructor({throughputEstimator:e,requestQuic:t,compatibilityMode:i=!1}){this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.abortAllController=new $t,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=Pt(n));const o=yield Yt(n,{signal:this.abortAllController.signal}).catch(Vt);return o?(this.onHeadersReceived(o.headers),o.text()):null}.bind(this)),this.fetch=r.abortable(this.abortAllController.signal,async function*(a,{rangeMethod:n=this.compatibilityMode?Et.HEADER:Et.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,p,f,m;let S=a;const g=new Headers;if(o)switch(n){case Et.HEADER:{g.append("Range",`bytes=${o.from}-${o.to}`);break}case Et.PARAM:{const D=new URL(S,location.href);D.searchParams.append("bytes",`${o.from}-${o.to}`),S=D.toString();break}default:r.assertNever(n)}this.requestQuic&&(S=Pt(S));let E=this.abortAllController.signal,y;if(u){const D=new $t;if(y=r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{D.abort()}catch(j){Vt(j)}}),this.abortAllController.signal.aborted||u.aborted)try{D.abort()}catch(j){Vt(j)}E=D.signal}const v=r.now(),b=yield Yt(S,{priority:d,headers:g,signal:E}).catch(Vt),T=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(T-v),!b)return y==null||y.unsubscribe(),null;if(!b.ok||!b.body)return y==null||y.unsubscribe(),Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`));this.onHeadersReceived(b.headers);const k=parseInt((p=b.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||o&&o.to-o.from+1||NaN;if(!k){const D=yield b.arrayBuffer();return(f=this.throughputEstimator)===null||f===void 0||f.addRawSpeed(D.byteLength,r.now()-T),l==null||l(new DataView(D),D.byteLength),y==null||y.unsubscribe(),D}if(!l&&!c)return y==null||y.unsubscribe(),b.arrayBuffer();const[N,U]=b.body.tee(),R=N.getReader();c&&((m=this.throughputEstimator)===null||m===void 0||m.trackStream(U));let x=0;const V=new ArrayBuffer(k),_=new Uint8Array(V),I=new DataView(V);let q=!1;const C=D=>{y==null||y.unsubscribe(),q=!0,Vt(D)},A=r.abortable(E,async function*({done:D,value:j}){if(x===0&&this.lastRequestFirstBytes$.next(r.now()-v),E.aborted){y==null||y.unsubscribe();return}!D&&j&&(_.set(j,x),x+=j.byteLength,l==null||l(I,x),yield R==null?void 0:R.read().then(A,C))}.bind(this));return yield R==null?void 0:R.read().then(A,C),y==null||y.unsubscribe(),q?null:V}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==me.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,p=!1,f,m;a.indexRange&&(f=a.indexRange.from,m=a.indexRange.to,p=u+1===f,p&&(c=Math.min(f,d),h=Math.max(m,u))),c=Math.min(c,0);const S=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!S)return null;const g=new DataView(S,d-c,u-c+1);if(!n.validateData(g))throw new Error("Invalid media file");const E=n.parseInit(g),y=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(E);if(!y)throw new ReferenceError("No way to load representation index");let v;if(p)v=new DataView(S,y.from-c,y.to-y.from+1);else{const T=yield this.fetch(a.url,{range:y,priority:o,measureThroughput:!1});if(!T)return null;v=new DataView(T)}const b=n.parseSegments(v,E,y);return{init:E,dataView:new DataView(S),segments:b}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==me.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{init:null,segments:a.segments.map(u=>({...u,status:G.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}=Kn(e);this.lastConnectionType$.next(t),this.lastConnectionReused$.next(i)}async fetchRepresentation(e,t,i="auto"){var a,n;const{type:o}=e;switch(o){case me.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case me.TEMPLATE:return(n=await this.fetchTemplateRepresentation(e,i))!==null&&n!==void 0?n:null;default:r.assertNever(o)}}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Vt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var Mf=ot,Vf=Li,Ff=$e,Uf=Ff("match"),jf=function(s){var e;return Mf(s)&&((e=s[Uf])!==void 0?!!e:Vf(s)=="RegExp")},Hf=Ui,Gf=String,Yf=function(s){if(Hf(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Gf(s)},qf=ut,zf=function(){var s=qf(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},Wf=Fe,Qf=Ue,Kf=na,Jf=zf,Or=RegExp.prototype,Xf=function(s){var e=s.flags;return e===void 0&&!("flags"in Or)&&!Qf(s,"flags")&&Kf(Or,s)?Wf(Jf,s):e},ga=Ve,Zf=Mi,em=Math.floor,As=ga("".charAt),tm=ga("".replace),ws=ga("".slice),im=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,sm=/\$([$&'`]|\d{1,2})/g,am=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=sm;return a!==void 0&&(a=Zf(a),d=im),tm(n,d,function(u,c){var h;switch(As(c,0)){case"$":return"$";case"&":return s;case"`":return ws(e,0,t);case"'":return ws(e,o);case"<":h=a[ws(c,1,-1)];break;default:var p=+c;if(p===0)return u;if(p>l){var f=em(p/10);return f===0?u:f<=l?i[f-1]===void 0?As(c,1):i[f-1]+As(c,1):u}h=i[p-1]}return h===void 0?"":h})},rm=Fi,nm=Fe,ya=Ve,Br=sa,om=ve,lm=Oi,um=jf,gt=Yf,dm=Bi,cm=Xf,hm=am,pm=$e,fm=pm("replace"),mm=TypeError,oo=ya("".indexOf),vm=ya("".replace),Mr=ya("".slice),Sm=Math.max,Vr=function(s,e,t){return t>s.length?-1:e===""?t:oo(s,e,t)};rm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Br(this),a,n,o,l,d,u,c,h,p,f=0,m=0,S="";if(!lm(e)){if(a=um(e),a&&(n=gt(Br(cm(e))),!~oo(n,"g")))throw mm("`.replaceAll` does not allow non-global regexes");if(o=dm(e,fm),o)return nm(o,e,i,t);if(a)return vm(gt(i),e,t)}for(l=gt(i),d=gt(e),u=om(t),u||(t=gt(t)),c=d.length,h=Sm(1,c),f=Vr(l,d,0);f!==-1;)p=u?gt(t(d,f,l)):hm(d,l,f,[],void 0,t),S+=Mr(l,m,f)+p,m=f+c,f=Vr(l,d,f+h);return m<l.length&&(S+=Mr(l,m)),S}});var bm=Wn,gm=bm("String","replaceAll"),ym=gm,Tm=ym,Em=Tm,$m=Em,Fr=ia($m);const Ur=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),a=(i==null?void 0:i[1])==="-"?-1:1,n={days:e(i==null?void 0:i[5],a),hours:e(i==null?void 0:i[6],a),minutes:e(i==null?void 0:i[7],a),seconds:e(i==null?void 0:i[8],a)};return n.days*24*60*60*1e3+n.hours*60*60*1e3+n.minutes*60*1e3+n.seconds*1e3},_s=(s,e)=>{let t=s;t=Fr(t,"$$","$");const i={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[a,n]of Object.entries(i)){const o=new RegExp(`\\$${a}(?:%0(\\d+)d)?\\$`,"g");t=Fr(t,o,(l,d)=>r.isNullable(n)?l:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},km=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,p,f,m,S,g,E,y,v,b,T,k,N,U,R,x,V,_,I,q,C,A,D,j,Z,ee,ue,ke,qe,H;const he=new DOMParser().parseFromString(s,"application/xml"),de={video:[],audio:[],text:[]},pe=he.children[0],ct=pe.getElementsByTagName("Period")[0],et=ct.children,ht=pe.getAttribute("type")==="dynamic",pt=pe.getAttribute("availabilityStartTime"),Xt=pt?new Date(pt).getTime():void 0;let tt;const Ta=pe.getAttribute("mediaPresentationDuration"),Ea=ct.getAttribute("duration"),qi=pe.getElementsByTagName("vk:Attrs")[0],$a=qi==null?void 0:qi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(Ta)tt=Ur(Ta);else if(Ea){const Se=Ur(Ea);r.isNonNullable(Se)&&(tt=Se)}else $a&&(tt=parseInt($a,10));let vo=0;const zi=(i=(t=pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],So=zi.includes(Ci.WEBM_AS_IN_FFMPEG)||zi.includes(Ci.WEBM_AS_IN_SPEC)?At.WEBM:At.MP4;for(const Se of et){const Zt=Se.getAttribute("mimeType"),bo=Se.getAttribute("codecs"),ka=(a=Se.getAttribute("contentType"))!==null&&a!==void 0?a:Zt==null?void 0:Zt.split("/")[0],go=(o=(n=Se.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],Pa=Se.querySelectorAll("Representation"),yo=Se.querySelector("SegmentTemplate");if(ka===ae.TEXT){for(const te of Pa){const ze=te.getAttribute("id")||"",ei=Se.getAttribute("lang"),ft=(u=(d=(l=te.querySelector("BaseURL"))===null||l===void 0?void 0:l.textContent)===null||d===void 0?void 0:d.trim())!==null&&u!==void 0?u:"",Wi=new URL(ft,e).toString(),Qi=ze.includes("_auto");de[ae.TEXT].push({id:ze,lang:ei,isAuto:Qi,kind:ae.TEXT,url:Wi})}continue}for(const te of Pa){const ze=(c=te.getAttribute("mimeType"))!==null&&c!==void 0?c:Zt,ei=(p=(h=te.getAttribute("codecs"))!==null&&h!==void 0?h:bo)!==null&&p!==void 0?p:"",ft=(m=(f=te.getAttribute("contentType"))!==null&&f!==void 0?f:ze==null?void 0:ze.split("/")[0])!==null&&m!==void 0?m:ka,Wi=(g=(S=Se.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&g!==void 0?g:[],Qi=parseInt((E=te.getAttribute("width"))!==null&&E!==void 0?E:"",10),Aa=parseInt((y=te.getAttribute("height"))!==null&&y!==void 0?y:"",10),wa=parseInt((v=te.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,_a=(b=te.getAttribute("frameRate"))!==null&&b!==void 0?b:"",To=(T=te.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Eo=_a?Sa(_a):void 0,$o=(k=te.getAttribute("id"))!==null&&k!==void 0?k:(vo++).toString(10),ko=ft==="video"?`${Aa}p`:ft==="audio"?`${wa}Kbps`:ei,Po=`${$o}@${ko}`,Ao=(R=(U=(N=te.querySelector("BaseURL"))===null||N===void 0?void 0:N.textContent)===null||U===void 0?void 0:U.trim())!==null&&R!==void 0?R:"",Da=new URL(Ao,e).toString(),wo=[...zi,...go,...Wi];let Ki;const _o=te.querySelector("SegmentBase"),it=(x=te.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:yo;if(_o){const It=(_=(V=te.querySelector("SegmentBase Initialization"))===null||V===void 0?void 0:V.getAttribute("range"))!==null&&_!==void 0?_:"",[xt,Xi]=It.split("-").map(mt=>parseInt(mt,10)),Nt={from:xt,to:Xi},Lt=(I=te.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Zi,ti]=Lt?Lt.split("-").map(mt=>parseInt(mt,10)):[],Ot=Lt?{from:Zi,to:ti}:void 0;Ki={type:me.BYTE_RANGE,url:Da,initRange:Nt,indexRange:Ot}}else if(it){const It={representationId:(q=te.getAttribute("id"))!==null&&q!==void 0?q:void 0,bandwidth:(C=te.getAttribute("bandwidth"))!==null&&C!==void 0?C:void 0},xt=parseInt((A=it.getAttribute("timescale"))!==null&&A!==void 0?A:"",10),Xi=(D=it.getAttribute("initialization"))!==null&&D!==void 0?D:"",Nt=it.getAttribute("media"),Lt=(Z=parseInt((j=it.getAttribute("startNumber"))!==null&&j!==void 0?j:"",10))!==null&&Z!==void 0?Z:1,Zi=_s(Xi,It);if(!Nt)throw new ReferenceError("No media attribute in SegmentTemplate");const ti=(ee=it.querySelectorAll("SegmentTimeline S"))!==null&&ee!==void 0?ee:[],Ot=[];let mt=0;if(ti.length){let es=Lt,xe=0;for(const Bt of ti){const We=parseInt((ue=Bt.getAttribute("d"))!==null&&ue!==void 0?ue:"",10),st=parseInt((ke=Bt.getAttribute("r"))!==null&&ke!==void 0?ke:"",10)||0,ii=parseInt((qe=Bt.getAttribute("t"))!==null&&qe!==void 0?qe:"",10);xe=Number.isFinite(ii)?ii:xe;const ts=We/xt*1e3,Ra=xe/xt*1e3;for(let si=0;si<st+1;si++){const Do=_s(Nt,{...It,segmentNumber:es.toString(10),segmentTime:(xe+si*We).toString(10)}),Ca=(Ra||0)+si*ts,Ro=Ca+ts;es++,Ot.push({time:{from:Ca,to:Ro},url:Do})}xe+=(st+1)*We,mt+=(st+1)*ts}}else if(r.isNonNullable(tt)){const xe=parseInt((H=it.getAttribute("duration"))!==null&&H!==void 0?H:"",10)/xt*1e3,Bt=Math.ceil(tt/xe);let We=0;for(let st=1;st<Bt;st++){const ii=_s(Nt,{...It,segmentNumber:st.toString(10),segmentTime:We.toString(10)});Ot.push({time:{from:We,to:We+xe},url:ii}),We+=xe}}Ki={type:me.TEMPLATE,baseUrl:Da,initUrl:Zi,totalSegmentsDurationMs:mt,segments:Ot}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ft||!ze)continue;const Ji={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[ft];Ji&&de[Ji].push({id:Po,kind:Ji,segmentReference:Ki,profiles:wo,duration:tt,bitrate:wa,mime:ze,codecs:ei,width:Qi,height:Aa,fps:Eo,quality:To})}}return{dynamic:ht,liveAvailabilityStartTime:Xt,duration:tt,container:So,representations:de}},ea=1e3,jr=["timeupdate","progress","play","seeked","stalled","waiting"];var fe;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(fe||(fe={}));let Pm=class{constructor(e){this.element=null,this.manifestUrlString="",this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.representationSubscription=new r.Subscription,this.state$=new K(fe.NONE),this.currentVideoRepresentation$=new r.ValueSubject(void 0),this.currentVideoRepresentationInit$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.lastConnectionType$=new r.ValueSubject(void 0),this.lastConnectionReused$=new r.ValueSubject(void 0),this.lastRequestFirstBytes$=new r.ValueSubject(void 0),this.isLive$=new r.ValueSubject(!1),this.liveDuration$=new r.ValueSubject(0),this.liveAvailabilityStartTime$=new r.ValueSubject(void 0),this.bufferLength$=new r.ValueSubject(0),this.liveLoadBufferLength$=new r.ValueSubject(0),this.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new $t,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i,a){var n;this.element=t,this.manifestUrlString=ye(i,a,se.DASH_CMAF_OFFSET_P),this.state$.startTransitionTo(fe.MANIFEST_READY),this.manifest=yield this.updateManifest(),!((n=this.manifest)===null||n===void 0)&&n.representations.video.length?this.state$.setState(fe.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.updateManifest=r.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:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:o})});if(!i)return this.manifest;let a;try{a=km(i!=null?i:"",this.manifestUrlString)}catch(o){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:o})}if(!a)return null;const n=({kind:o,mime:l,codecs:d})=>{var u,c,h,p;return!!(!((c=(u=this.element)===null||u===void 0?void 0:u.canPlayType)===null||c===void 0)&&c.call(u,l)&&(!((p=(h=window.MediaSource)===null||h===void 0?void 0:h.isTypeSupported)===null||p===void 0)&&p.call(h,`${l}; codecs="${d}"`))||o===ae.TEXT)};return this.isLive$.getValue()!==a.dynamic&&(this.isLive$.next(a.dynamic),this.liveDuration$.getValue()!==a.duration&&this.liveDuration$.next(-1*((t=a.duration)!==null&&t!==void 0?t:0)/1e3),this.liveAvailabilityStartTime$.getValue()!==a.liveAvailabilityStartTime&&this.liveAvailabilityStartTime$.next(a.liveAvailabilityStartTime)),{...a,representations:kt(Object.entries(a.representations).map(([o,l])=>[o,l.filter(n)]))}}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.representationSubscription.unsubscribe(),this.state$.startTransitionTo(fe.REPRESENTATIOS_READY),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const a={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?this.element.currentTime*1e3:void 0,manifest:this.manifest};if(this.videoBufferManager=new Lr(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new Lr(ae.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),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(r.interval(ea).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=Pr(this.manifestUrlString,se.DASH_CMAF_OFFSET_P);this.manifestUrlString=ye(this.manifestUrlString,u+1e3,se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...jr.map(l=>r.fromEvent(this.element,l))).pipe(r.throttle(ea),r.map(l=>this.element?Ke(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 p=((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 S,g;return(g=(S=m.getLiveSegmentsToLoadState(this.manifest))===null||S===void 0?void 0:S.to)!==null&&g!==void 0?g:0}))-p}this.liveLoadBufferLength$.next(h)}));let l=0;this.representationSubscription.add(this.liveLoadBufferLength$.subscribe(async d=>{r.assertNonNullable(this.element);const u=this.element.playbackRate,c=Pr(this.manifestUrlString,se.DASH_CMAF_OFFSET_P),h=Rf*u,p=If*u,f=Cf*u;l=d>l?d:l;const m=c===0&&d<f,S=c!==0&&d<h+f&&d>=h,g=c!==0&&d<h;if(g||S){const E=l-(h+p),y=Math.trunc(c+E/u);let v;d?y>0?v=y:v=0:v=c,this.manifestUrlString=ye(this.manifestUrlString,v,se.DASH_CMAF_OFFSET_P)}(m||g||S)&&(await this.updateLive(),l=0)}))}const n=r.merge(...this.bufferManagers.map(l=>l.fullyBuffered$)).pipe(r.map(()=>this.bufferManagers.every(l=>l.fullyBuffered$.getValue()))),o=r.merge(...this.bufferManagers.map(l=>l.onLastSegment$)).pipe(r.map(()=>this.bufferManagers.some(l=>l.onLastSegment$.getValue())));this.representationSubscription.add(r.merge(this.forceEnded$,r.combine({allBuffersFull:n,someBufferEnded:o}).pipe(r.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:r.ErrorCategory.VIDEO_PIPELINE,message:"Failed to end MediaSource stream",thrown:d})}})),this.representationSubscription.add(r.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)})),r.isNonNullable(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&r.isNonNullable(i)?yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(i)]):yield this.videoBufferManager.startWith(t),this.state$.setState(fe.REPRESENTATIOS_READY)}.bind(this)),this.tick=()=>{var t,i;if(!this.element||!this.videoBufferManager)return;const a=this.element.currentTime*1e3;this.videoBufferManager.maintain(a),(t=this.audioBufferManager)===null||t===void 0||t.maintain(a),(this.videoBufferManager.gaps.length||!((i=this.audioBufferManager)===null||i===void 0)&&i.gaps.length)&&!this.gapWatchdogStarted&&(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=r.interval(this.tuning.gapWatchdogInterval).subscribe(()=>this.jumpGap(),n=>{this.error$.next({id:"GapWatchdog",category:r.ErrorCategory.WTF,message:"Error handling gaps",thrown:n})}),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new Bf({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}async seekLive(e){var t,i,a,n;r.assertNonNullable(this.element),this.manifestUrlString=ye(this.manifestUrlString,e,se.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((a=this.audioBufferManager)===null||a===void 0?void 0:a.seekLive((n=this.manifest)===null||n===void 0?void 0:n.representations.audio))}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(fe.RUNNING),this.subscription.add(r.merge(...jr.map(e=>r.fromEvent(this.element,e)),r.fromEvent(window,"online")).subscribe(()=>this.tick(),e=>{this.error$.next({id:"DashVKPlayer",category:r.ErrorCategory.WTF,message:"Internal logic error",thrown:e})})),this.subscription.add(r.fromEvent(this.element,"progress").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)})),this.subscription.add(r.fromEvent(this.element,"waiting").subscribe(()=>{this.element&&this.element.readyState===2&&!this.element.seeking&&Zs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[ae.VIDEO]:this.videoBufferManager,[ae.AUDIO]:this.audioBufferManager,[ae.TEXT]:null}[e];return i==null?void 0:i.switchTo(t)}seek(e,t){var i,a,n,o,l;r.assertNonNullable(this.element),r.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=(a=this.audioBufferManager)===null||a===void 0?void 0:a.findSegmentStartTime(e))!==null&&n!==void 0?n:e),Zs(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(fe.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 a of this.bufferManagers)for(const n of a.gaps)a.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 a=Math.max(...i);a===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=a/1e3}}};class Am{constructor(e,t){this.fov=e,this.orientation=t}}class wm{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 a=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:a,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 a=-this.fadeCorrection*(this.fadeTime/1e3)**2+1;this.setRotationSpeed(this.fadeStartSpeed.x*a,this.fadeStartSpeed.y*a,this.fadeStartSpeed.z*a),a>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 _m=`#define GLSLIFY 1
|
|
30
30
|
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;}`,Dm=`#ifdef GL_ES
|
|
31
31
|
precision highp float;precision highp int;
|
|
32
32
|
#else
|