@vkontakte/videoplayer-core 2.0.92 → 2.0.93
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +7 -7
- package/es2015.esm.js +7 -7
- package/es2018.cjs.js +7 -7
- package/es2018.esm.js +7 -7
- package/esnext.cjs.js +7 -7
- package/esnext.esm.js +7 -7
- package/evergreen.esm.js +7 -7
- package/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.93
|
|
3
|
+
* Fri, 17 Nov 2023 13:52:44 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-93/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var Co=Object.create;var Ca=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&&Ca(s,a,{get:()=>e[a],enumerable:!(i=Io(e,a))||i.enumerable});return s};var Ia=(s,e,t)=>(t=s!=null?Co(No(s)):{},Oo(e||!s||!s.__esModule?Ca(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Bo=require("lodash/debounce.js");const tn="2.0.92";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 ts=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{};function ta(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")}),sn=Ni,an=Function.prototype,Us=an.call,jo=sn&&an.bind.bind(Us,Us),Ve=sn?jo:function(s){return function(){return Us.apply(s,arguments)}},rn=Ve,Ho=rn({}.toString),Go=rn("".slice),Li=function(s){return Go(Ho(s),8,-1)},Yo=Ve,qo=Me,zo=Li,is=Object,Wo=Yo("".split),Qo=qo(function(){return!is("z").propertyIsEnumerable(0)})?function(s){return zo(s)=="String"?Wo(s,""):is(s)}:is,Oi=function(s){return s==null},Ko=Oi,Jo=TypeError,ia=function(s){if(Ko(s))throw Jo("Can't call method on "+s);return s},Xo=Qo,Zo=ia,zt=function(s){return Xo(Zo(s))},_t={},ai=function(s){return s&&s.Math==Math&&s},Te=ai(typeof globalThis=="object"&&globalThis)||ai(typeof window=="object"&&window)||ai(typeof self=="object"&&self)||ai(typeof ts=="object"&&ts)||function(){return this}()||ts||Function("return this")(),js=typeof document=="object"&&document.all,el=typeof js=="undefined"&&js!==void 0,nn={all:js,IS_HTMLDDA:el},on=nn,tl=on.all,ve=on.IS_HTMLDDA?function(s){return typeof s=="function"||s===tl}:function(s){return typeof s=="function"},il=Te,sl=ve,xa=il.WeakMap,al=sl(xa)&&/native code/.test(String(xa)),Na=ve,ln=nn,rl=ln.all,ot=ln.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Na(s)||s===rl}:function(s){return typeof s=="object"?s!==null:Na(s)},nl=Me,lt=!nl(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),Dt={},ol=Te,La=ot,Hs=ol.document,ll=La(Hs)&&La(Hs.createElement),un=function(s){return ll?Hs.createElement(s):{}},ul=lt,dl=Me,cl=un,dn=!ul&&!dl(function(){return Object.defineProperty(cl("div"),"a",{get:function(){return 7}}).a!=7}),hl=lt,pl=Me,cn=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)},sa={},ss=sa,as=Te,bl=ve,Oa=function(s){return bl(s)?s:void 0},aa=function(s,e){return arguments.length<2?Oa(ss[s])||Oa(as[s]):ss[s]&&ss[s][e]||as[s]&&as[s][e]},gl=Ve,ra=gl({}.isPrototypeOf),yl=typeof navigator!="undefined"&&String(navigator.userAgent)||"",hn=Te,rs=yl,Ba=hn.process,Ma=hn.Deno,Va=Ba&&Ba.versions||Ma&&Ma.version,Fa=Va&&Va.v8,ge,Ai;Fa&&(ge=Fa.split("."),Ai=ge[0]>0&&ge[0]<4?1:+(ge[0]+ge[1]));!Ai&&rs&&(ge=rs.match(/Edge\/(\d+)/),(!ge||ge[1]>=74)&&(ge=rs.match(/Chrome\/(\d+)/),ge&&(Ai=+ge[1])));var Tl=Ai,Ua=Tl,El=Me,$l=Te,kl=$l.String,pn=!!Object.getOwnPropertySymbols&&!El(function(){var s=Symbol();return!kl(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ua&&Ua<41}),Pl=pn,fn=Pl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",Al=aa,wl=ve,_l=ra,Dl=fn,Rl=Object,mn=Dl?function(s){return typeof s=="symbol"}:function(s){var e=Al("Symbol");return wl(e)&&_l(e.prototype,Rl(s))},Cl=String,na=function(s){try{return Cl(s)}catch(e){return"Object"}},Il=ve,xl=na,Nl=TypeError,oa=function(s){if(Il(s))return s;throw Nl(xl(s)+" is not a function")},Ll=oa,Ol=Oi,Bi=function(s,e){var t=s[e];return Ol(t)?void 0:Ll(t)},ns=Fe,os=ve,ls=ot,Bl=TypeError,Ml=function(s,e){var t,i;if(e==="string"&&os(t=s.toString)&&!ls(i=ns(t,s))||os(t=s.valueOf)&&!ls(i=ns(t,s))||e!=="string"&&os(t=s.toString)&&!ls(i=ns(t,s)))return i;throw Bl("Can't convert object to primitive value")},vn={exports:{}},ja=Te,Vl=Object.defineProperty,Fl=function(s,e){try{Vl(ja,s,{value:e,configurable:!0,writable:!0})}catch(t){ja[s]=e}return e},Ul=Te,jl=Fl,Ha="__core-js_shared__",Hl=Ul[Ha]||jl(Ha,{}),Sn=Hl,Ga=Sn;(vn.exports=function(s,e){return Ga[s]||(Ga[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 bn=vn.exports,Gl=ia,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),gn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Xl(++Kl+Jl,36)},Zl=Te,eu=bn,Ya=Ue,tu=gn,iu=pn,su=fn,Tt=Zl.Symbol,us=eu("wks"),au=su?Tt.for||Tt:Tt&&Tt.withoutSetter||tu,Ee=function(s){return Ya(us,s)||(us[s]=iu&&Ya(Tt,s)?Tt[s]:au("Symbol."+s)),us[s]},ru=Fe,qa=ot,za=mn,nu=Bi,ou=Ml,lu=Ee,uu=TypeError,du=lu("toPrimitive"),cu=function(s,e){if(!qa(s)||za(s))return s;var t=nu(s,du),i;if(t){if(e===void 0&&(e="default"),i=ru(t,s,e),!qa(i)||za(i))return i;throw uu("Can't convert object to primitive value")}return e===void 0&&(e="number"),ou(s,e)},hu=cu,pu=mn,la=function(s){var e=hu(s,"string");return pu(e)?e:e+""},fu=lt,mu=dn,vu=cn,ni=ut,Wa=la,Su=TypeError,ds=Object.defineProperty,bu=Object.getOwnPropertyDescriptor,cs="enumerable",hs="configurable",ps="writable";Dt.f=fu?vu?function(e,t,i){if(ni(e),t=Wa(t),ni(i),typeof e=="function"&&t==="prototype"&&"value"in i&&ps in i&&!i[ps]){var a=bu(e,t);a&&a[ps]&&(e[t]=i.value,i={configurable:hs in i?i[hs]:a[hs],enumerable:cs in i?i[cs]:a[cs],writable:!1})}return ds(e,t,i)}:ds:function(e,t,i){if(ni(e),t=Wa(t),ni(i),mu)try{return ds(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=bn,$u=gn,Qa=Eu("keys"),ua=function(s){return Qa[s]||(Qa[s]=$u(s))},da={},ku=al,yn=Te,Pu=ot,Au=Wt,fs=Ue,ms=Sn,wu=ua,_u=da,Ka="Object already initialized",Gs=yn.TypeError,Du=yn.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 Gs("Incompatible receiver, "+s+" required");return t}};if(ku||ms.state){var ke=ms.state||(ms.state=new Du);ke.get=ke.get,ke.has=ke.has,ke.set=ke.set,wi=function(s,e){if(ke.has(s))throw Gs(Ka);return e.facade=s,ke.set(s,e),e},Gt=function(s){return ke.get(s)||{}},_i=function(s){return ke.has(s)}}else{var vt=wu("state");_u[vt]=!0,wi=function(s,e){if(fs(s,vt))throw Gs(Ka);return e.facade=s,Au(s,vt,e),e},Gt=function(s){return fs(s,vt)?s[vt]:{}},_i=function(s){return fs(s,vt)}}var Iu={set:wi,get:Gt,has:_i,enforce:Ru,getterFor:Cu},xu=Ni,Tn=Function.prototype,Ja=Tn.apply,Xa=Tn.call,Nu=typeof Reflect=="object"&&Reflect.apply||(xu?Xa.bind(Ja):function(){return Xa.apply(Ja,arguments)}),Lu=Li,Ou=Ve,En=function(s){if(Lu(s)==="Function")return Ou(s)},$n={},kn={},Pn={}.propertyIsEnumerable,An=Object.getOwnPropertyDescriptor,Bu=An&&!Pn.call({1:2},1);kn.f=Bu?function(e){var t=An(this,e);return!!t&&t.enumerable}:Pn;var Mu=lt,Vu=Fe,Fu=kn,Uu=Vi,ju=zt,Hu=la,Gu=Ue,Yu=dn,Za=Object.getOwnPropertyDescriptor;$n.f=Mu?Za:function(e,t){if(e=ju(e),t=Hu(t),Yu)try{return Za(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,er=En,ed=oa,td=Ni,id=er(er.bind),wn=function(s,e){return ed(s),e===void 0?s:td?id(s,e):function(){return s.apply(e,arguments)}},oi=Te,sd=Nu,ad=En,rd=ve,nd=$n.f,od=Zu,St=sa,ld=wn,bt=Wt,tr=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&&tr(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",tr(St,h)||bt(St,h,{}),bt(St[h],p,f),s.real&&d&&(u||!d[p])&&bt(d,p,f)))},Ys=lt,dd=Ue,_n=Function.prototype,cd=Ys&&Object.getOwnPropertyDescriptor,ca=dd(_n,"name"),hd=ca&&function(){}.name==="something",pd=ca&&(!Ys||Ys&&cd(_n,"name").configurable),fd={EXISTS:ca,PROPER:hd,CONFIGURABLE:pd},Dn={},md=Math.ceil,vd=Math.floor,Sd=Math.trunc||function(e){var t=+e;return(t>0?vd:md)(t)},bd=Sd,ha=function(s){var e=+s;return e!==e||e===0?0:bd(e)},gd=ha,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=ha,kd=Math.min,Pd=function(s){return s>0?kd($d(s),9007199254740991):0},Ad=Pd,pa=function(s){return Ad(s.length)},wd=zt,_d=Ed,Dd=pa,ir=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:ir(!0),indexOf:ir(!1)},Cd=Ve,vs=Ue,Id=zt,xd=Rd.indexOf,Nd=da,sr=Cd([].push),Ld=function(s,e){var t=Id(s),i=0,a=[],n;for(n in t)!vs(Nd,n)&&vs(t,n)&&sr(a,n);for(;e.length>i;)vs(t,n=e[i++])&&(~xd(a,n)||sr(a,n));return a},Rn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Od=Ld,Bd=Rn,Md=Object.keys||function(e){return Od(e,Bd)},Vd=lt,Fd=cn,Ud=Dt,jd=ut,Hd=zt,Gd=Md;Dn.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=aa,qd=Yd("document","documentElement"),zd=ut,Wd=Dn,ar=Rn,Qd=da,Kd=qd,Jd=un,Xd=ua,rr=">",nr="<",qs="prototype",zs="script",Cn=Xd("IE_PROTO"),Ss=function(){},In=function(s){return nr+zs+rr+s+nr+"/"+zs+rr},or=function(s){s.write(In("")),s.close();var e=s.parentWindow.Object;return s=null,e},Zd=function(){var s=Jd("iframe"),e="java"+zs+":",t;return s.style.display="none",Kd.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(In("document.F=Object")),t.close(),t.F},li,Ei=function(){try{li=new ActiveXObject("htmlfile")}catch(e){}Ei=typeof document!="undefined"?document.domain&&li?or(li):Zd():or(li);for(var s=ar.length;s--;)delete Ei[qs][ar[s]];return Ei()};Qd[Cn]=!0;var xn=Object.create||function(e,t){var i;return e!==null?(Ss[qs]=zd(e),i=new Ss,Ss[qs]=null,i[Cn]=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=ua,nc=tc,lr=rc("IE_PROTO"),Ws=Object,oc=Ws.prototype,Nn=nc?Ws.getPrototypeOf:function(s){var e=ac(s);if(ic(e,lr))return e[lr];var t=e.constructor;return sc(t)&&e instanceof t?t.prototype:e instanceof Ws?oc:null},lc=Wt,Ln=function(s,e,t,i){return i&&i.enumerable?s[e]=t:lc(s,e,t),s},uc=Me,dc=ve,cc=ot,hc=xn,ur=Nn,pc=Ln,fc=Ee,Qs=fc("iterator"),On=!1,Le,bs,gs;[].keys&&(gs=[].keys(),"next"in gs?(bs=ur(ur(gs)),bs!==Object.prototype&&(Le=bs)):On=!0);var mc=!cc(Le)||uc(function(){var s={};return Le[Qs].call(s)!==s});mc?Le={}:Le=hc(Le);dc(Le[Qs])||pc(Le,Qs,function(){return this});var Bn={IteratorPrototype:Le,BUGGY_SAFARI_ITERATORS:On},vc=Ee,Sc=vc("toStringTag"),Mn={};Mn[Sc]="z";var fa=String(Mn)==="[object z]",bc=fa,gc=ve,$i=Li,yc=Ee,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=fa,Ac=Ui,wc=Pc?{}.toString:function(){return"[object "+Ac(this)+"]"},_c=fa,Dc=Dt.f,Rc=Wt,Cc=Ue,Ic=wc,xc=Ee,dr=xc("toStringTag"),Vn=function(s,e,t,i){if(s){var a=t?s:s.prototype;Cc(a,dr)||Dc(a,dr,{configurable:!0,value:e}),i&&!_c&&Rc(a,"toString",Ic)}},Nc=Bn.IteratorPrototype,Lc=xn,Oc=Vi,Bc=Vn,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,Fn=fd,Hc=Fc,Gc=Nn,Yc=Vn,cr=Ln,qc=Ee,hr=_t,Un=Bn,zc=Fn.PROPER;Fn.CONFIGURABLE;Un.IteratorPrototype;var ui=Un.BUGGY_SAFARI_ITERATORS,ys=qc("iterator"),pr="keys",di="values",fr="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 pr:return function(){return new t(this,E)};case di:return function(){return new t(this,E)};case fr:return function(){return new t(this,E)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[ys]||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),hr[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(pr),entries:l(fr)},o)for(g in S)(ui||u||!(g in c))&&cr(c,g,S[g]);else Uc({target:e,proto:!0,forced:ui||u},S);return o&&c[ys]!==p&&cr(c,ys,p,{name:a}),hr[e]=p,S},Kc=function(s,e){return{value:s,done:e}},Jc=zt,mr=_t,jn=Iu;Dt.f;var Xc=Qc,ci=Kc,Hn="Array Iterator",Zc=jn.set,eh=jn.getterFor(Hn);Xc(Array,"Array",function(s,e){Zc(this,{type:Hn,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");mr.Arguments=mr.Array;var th=Ee,ih=_t,sh=th("iterator"),ah=Array.prototype,rh=function(s){return s!==void 0&&(ih.Array===s||ah[sh]===s)},nh=Ui,vr=Bi,oh=Oi,lh=_t,uh=Ee,dh=uh("iterator"),Gn=function(s){if(!oh(s))return vr(s,dh)||vr(s,"@@iterator")||lh[nh(s)]},ch=Fe,hh=oa,ph=ut,fh=na,mh=Gn,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,Sr=ut,gh=Bi,yh=function(s,e,t){var i,a;Sr(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 Sr(i),t},Th=wn,Eh=Fe,$h=ut,kh=na,Ph=rh,Ah=pa,br=ra,wh=Sh,_h=Gn,gr=yh,Dh=TypeError,ki=function(s,e){this.stopped=s,this.result=e},yr=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&&gr(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&&br(yr,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){gr(u,"throw",y)}if(typeof f=="object"&&f&&br(yr,f))return f}return new ki(!1)},Ch=la,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=sa,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=Te,Hh=Ui,Gh=Wt,Tr=_t,Yh=Ee,Er=Yh("toStringTag");for(var Ts in Uh){var $r=jh[Ts],Es=$r&&$r.prototype;Es&&Hh(Es)!==Er&&Gh(Es,Er,Ts),Tr[Ts]=Tr.Array}var qh=Vh,zh=qh,Wh=zh,Qh=Wh,kt=ta(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 Re=(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 kr=(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,Pr=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=Re(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(Pr).subscribe(()=>n(`timeout(${Pr})`)))});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 ye=(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)=>ye(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),je=(s,e,t,i)=>ye(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}),Je=(s,e,t,i)=>ye(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(ye(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(ye(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(ye(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(ye(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 ma=s=>{s.removeAttribute("src"),s.load()},op=s=>{try{s.pause(),s.playbackRate=0,ma(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 Ks=window.WeakMap?new WeakMap:new lp,He=s=>{let e=s.querySelector("video");const t=!!e;return e?ma(e):(e=document.createElement("video"),s.appendChild(e)),Ks.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=Ks.get(s);Ks.delete(s),e?ma(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 Yn=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},Ar=s=>{const e=Yn(s);return!!(e&&e.fullscreenElement&&e.fullscreenElement===s)},up=s=>{const e=Yn(s);return!!(e&&e.pictureInPictureElement&&e.pictureInPictureElement===s)},Js=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<Js&&(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||Js))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 qn=(s,e,t=Js)=>{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(()=>qn(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(Ar(s));return r.fromEvent(s,"fullscreenchange").pipe(r.map(()=>Ar(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}},va=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=pa,fp=ha;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=aa,zn=mp,vp=zn,Sp=vp("Array","at"),bp=Sp,gp=bp,yp=gp,Tp=yp,Ae=ta(Tp);let Sa=!1,Ne={};const Ep=s=>{Sa=s},$p=()=>{Ne={}},kp=s=>{s(Ne)},hi=(s,e)=>{var t;Sa&&(Ne.meta=(t=Ne.meta)!==null&&t!==void 0?t:{},Ne.meta[s]=e)};class we{constructor(e){this.name=e}next(e){var t,i;if(!Sa)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 we("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=Ae(T,-1))===null||f===void 0?void 0:f.quality,N=(m=Ae(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.93";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},Te=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=Te,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=Te,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=Te,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=Te,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=Te,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=Te,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=Te,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=Te,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,Ee=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=Ee,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=Te,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 ke=vs.state||(vs.state=new Du);ke.get=ke.get,ke.has=ke.has,ke.set=ke.set,wi=function(s,e){if(ke.has(s))throw Ys(Ja);return e.facade=s,ke.set(s,e),e},Gt=function(s){return ke.get(s)||{}},_i=function(s){return ke.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=Te,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=Ee,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=Ee,Sc=vc("toStringTag"),Vn={};Vn[Sc]="z";var ma=String(Vn)==="[object z]",bc=ma,gc=ve,$i=Li,yc=Ee,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=Ee,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=Ee,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=Ee,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=Ee,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=Te,Hh=Ui,Gh=Wt,Er=_t,Yh=Ee,$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 Re=(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=Re(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 ye=(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)=>ye(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),je=(s,e,t,i)=>ye(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)=>ye(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(ye(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(ye(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(ye(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(ye(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,Ae=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 we{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 we("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=Ae(T,-1))===null||f===void 0?void 0:f.quality,N=(m=Ae(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 wr{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?va(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(ye(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(ye(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(()=>qn(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(Je(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=Re(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 _r=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 Xe=async s=>{const e=s.muted;try{await s.play()}catch(t){if(!_r(t))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return _r(i)&&(s.muted=!1,console.warn(i)),!1}}return!0};function ne(){return r.now()}function Wn(s){return ne()-s}function Dr(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 _=Wn(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=Dr(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=Dr(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,$e(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=Ze=>{window.setTimeout(()=>{h()&&j(H,oe)},Ze)};if(this.sourceBuffer.updating)k("Source buffer is updating; delaying appendBuffer"),ct(100);else{const Ze=ne(),ht=T.currentTime;!this.paused&&T.buffered.length>1&&q===ht&&Ze-C>500&&(k("Stall suspected; trying to fix"),this._fixupStall()),q!==ht&&(q=ht,C=Ze);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:Ze,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())},$e=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&&Wn(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;Xe(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(Re(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(O.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return 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(Je(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(Re(this.params.source.url,o)),a&&this.dash.pause(),this.liveOffset.resetTo(o,a)}}var Qn=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}},Qe=(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 Kn{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 Kn(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 Kn(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 $e=u.parentElement;if(($e==null?void 0:$e.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=$e.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?va(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(Je(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=Qe(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=Qe(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}=Qn(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(){Xe(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 Rr{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 Jn extends Rr{constructor(){super(),this.listeners||Rr.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 Xn=class{constructor(){Object.defineProperty(this,"signal",{value:new Jn,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&&(Xn.prototype[Symbol.toStringTag]="AbortController",Jn.prototype[Symbol.toStringTag]="AbortSignal");function Zn(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(!Zn({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=Zn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),eo=Gi?Kp({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Yt=Gi?eo.fetch:window.fetch;Gi?eo.Request:window.Request;const $t=Gi?Xn:window.AbortController;var Xs=(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",Cr=Xp?Jp:window.requestIdleCallback;var $s,ks;let to=!1;try{to=r.getCurrentBrowser().browser===r.CurrentClientBrowser.Safari&&parseInt((ks=($s=navigator.userAgent.match(/Version\/(\d+)/))===null||$s===void 0?void 0:$s[1])!==null&&ks!==void 0?ks:"",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;to&&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 Ir=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 io 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:io};class mf{createBox(e,t){const i=ff[e];return i?new i(t):new io(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 xr={[$.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}},so=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 xr,n=a?xr[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},_e=(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=so(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=so(s);return wt(a.value,({tag:n,type:o,value:l})=>(n===$.EBMLReadVersion?e=_e(l,o):n===$.DocType?t=_e(l,o):n===$.DocTypeReadVersion&&(i=_e(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},ao=[$.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=_e(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=_e(m,f):p===$.Duration?a=_e(m,f):p===$.SeekPosition&&u===$.Cues?d=_e(m,f):p===$.Tracks?wt(m,({tag:g,type:E,value:y})=>g===$.ProjectionType?(c=_e(y,E)===1,!1):!0):n&&o&&ao.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=_e(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=_e(u,d));break;default:t&&ao.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},ro=1e4,Rf=3e4,Cf=5e3,If=ro,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=Ae(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Ae(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<ro&&i>=0;)e.unshift(s[i]),t+=s[i].time.to-s[i].time.from,i--;return e};class Nr{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,Ir(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=Qe(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)&&Ir(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Qe(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=Ae(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&&Qe(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Ae(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=Ae(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&&!Xs(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:Ae(e,0).byte.from,to:Ae(e,-1).byte.to};break}case me.TEMPLATE:{const u=Ae(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=Qe((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=Cr(()=>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=Cr(()=>{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}=Qn(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=Ee,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=ra,Jf=zf,Lr=RegExp.prototype,Xf=function(s){var e=s.flags;return e===void 0&&!("flags"in Lr)&&!Qf(s,"flags")&&Kf(Lr,s)?Wf(Jf,s):e},ba=Ve,Zf=Mi,em=Math.floor,Ps=ba("".charAt),tm=ba("".replace),As=ba("".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(Ps(c,0)){case"$":return"$";case"&":return s;case"`":return As(e,0,t);case"'":return As(e,o);case"<":h=a[As(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?Ps(c,1):i[f-1]+Ps(c,1):u}h=i[p-1]}return h===void 0?"":h})},rm=Fi,nm=Fe,ga=Ve,Or=ia,om=ve,lm=Oi,um=jf,gt=Yf,dm=Bi,cm=Xf,hm=am,pm=Ee,fm=pm("replace"),mm=TypeError,no=ga("".indexOf),vm=ga("".replace),Br=ga("".slice),Sm=Math.max,Mr=function(s,e,t){return t>s.length?-1:e===""?t:no(s,e,t)};rm({target:"String",proto:!0},{replaceAll:function(e,t){var i=Or(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(Or(cm(e))),!~no(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=Mr(l,d,0);f!==-1;)p=u?gt(t(d,f,l)):hm(d,l,f,[],void 0,t),S+=Br(l,m,f)+p,m=f+c,f=Mr(l,d,f+h);return m<l.length&&(S+=Br(l,m)),S}});var bm=zn,gm=bm("String","replaceAll"),ym=gm,Tm=ym,Em=Tm,$m=Em,Vr=ta($m);const Fr=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},ws=(s,e)=>{let t=s;t=Vr(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=Vr(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,$e,qe,H;const he=new DOMParser().parseFromString(s,"application/xml"),de={video:[],audio:[],text:[]},pe=he.children[0],ct=pe.getElementsByTagName("Period")[0],Ze=ct.children,ht=pe.getAttribute("type")==="dynamic",pt=pe.getAttribute("availabilityStartTime"),Xt=pt?new Date(pt).getTime():void 0;let et;const ya=pe.getAttribute("mediaPresentationDuration"),Ta=ct.getAttribute("duration"),qi=pe.getElementsByTagName("vk:Attrs")[0],Ea=qi==null?void 0:qi.getElementsByTagName("vk:XPlaybackDuration")[0].textContent;if(ya)et=Fr(ya);else if(Ta){const Se=Fr(Ta);r.isNonNullable(Se)&&(et=Se)}else Ea&&(et=parseInt(Ea,10));let mo=0;const zi=(i=(t=pe.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],vo=zi.includes(Ci.WEBM_AS_IN_FFMPEG)||zi.includes(Ci.WEBM_AS_IN_SPEC)?At.WEBM:At.MP4;for(const Se of Ze){const Zt=Se.getAttribute("mimeType"),So=Se.getAttribute("codecs"),$a=(a=Se.getAttribute("contentType"))!==null&&a!==void 0?a:Zt==null?void 0:Zt.split("/")[0],bo=(o=(n=Se.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],ka=Se.querySelectorAll("Representation"),go=Se.querySelector("SegmentTemplate");if($a===ae.TEXT){for(const te of ka){const tt=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();de[ae.TEXT].push({id:tt,lang:ei,kind:ae.TEXT,url:Wi})}continue}for(const te of ka){const tt=(c=te.getAttribute("mimeType"))!==null&&c!==void 0?c:Zt,ei=(p=(h=te.getAttribute("codecs"))!==null&&h!==void 0?h:So)!==null&&p!==void 0?p:"",ft=(m=(f=te.getAttribute("contentType"))!==null&&f!==void 0?f:tt==null?void 0:tt.split("/")[0])!==null&&m!==void 0?m:$a,Wi=(g=(S=Se.getAttribute("profiles"))===null||S===void 0?void 0:S.split(","))!==null&&g!==void 0?g:[],yo=parseInt((E=te.getAttribute("width"))!==null&&E!==void 0?E:"",10),Pa=parseInt((y=te.getAttribute("height"))!==null&&y!==void 0?y:"",10),Aa=parseInt((v=te.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,wa=(b=te.getAttribute("frameRate"))!==null&&b!==void 0?b:"",To=(T=te.getAttribute("quality"))!==null&&T!==void 0?T:void 0,Eo=wa?va(wa):void 0,$o=(k=te.getAttribute("id"))!==null&&k!==void 0?k:(mo++).toString(10),ko=ft==="video"?`${Pa}p`:ft==="audio"?`${Aa}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:"",_a=new URL(Ao,e).toString(),wo=[...zi,...bo,...Wi];let Qi;const _o=te.querySelector("SegmentBase"),it=(x=te.querySelector("SegmentTemplate"))!==null&&x!==void 0?x:go;if(_o){const It=(_=(V=te.querySelector("SegmentBase Initialization"))===null||V===void 0?void 0:V.getAttribute("range"))!==null&&_!==void 0?_:"",[xt,Ji]=It.split("-").map(mt=>parseInt(mt,10)),Nt={from:xt,to:Ji},Lt=(I=te.querySelector("SegmentBase"))===null||I===void 0?void 0:I.getAttribute("indexRange"),[Xi,ti]=Lt?Lt.split("-").map(mt=>parseInt(mt,10)):[],Ot=Lt?{from:Xi,to:ti}:void 0;Qi={type:me.BYTE_RANGE,url:_a,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),Ji=(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,Xi=ws(Ji,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 Zi=Lt,xe=0;for(const Bt of ti){const ze=parseInt((ue=Bt.getAttribute("d"))!==null&&ue!==void 0?ue:"",10),st=parseInt(($e=Bt.getAttribute("r"))!==null&&$e!==void 0?$e:"",10)||0,ii=parseInt((qe=Bt.getAttribute("t"))!==null&&qe!==void 0?qe:"",10);xe=Number.isFinite(ii)?ii:xe;const es=ze/xt*1e3,Da=xe/xt*1e3;for(let si=0;si<st+1;si++){const Do=ws(Nt,{...It,segmentNumber:Zi.toString(10),segmentTime:(xe+si*ze).toString(10)}),Ra=(Da||0)+si*es,Ro=Ra+es;Zi++,Ot.push({time:{from:Ra,to:Ro},url:Do})}xe+=(st+1)*ze,mt+=(st+1)*es}}else if(r.isNonNullable(et)){const xe=parseInt((H=it.getAttribute("duration"))!==null&&H!==void 0?H:"",10)/xt*1e3,Bt=Math.ceil(et/xe);let ze=0;for(let st=1;st<Bt;st++){const ii=ws(Nt,{...It,segmentNumber:st.toString(10),segmentTime:ze.toString(10)});Ot.push({time:{from:ze,to:ze+xe},url:ii}),ze+=xe}}Qi={type:me.TEMPLATE,baseUrl:_a,initUrl:Xi,totalSegmentsDurationMs:mt,segments:Ot}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!ft||!tt)continue;const Ki={video:ae.VIDEO,audio:ae.AUDIO,text:ae.TEXT}[ft];Ki&&de[Ki].push({id:Po,kind:Ki,segmentReference:Qi,profiles:wo,duration:et,bitrate:Aa,mime:tt,codecs:ei,width:yo,height:Pa,fps:Eo,quality:To})}}return{dynamic:ht,liveAvailabilityStartTime:Xt,duration:et,container:vo,representations:de}},Zs=1e3,Ur=["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=Re(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 Nr(ae.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new Nr(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(Zs).subscribe(l=>{var d;if(!((d=this.element)===null||d===void 0)&&d.paused){const u=kr(this.manifestUrlString,se.DASH_CMAF_OFFSET_P);this.manifestUrlString=Re(this.manifestUrlString,u+1e3,se.DASH_CMAF_OFFSET_P)}})),this.representationSubscription.add(r.merge(...Ur.map(l=>r.fromEvent(this.element,l))).pipe(r.throttle(Zs),r.map(l=>this.element?Qe(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=kr(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=Re(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=Re(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(...Ur.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&&Xs(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),Xs(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(ye(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(ye(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=Re(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,$e(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())},$e=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(Re(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(o===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(o===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const h=l==null?void 0:l.from;h&&h===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:o===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(O.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)}),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset()));return;default:return 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(Re(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 $e=u.parentElement;if(($e==null?void 0:$e.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=$e.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},_e=(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=_e(l,o):n===$.DocType?t=_e(l,o):n===$.DocTypeReadVersion&&(i=_e(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=_e(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=_e(m,f):p===$.Duration?a=_e(m,f):p===$.SeekPosition&&u===$.Cues?d=_e(m,f):p===$.Tracks?wt(m,({tag:g,type:E,value:y})=>g===$.ProjectionType?(c=_e(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=_e(u,d));break;case $.CueTrackPositions:break;case $.CueClusterPosition:o&&(o.position=_e(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=Ae(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Ae(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=Ae(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=Ae(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=Ae(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:Ae(e,0).byte.from,to:Ae(e,-1).byte.to};break}case me.TEMPLATE:{const u=Ae(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=Ee,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=Ee,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,$e,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(($e=Bt.getAttribute("r"))!==null&&$e!==void 0?$e:"",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=Re(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=Re(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=Re(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=Re(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
|
|
@@ -34,5 +34,5 @@ precision highp float;
|
|
|
34
34
|
#define GLSLIFY 1
|
|
35
35
|
#endif
|
|
36
36
|
#define PI 3.14159265358979323846264
|
|
37
|
-
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Rm{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Am(this.params.fov,this.params.orientation),this.cameraRotationManager=new wm(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(_m,this.gl.VERTEX_SHADER),i=this.createShader(Dm,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,n=e-i,o=t-a,l=e+i,d=t-a,u=e+i,c=t+a,h=e-i,p=t+a;return[n,o,l,d,u,c,h,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class oo{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.videoTracks$=new r.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new wp,this.textTracks=[],this.syncPlayback=()=>{var t,i,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===B.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==J.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),(a=this.liveOffset)===null||a===void 0||a.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}}},this.init3DScene=t=>{var i,a,n;if(this.scene3D)return;this.scene3D=new Rm(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((a=t.projectionData)===null||a===void 0?void 0:a.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Pm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Ye(this.video),a=this.constructor.name,n=l=>{e.error$.next({id:a,category:r.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(r.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(dt(this.video,t.isLooped,a)),this.subscription.add(je(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Je(this.video,t.playbackRate,i.playbackRateState$,a)),n(Di(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===fe.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const p=this.player.getRepresentations();r.assertNonNullable(p,"Manifest not loaded or empty");const f=Array.from(p.audio).sort((E,y)=>y.bitrate-E.bitrate),m=Array.from(p.video).sort((E,y)=>y.bitrate-E.bitrate),S=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(const E of f){const y=Nf(E);y&&this.audioTracks.push({track:y,representation:E})}for(const E of m){const y=xf(E);if(y){h.push({track:y,representation:E});const v=!this.params.tuning.isAudioDisabled&&Lf(f,m,E);v&&this.audioRepresentations.set(E.id,v)}}this.videoTracks$.next(h);for(const E of S){const y=Of(E);y&&this.textTracks.push({track:y,representation:E})}this.params.output.availableVideoTracks$.next(h.map(({track:E})=>E)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:E})=>E)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:E})=>E));const g=this.selectVideoRepresentation();r.assertNonNullable(g),this.player.initRepresentations(g.id,(c=this.audioRepresentations.get(g.id))===null||c===void 0?void 0:c.id)}else u===fe.REPRESENTATIOS_READY&&(this.videoState.setState(J.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==fe.RUNNING||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();if(p&&this.params.output.autoVideoTrackLimits$.next(p.to),h){this.player.switchRepresentation(ae.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ae.AUDIO,f.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,i,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=Qe(this.video.buffered,this.video.currentTime*1e3),p=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(h/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(i=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),S=Rt(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:f,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=l?S!=null?S:u:u!=null?u:S;return g&&((o=this.videoTracks$.getValue().find(({track:E})=>E===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Xe(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(J.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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}}class Cm extends oo{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Im extends oo{constructor(e){super(e),this.liveOffset=new ji}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(r.combine({interval:r.interval(Zs),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var n;if(this.videoState.getState()===J.PLAYING){const o=e.position$.getValue()+(a-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:a,liveAvailabilityStartTime:n})=>a&&n?a+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===J.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,a)})}}const Pe={};var Y;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const Ft=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class xm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(Y.INITIALIZING),this.textTracksManager=new Ce,this.trackLevels=new Map,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();if(t!==Y.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case Y.STOPPED:break;case Y.READY:case Y.PLAYING:case Y.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PLAYING:case Y.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case Y.PLAYING:break;case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case Y.PAUSED:break;case Y.STOPPED:this.prepare();break;case Y.READY:this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Y.PLAYING:this.pause();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.isLive$.next(!1),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.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(a=>{e||(Pe.Hls=a.default,Pe.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Pe.Hls,"hls.js not loaded"),this.hls=new Pe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){r.assertNonNullable(Pe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Ye(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(dt(this.video,e.isLooped,i)),this.subscription.add(je(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Je(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(Ft(this.hls,Pe.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),n(Ft(this.hls,Pe.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var p,f;const m=h.name||h.height.toString(10),{width:S,height:g}=h,E=(f=Kt((p=h.attrs.QUALITY)!==null&&p!==void 0?p:""))!==null&&f!==void 0?f:r.videoSizeToQuality({width:S,height:g});if(!E)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:E,bitrate:h.bitrate/1e3,size:{width:S,height:g},fps:y};return this.trackLevels.set(m,{track:v,level:h}),c.push(v),c},[]))),t.availableVideoTracks$),n(Ft(this.hls,Pe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const c=[];for(const h of u.subtitleTracks){const p=h.name,f=h.attrs.URI||"",m=h.lang,S="internal";c.push({id:p,url:f,language:m,type:S})}e.internalTextTracks.startTransitionTo(c)}}),n(Ft(this.hls,Pe.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>le(u))),t.hostname$),this.subscription.add(ye(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Ft(this.hls,Pe.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ye(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(r.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const p=this.hls.levels.indexOf(h),f=this.hls.currentLevel,m=this.hls.levels[f];!m||h.bitrate>m.bitrate?this.hls.nextLevel=p:(this.hls.loadLevel=p,this.hls.loadLevel=p)},{changed$:l.pipe(r.map(u=>u==null?void 0:u.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Y.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Y.PLAYING),await Xe(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(Y.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const jr="X-Playback-Duration";var Hr=async s=>{var e;const t=await Yt(s),i=await t.text(),a=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return a?parseInt(a,10):t.headers.has(jr)?parseInt(t.headers.get(jr),10):void 0};const Nm=s=>{let e=null;if(s.QUALITY&&(e=Kt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=r.videoSizeToQuality({width:t,height:i})}return e!=null?e:null},lo=async(s,e=s)=>{var t,i;const o=(await(await Yt(s)).text()).split(`
|
|
38
|
-
`),l=[],d=[];for(let u=0;u<o.length;u++){const c=o[u],h=c.match(/^#EXT-X-STREAM-INF:(.+)/),p=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!h&&!p)){if(h){const f=kt(h[1].split(",").map(b=>b.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=Nm(f);let g;f.BANDWIDTH&&(g=parseInt(f.BANDWIDTH,10)/1e3||void 0),!g&&f["AVERAGE-BANDWIDTH"]&&(g=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const E=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[b,T]=f.RESOLUTION.split("x").map(k=>parseInt(k,10));b&&T&&(y={width:b,height:T})}const v=new URL(o[++u],e).toString();S&&l.push({id:m,quality:S,url:v,bandwidth:g,size:y,fps:E})}if(p){const f=kt(p[1].split(",").map(E=>E.split("=")).map(([E,y])=>[E,y.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,g=f.NAME;m&&S&&d.push({type:"internal",id:S,label:g,language:S,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}};var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class Lm{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new K(z.STOPPED),this.textTracksManager=new Ce,this.manifests$=new r.ValueSubject([]),this.liveOffset=new ji,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(o===exports.PlaybackState.STOPPED){n!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(n===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(d||u){const p=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(p),this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested){this.videoState.startTransitionTo(z.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(n){case z.READY:o===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(n)}},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url};lo(Re(this.params.source.url),this.params.source.url).then(({qualityManifests:a})=>{this.manifests$.next([i,...a])},a=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:a})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(je(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Je(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const p=this.manifests$.getValue().find(f=>f.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(le(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===B.Requested&&this.seek(l.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?se.DASH_CMAF_OFFSET_P:se.OFFSET_P,i=Re(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),Hr(i).then(a=>{var n;if(!r.isNullable(a))this.maxSeekBackTime$.next(a);else{const o=(n=this.params.source.maxSeekBackTime)!==null&&n!==void 0?n:this.maxSeekBackTime$.getValue();if(r.isNullable(o)||!isFinite(o))try{Yt(i).then(l=>l.text()).then(l=>{var d;const u=(d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l))===null||d===void 0?void 0:d[1];if(u){const c=new URL(u,i).toString();Hr(c).then(h=>{r.isNullable(h)||this.maxSeekBackTime$.next(h)})}})}catch(l){}}})}playIfAllowed(){Xe(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),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}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var Q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(Q||(Q={}));class Om{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(Q.STOPPED),this.textTracksManager=new Ce,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){a!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Q.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:p}=this.video;this.prepare(),c.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:p*1e3,forcePrecise:!0});return}switch((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===B.Requested&&this.seek(c.position),a){case Q.READY:n===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case Q.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),lo(this.params.source.url).then(({qualityManifests:i,textTracks:a})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(a)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));if(n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Je(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Q.READY&&this.videoState.setState(Q.READY),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const p=this.manifests$.getValue().find(f=>f.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(le(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Q.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===B.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(r.merge(r.fromEvent(l,"addtrack"),r.fromEvent(l,"removetrack"),r.fromEvent(l,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<l.length;d++)l[d].mode="hidden"},i))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}prepare(){const e=this.selectManifest();r.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Xe(this.video).then(e=>{e||(this.videoState.setState(Q.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));class Bm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(X.STOPPED),this.trackUrls={},this.textTracksManager=new Ce,this.syncPlayback=()=>{var t,i,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(X.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.seekState.getState();if(u&&n!==X.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===X.STOPPED){this.videoState.startTransitionTo(X.READY),this.prepare();return}if(c){const{currentTime:p}=this.video;this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:p*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((a=(i=this.trackUrls[c.to])===null||i===void 0?void 0:i.track)===null||a===void 0?void 0:a.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested&&this.seek(h.position),n){case X.READY:o===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed());return;case X.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Je(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===X.READY&&this.videoState.setState(X.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&r.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ge(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();r.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];r.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(le(t))}playIfAllowed(){Xe(this.video).then(e=>{e||(this.videoState.setState(X.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,a;let n;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const o=(i=Object.values(this.trackUrls).find(u=>r.isLowerOrEqual(u.track.quality,e)))===null||i===void 0?void 0:i.track,l=this.params.desiredState.videoTrack.getState(),d=(a=this.trackUrls[l!=null?l:"0"])===null||a===void 0?void 0:a.track;o&&d&&r.isHigherOrEqual(d.quality,o.quality)&&(n=o)}else if(!e){const o=Object.values(this.trackUrls).map(l=>l.track);n=Rt(o,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const Gr=["stun:videostun.mycdn.me:80"],Mm=1e3,Vm=3,_s=()=>null;class Fm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=_s,this.externalStopCallback=_s,this.externalErrorCallback=_s,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Gr}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Mm)}normalizeOptions(e={}){const t={stunServerList:Gr,maxRetryNumber:Vm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var W;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));class Um{constructor(e){this.videoState=new K(W.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case W.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=He(e.container),this.liveStreamClient=new Fm(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ge(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=Ye(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(je(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case W.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.READY:break;case W.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:r.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(W.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Xe(this.video).then(e=>{e||(this.videoState.setState(W.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}))}prepare(){this.liveStreamClient.connect()}}class Yr{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var Ds,Rs,Cs,Is,xs,Ns,vi,Ls,Si,Os,bi,Bs,gi,Ms,yi,Vs,Ti,Fs;const uo=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,Ke=document.createElement("video"),jm='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Hm='video/mp4; codecs="hev1.1.6.L93.B0"',co='video/webm; codecs="vp09.00.10.08"',ho='video/webm; codecs="av01.0.00M.08"',Gm='audio/mp4; codecs="mp4a.40.2"',Ym='audio/webm; codecs="opus"',be={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Rs=(Ds=window.SourceBuffer)===null||Ds===void 0?void 0:Ds.prototype)===null||Rs===void 0)&&Rs.appendBuffer)),hls:!!(!((Cs=Ke.canPlayType)===null||Cs===void 0)&&Cs.call(Ke,"application/x-mpegurl")||!((Is=Ke.canPlayType)===null||Is===void 0)&&Is.call(Ke,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ce={mp4:!!(!((xs=Ke.canPlayType)===null||xs===void 0)&&xs.call(Ke,"video/mp4")),webm:!!(!((Ns=Ke.canPlayType)===null||Ns===void 0)&&Ns.call(Ke,"video/webm")),cmaf:!0},De={h264:!!(!((Ls=(vi=window.MediaSource)===null||vi===void 0?void 0:vi.isTypeSupported)===null||Ls===void 0)&&Ls.call(vi,jm)),h265:!!(!((Os=(Si=window.MediaSource)===null||Si===void 0?void 0:Si.isTypeSupported)===null||Os===void 0)&&Os.call(Si,Hm)),vp9:!!(!((Bs=(bi=window.MediaSource)===null||bi===void 0?void 0:bi.isTypeSupported)===null||Bs===void 0)&&Bs.call(bi,co)),av1:!!(!((Ms=(gi=window.MediaSource)===null||gi===void 0?void 0:gi.isTypeSupported)===null||Ms===void 0)&&Ms.call(gi,ho)),aac:!!(!((Vs=(yi=window.MediaSource)===null||yi===void 0?void 0:yi.isTypeSupported)===null||Vs===void 0)&&Vs.call(yi,Gm)),opus:!!(!((Fs=(Ti=window.MediaSource)===null||Ti===void 0?void 0:Ti.isTypeSupported)===null||Fs===void 0)&&Fs.call(Ti,Ym))},yt=(De.h264||De.h265)&&De.aac;var We;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(We||(We={}));var Oe;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Oe||(Oe={}));let at;const qm=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:ho}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:co}})]);at={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{qm()}catch(s){console.error(s)}const qt=be.hls&&ce.mp4,zm=()=>Object.keys(De).filter(s=>De[s]),Wm=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.DASH_SEP:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.DASH_WEBM:return be.mse&&ce.webm&&De.vp9&&De.opus;case exports.VideoFormat.DASH_WEBM_AV1:return be.mse&&ce.webm&&De.av1&&De.opus;case exports.VideoFormat.DASH_LIVE:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.DASH_LIVE_CMAF:return be.mse&&ce.mp4&&yt&&ce.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return qt||e&&be.mse&&ce.mp4&&yt;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return qt;case exports.VideoFormat.MPEG:return ce.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return be.webrtc&&be.ws&&De.h264&&(ce.mp4||ce.webm);default:return r.assertNever(t)}}),Ut=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case We.VP9:return[e,t];case We.AV1:return[t,e];case We.NONE:return[];case We.SMOOTH:return at?at[t].smooth?[t,e]:at[e].smooth?[e,t]:[t,e]:[e,t];case We.POWER_EFFICIENT:return at?at[t].powerEfficient?[t,e]:at[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(s)}return[e,t]},Qm=({webmCodec:s,androidPreferredFormat:e})=>{if(uo)switch(e){case Oe.MPEG:return[exports.VideoFormat.MPEG,...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case Oe.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case Oe.DASH:return[...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return qt?[...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Km=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],a=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...a],o=[...a,...i];let l;if(uo)switch(s){case Oe.DASH:{l=n;break}case Oe.HLS:case Oe.MPEG:{l=o;break}}else qt?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},qr=s=>s?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Jm=s=>new r.Observable(e=>{const t=new r.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:c})=>`${u}-${c}`)),a=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(r.map(({type:u})=>u!==void 0)),o=new r.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Xm={cacheDuration:12e4},Zm={chunkDuration:5e3,maxParallelRequests:5};class ev{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Wm([...Km(this.params.tuning),...Qm(this.params.tuning)],this.params.tuning.useHlsJs).filter(l=>r.isNonNullable(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning;let n=[];i?n=[i]:a.length?n=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new Yr(n);const o=[...qr(!0),...qr(!1)];this.chromecastFormatsIterator=new Yr(o.filter(l=>r.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==B.None;if(this.params.desiredState.seekState.setState({state:B.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case re.SCREEN:return this.createScreenProvider(t);case re.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Qp({...o,source:l,config:Xm})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new wr({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new Cm({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJsCMAF?new wr({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new Im({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),qt||!this.params.tuning.useHlsJs?new Om({...o,source:l}):new xm({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Lm({...o,source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Bm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Gp({...o,source:l,config:{...Zm,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Um({container:i,source:l,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new ep({connection:l,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?re.CHROMECAST:re.SCREEN}chooseFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case re.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.next();case re.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case re.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case re.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return kt(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;return e.add(r.merge(this.providerOutput.error$,Jm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===re.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(re.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===r.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:re.SCREEN)}})),e}}const ea=(s,e,t)=>t*e+(1-t)*s,po=(s,e)=>s.reduce((t,i)=>t+i,0)/e,tv=(s,e,t,i)=>{let a=0,n=t;const o=po(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?a++:a--,n=(s.length+n-1)%s.length;return Math.abs(a)===l};class fo{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new we(`raw_${i}`),this.smoothedSeries$=new we(`smoothed_${i}`),this.reportedSeries$=new we(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class iv extends fo{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ea(this.slow,e,this.params.emaAlphaSlow),this.fast=ea(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class sv extends fo{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=po(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ea(this.emaSmoothed,e,this.params.emaAlpha);const i=tv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class zr{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new iv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new sv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const av=5e3,Wr="one_video_throughput",Qr="one_video_rtt",Be=window.navigator.connection,Kr=()=>{const s=Be==null?void 0:Be.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},Jr=()=>{const s=Be==null?void 0:Be.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Xr=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class Ht{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Ht.load(Wr)||(e.useBrowserEstimation?Kr():void 0)||av,n=(i=(t=Ht.load(Qr))!==null&&t!==void 0?t:e.useBrowserEstimation?Jr():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Xr(a,n,e.rttPenaltyRequestSize)),this.throughput=zr.getSmoothedValue(a,-1,e),this.rtt=zr.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Kr();d&&this.throughput.next(d);const u=Jr();r.isNonNullable(u)&&this.rtt.next(u)};Be&&"onchange"in Be&&this.subscription.add(r.fromEvent(Be,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{r.safeStorage.set(Wr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{r.safeStorage.set(Qr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Xr(o,l,e.rttPenaltyRequestSize)),r.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=r.now();let n=0,o=r.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{u?(this.addRawSpeed(i,r.now()-a,1),this.concurrentDownloads.delete(e)):c&&(i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&r.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,r.now()-o,this.concurrentDownloads.size),n=0,o=r.now()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Ht.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=r.safeStorage.get(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Zr={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:We.VP9,androidPreferredFormat:Oe.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},rv=s=>{var e;return{...r.fillWithDefault(s,Zr),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...Zr.configName]}};var en=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===B.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===B.None))),nv=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};class ov{constructor(e={configName:[]}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:B.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),internalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({}),cameraOrientation:new K({x:0,y:0})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:kp},this.initLogs(),this.tuning=rv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Vo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ht(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(p,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,a;return this.config=e,this.domContainer=nv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new ev({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=i&&!a&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;r.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t,i,a;return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&((t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$.getValue().length)===0?(i=this.providerContainer)===null||i===void 0||i.providerOutput.availableTextTracks$.pipe(r.filter(n=>n.length>0),r.once()).subscribe(n=>{n.find(o=>o.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||!((a=this.providerContainer)===null||a===void 0)&&a.providerOutput.availableTextTracks$.getValue().find(n=>n.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const a=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+n.x,y:a.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){r.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===B.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===B.Requested?this.desiredState.seekState.setState({...o,state:B.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:l})=>l).sort((l,d)=>r.isInvariantQuality(l)?1:r.isInvariantQuality(d)?-1:r.isHigher(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(r.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:en({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:l,isLowLatency:d})=>{const u=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(l)<u/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:l,duration:d})=>o&&Math.abs(d)-Math.abs(l)<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(en({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o!=null?o:r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.getValue();return o&&!l}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),$p(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Ep(i)),this.providerContainer.current$.subscribe(({type:i})=>hi("provider",i)),t.duration$.subscribe(i=>hi("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>hi("tracks",i)),this.events.fatalError$.subscribe(new we("fatalError")),this.events.managedError$.subscribe(new we("managedError")),t.position$.subscribe(new we("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new we("quality")),this.info.currentBuffer$.subscribe(new we("buffer")),t.isBuffering$.subscribe(new we("isBuffering"))].forEach(i=>this.subscription.add(i)),hi("codecs",zm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const lv=`@vkontakte/videoplayer-core@${tn}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=ov;exports.SDK_VERSION=lv;exports.VERSION=tn;
|
|
37
|
+
varying vec2 v_texel;uniform sampler2D u_texture;uniform vec2 u_focus;void main(void){float lambda0=u_focus.x/360.0;float phi0=u_focus.y/180.0;float lambda=PI*2.0*(v_texel.x-0.5-lambda0);float phi=PI*(v_texel.y-0.5-phi0);float p=sqrt(lambda*lambda+phi*phi);float c=atan(p);float cos_c=cos(c);float sin_c=sin(c);float x=lambda0+atan(lambda*sin_c,p*cos(phi0)*cos_c-phi*sin(phi0)*sin_c);float y=asin(cos_c*sin(phi0)+(phi*sin_c*cos(phi0))/p);vec2 tc=vec2(mod(x/(PI*2.0)-0.5,1.0),mod(y/PI-0.5,1.0));gl_FragColor=texture2D(u_texture,tc);}`;class Rm{constructor(e,t,i){this.videoInitialized=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.params=i,this.canvas=this.createCanvas();const a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.container.appendChild(this.canvas),this.camera=new Am(this.params.fov,this.params.orientation),this.cameraRotationManager=new wm(this.camera,{rotationSpeed:this.params.rotationSpeed,maxYawAngle:this.params.maxYawAngle,rotationSpeedCorrection:this.params.rotationSpeedCorrection,degreeToPixelCorrection:this.params.degreeToPixelCorrection,speedFadeTime:this.params.speedFadeTime,speedFadeThreshold:this.params.speedFadeThreshold}),this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.videoElementDataLoadedFn=this.onDataLoadedHandler.bind(this),this.renderFn=this.render.bind(this)}play(){this.active||(this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",this.videoElementDataLoadedFn))}stop(){this.active=!1}startCameraManualRotation(e,t){this.cameraRotationManager.setRotationSpeed(e*this.params.rotationSpeed,t*this.params.rotationSpeed,0),this.cameraRotationManager.startRotation()}stopCameraManualRotation(e=!1){this.cameraRotationManager.stopRotation(e)}turnCamera(e,t){this.cameraRotationManager.turnCamera(e,t)}pointCameraTo(e,t){this.cameraRotationManager.pointCameraTo(e,t)}pixelToDegree(e){return{x:this.params.degreeToPixelCorrection*this.params.fov.x*-e.x/this.viewportWidth,y:this.params.degreeToPixelCorrection*this.params.fov.y*e.y/this.viewportHeight}}getCameraRotation(){return this.camera.orientation}holdCamera(){this.cameraRotationManager.stopRotation(!0)}releaseCamera(){this.cameraRotationManager.onCameraRelease()}destroy(){this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),this.stop(),this.canvas.remove()}setViewportSize(e,t){this.viewportWidth=e,this.viewportHeight=t,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}onDataLoadedHandler(){this.videoInitialized=!0,this.doPlay()}doPlay(){this.updateFrameSize(),this.vertexBuffer=this.createVertexBuffer(),this.active=!0,this.sourceVideoElement.removeEventListener("loadeddata",this.videoElementDataLoadedFn),requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateTexture(),this.updateTextureMappingBuffer();const t=this.gl.getAttribLocation(this.program,"a_vertex"),i=this.gl.getAttribLocation(this.program,"a_texel"),a=this.gl.getUniformLocation(this.program,"u_texture"),n=this.gl.getUniformLocation(this.program,"u_focus");this.gl.enableVertexAttribArray(t),this.gl.enableVertexAttribArray(i),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.vertexBuffer),this.gl.vertexAttribPointer(t,2,this.gl.FLOAT,!1,0,0),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.vertexAttribPointer(i,2,this.gl.FLOAT,!1,0,0),this.gl.activeTexture(this.gl.TEXTURE0),this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.uniform1i(a,0),this.gl.uniform2f(n,-this.camera.orientation.x,-this.camera.orientation.y),this.gl.drawArrays(this.gl.TRIANGLE_FAN,0,4),this.gl.bindTexture(this.gl.TEXTURE_2D,null),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),this.gl.disableVertexAttribArray(t),this.gl.disableVertexAttribArray(i),this.active&&requestAnimationFrame(this.renderFn)}createShader(e,t){const i=this.gl.createShader(t);if(!i)throw this.destroy(),new Error(`Could not create shader (${t})`);if(this.gl.shaderSource(i,e),this.gl.compileShader(i),!this.gl.getShaderParameter(i,this.gl.COMPILE_STATUS))throw this.destroy(),new Error("An error occurred while compiling the shader: "+this.gl.getShaderInfoLog(i));return i}createProgram(){const e=this.gl.createProgram();if(!e)throw this.destroy(),new Error("Could not create shader program");const t=this.createShader(_m,this.gl.VERTEX_SHADER),i=this.createShader(Dm,this.gl.FRAGMENT_SHADER);if(this.gl.attachShader(e,t),this.gl.attachShader(e,i),this.gl.linkProgram(e),!this.gl.getProgramParameter(e,this.gl.LINK_STATUS))throw this.destroy(),new Error("Could not link shader program.");return e}createTexture(){const e=this.gl.createTexture();if(!e)throw this.destroy(),new Error("Could not create texture");return this.gl.bindTexture(this.gl.TEXTURE_2D,e),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MAG_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_MIN_FILTER,this.gl.LINEAR),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_S,this.gl.CLAMP_TO_EDGE),this.gl.texParameteri(this.gl.TEXTURE_2D,this.gl.TEXTURE_WRAP_T,this.gl.CLAMP_TO_EDGE),this.gl.bindTexture(this.gl.TEXTURE_2D,null),e}updateTexture(){this.gl.bindTexture(this.gl.TEXTURE_2D,this.videoTexture),this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!0),this.gl.texImage2D(this.gl.TEXTURE_2D,0,this.gl.RGBA,this.gl.RGBA,this.gl.UNSIGNED_BYTE,this.sourceVideoElement),this.gl.bindTexture(this.gl.TEXTURE_2D,null)}createVertexBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create vertex buffer");let t=1,i=1;const a=this.frameHeight/(this.frameWidth/this.viewportWidth);return a>this.viewportHeight?t=this.viewportHeight/a:i=a/this.viewportHeight,this.gl.bindBuffer(this.gl.ARRAY_BUFFER,e),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([-t,-i,t,-i,t,i,-t,i]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null),e}createTextureMappingBuffer(){const e=this.gl.createBuffer();if(!e)throw this.destroy(),new Error("Could not create texture mapping buffer");return e}calculateTexturePosition(){const e=.5-this.camera.orientation.x/360,t=.5-this.camera.orientation.y/180,i=this.camera.fov.x/360/2,a=this.camera.fov.y/180/2,n=e-i,o=t-a,l=e+i,d=t-a,u=e+i,c=t+a,h=e-i,p=t+a;return[n,o,l,d,u,c,h,p]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateFrameSize(){this.frameWidth=this.sourceVideoElement.videoWidth,this.frameHeight=this.sourceVideoElement.videoHeight}createCanvas(){const e=document.createElement("canvas");return e.style.position="absolute",e.style.left="0",e.style.top="0",e.style.width="100%",e.style.height="100%",e}}class lo{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new Ce,this.droppedFramesManager=new Hi,this.videoTracks$=new r.ValueSubject([]),this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new wp,this.textTracks=[],this.syncPlayback=()=>{var t,i,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition()){if(d.state===B.Requested&&(l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&n!==J.STOPPED&&o!==exports.PlaybackState.STOPPED){const c=(i=(t=this.liveOffset)===null||t===void 0?void 0:t.getTotalPausedTime())!==null&&i!==void 0?i:0;this.seek(d.position-c,d.forcePrecise)}if(o===exports.PlaybackState.STOPPED){n!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(J.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(n){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:o===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.READY&&P(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),(a=this.liveOffset)===null||a===void 0||a.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.liveOffset?this.liveOffset.getTotalOffset()/1e3<Math.abs(this.params.output.duration$.getValue())?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(0,!1):this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}}},this.init3DScene=t=>{var i,a,n;if(this.scene3D)return;this.scene3D=new Rm(this.params.container,this.video,{fov:this.params.tuning.spherical.fov,orientation:this.params.tuning.spherical.orientation||{x:((i=t.projectionData)===null||i===void 0?void 0:i.pose.yaw)||0,y:((a=t.projectionData)===null||a===void 0?void 0:a.pose.pitch)||0,z:((n=t.projectionData)===null||n===void 0?void 0:n.pose.roll)||0},rotationSpeed:this.params.tuning.spherical.rotationSpeed,maxYawAngle:this.params.tuning.spherical.maxYawAngle,rotationSpeedCorrection:this.params.tuning.spherical.rotationSpeedCorrection,degreeToPixelCorrection:this.params.tuning.spherical.degreeToPixelCorrection,speedFadeTime:this.params.tuning.spherical.speedFadeTime,speedFadeThreshold:this.params.tuning.spherical.speedFadeThreshold});const o=this.elementSize$.getValue();o&&this.scene3D.setViewportSize(o.width,o.height)},this.destroy3DScene=()=>{this.scene3D&&(this.scene3D.destroy(),this.scene3D=void 0)},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Pm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}getProviderSubscriptionInfo(){const{output:e,desiredState:t}=this.params,i=Ye(this.video),a=this.constructor.name,n=l=>{e.error$.next({id:a,category:r.ErrorCategory.WTF,message:`${a} internal logic error`,thrown:l})};return{output:e,desiredState:t,observableVideo:i,genericErrorListener:n,connect:(l,d)=>this.subscription.add(l.subscribe(d,n))}}subscribe(){const{output:e,desiredState:t,observableVideo:i,genericErrorListener:a,connect:n}=this.getProviderSubscriptionInfo();this.droppedFramesManager.connect({logger:this.params.dependencies.logger,video:this.video,droppedFramesChecker:this.params.tuning.droppedFramesChecker,isAuto:this.params.desiredState.autoVideoTrackSwitching,playing$:i.playing$,pause$:i.pause$,tracks$:this.videoTracks$.pipe(r.map(u=>u.map(({track:c})=>c)))}),n(i.ended$,e.endedEvent$),n(i.looped$,e.loopedEvent$),n(i.error$,e.error$),n(i.isBuffering$,e.isBuffering$),n(i.currentBuffer$,e.currentBuffer$),n(i.playing$,e.firstFrameEvent$),n(i.canplay$,e.canplay$),n(i.inPiP$,e.inPiP$),n(i.inFullscreen$,e.inFullscreen$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.isLive$,e.isLive$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once()),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(dt(this.video,t.isLooped,a)),this.subscription.add(je(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Xe(this.video,t.playbackRate,i.playbackRateState$,a)),n(Di(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING),this.scene3D&&this.scene3D.play()},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},a)).add(i.canplay$.subscribe(()=>{this.videoState.getState()===J.PLAYING&&this.playIfAllowed()},a)),this.subscription.add(this.player.state$.stateChangeEnded$.subscribe(({to:u})=>{var c;if(u===fe.MANIFEST_READY){const h=[];this.audioTracks=[],this.textTracks=[];const p=this.player.getRepresentations();r.assertNonNullable(p,"Manifest not loaded or empty");const f=Array.from(p.audio).sort((E,y)=>y.bitrate-E.bitrate),m=Array.from(p.video).sort((E,y)=>y.bitrate-E.bitrate),S=Array.from(p.text);if(!this.params.tuning.isAudioDisabled)for(const E of f){const y=Nf(E);y&&this.audioTracks.push({track:y,representation:E})}for(const E of m){const y=xf(E);if(y){h.push({track:y,representation:E});const v=!this.params.tuning.isAudioDisabled&&Lf(f,m,E);v&&this.audioRepresentations.set(E.id,v)}}this.videoTracks$.next(h);for(const E of S){const y=Of(E);y&&this.textTracks.push({track:y,representation:E})}this.params.output.availableVideoTracks$.next(h.map(({track:E})=>E)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:E})=>E)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length),this.textTracks.length>0&&this.params.desiredState.internalTextTracks.startTransitionTo(this.textTracks.map(({track:E})=>E));const g=this.selectVideoRepresentation();r.assertNonNullable(g),this.player.initRepresentations(g.id,(c=this.audioRepresentations.get(g.id))===null||c===void 0?void 0:c.id)}else u===fe.REPRESENTATIOS_READY&&(this.videoState.setState(J.READY),this.player.initBuffer())},a));const o=u=>e.error$.next({id:"RepresentationSwitch",category:r.ErrorCategory.WTF,message:"Switching representations threw",thrown:u});this.subscription.add(r.merge(this.player.state$.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,t.autoVideoTrackLimits.stateChangeStarted$,this.elementSize$,this.droppedFramesManager.onDroopedVideoFramesLimit$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==fe.RUNNING||c||!this.videoTracks$.getValue().length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation(),p=this.params.desiredState.autoVideoTrackLimits.getTransition();if(p&&this.params.output.autoVideoTrackLimits$.next(p.to),h){this.player.switchRepresentation(ae.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(ae.AUDIO,f.id).catch(o)}},a)),this.subscription.add(t.cameraOrientation.stateChangeEnded$.subscribe(({to:u})=>{this.scene3D&&u&&this.scene3D.pointCameraTo(u.x,u.y)})),this.subscription.add(this.elementSize$.subscribe(u=>{this.scene3D&&u&&this.scene3D.setViewportSize(u.width,u.height)})),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var c;return u&&((c=this.videoTracks$.getValue().find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,a)),this.subscription.add(this.player.currentVideoRepresentationInit$.subscribe(u=>{var c,h;if(u!=null&&u.is3dVideo&&(!((c=this.params.tuning.spherical)===null||c===void 0)&&c.enabled))try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(p){e.warning$.next({id:"DashVKProvider",message:`DashVKProvider could not initialize 3D-scene: ${p}`})}else this.destroy3DScene(),!((h=this.params.tuning.spherical)===null||h===void 0)&&h.enabled&&e.is3DVideo$.next(!1)},a)),this.textTracksManager.connect(this.video,t,e);const l=t.playbackState.stateChangeStarted$.pipe(r.map(({to:u})=>u===exports.PlaybackState.READY),r.filterChanged());this.subscription.add(r.merge(l,t.autoVideoTrackSwitching.stateChangeStarted$,this.player.state$.stateChangeEnded$).subscribe(()=>{const u=t.autoVideoTrackSwitching.getState(),h=t.playbackState.getState()===exports.PlaybackState.READY?this.params.tuning.dash.forwardBufferTargetPreload:u?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual;this.player.setBufferTarget(h)})),this.subscription.add(r.merge(l,this.player.state$.stateChangeEnded$).subscribe(()=>this.player.setPreloadOnly(t.playbackState.getState()===exports.PlaybackState.READY)));const d=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,a))}selectVideoRepresentation(){var e,t,i,a,n,o;const l=this.params.desiredState.autoVideoTrackSwitching.getState(),d=this.params.desiredState.videoTrack.getState(),u=(e=this.videoTracks$.getValue().find(({track:{id:E}})=>E===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=Ke(this.video.buffered,this.video.currentTime*1e3),p=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,f=Math.min(h/Math.min(p,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),m=Math.max(u&&!l&&(i=(t=this.audioRepresentations.get(u.id))===null||t===void 0?void 0:t.bitrate)!==null&&i!==void 0?i:0,c&&(n=(a=this.audioRepresentations.get(c.id))===null||a===void 0?void 0:a.bitrate)!==null&&n!==void 0?n:0),S=Rt(this.videoTracks$.getValue().map(({track:E})=>E),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:m,forwardBufferHealth:f,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate,droppedVideoMaxQualityLimit:this.droppedFramesManager.droppedVideoMaxQualityLimit,abrLogger:this.params.dependencies.abrLogger}),g=l?S!=null?S:u:u!=null?u:S;return g&&((o=this.videoTracks$.getValue().find(({track:E})=>E===g))===null||o===void 0?void 0:o.representation)}prepare(e=0){this.player.initManifest(this.video,this.params.source.url,e)}playIfAllowed(){Ze(this.video).then(e=>{var t;e||((t=this.liveOffset)===null||t===void 0||t.pause(),this.videoState.setState(J.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}))}destroy(){this.subscription.unsubscribe(),this.droppedFramesManager.destroy(),this.destroy3DScene(),this.textTracksManager.destroy(),this.player.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}}class Cm extends lo{subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();i(t.timeUpdate$,e.position$),i(t.durationChange$,e.duration$)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}}class Im extends lo{constructor(e){super(e),this.liveOffset=new ji}subscribe(){super.subscribe();const{output:e,observableVideo:t,connect:i}=this.getProviderSubscriptionInfo();this.params.output.position$.next(0),i(t.timeUpdate$,e.liveBufferTime$),i(this.player.liveDuration$,e.duration$),this.subscription.add(r.combine({interval:r.interval(ea),playbackRate:t.playbackRateState$}).subscribe(({playbackRate:a})=>{var n;if(this.videoState.getState()===J.PLAYING){const o=e.position$.getValue()+(a-1);e.position$.next(o),(n=this.liveOffset)===null||n===void 0||n.resetTo(-o*1e3)}})).add(r.combine({liveBufferTime:e.liveBufferTime$,liveAvailabilityStartTime:this.player.liveAvailabilityStartTime$}).pipe(r.map(({liveBufferTime:a,liveAvailabilityStartTime:n})=>a&&n?a+n:void 0)).subscribe(e.liveTime$))}seek(e){this.params.output.willSeekEvent$.next();const t=this.params.desiredState.playbackState.getState(),i=this.videoState.getState(),a=t===exports.PlaybackState.PAUSED&&i===J.PAUSED,n=-e,o=Math.trunc(n/1e3<=Math.abs(this.params.output.duration$.getValue())?n:0);this.player.seekLive(o).then(()=>{var l;this.params.output.position$.next(e/1e3),(l=this.liveOffset)===null||l===void 0||l.resetTo(o,a)})}}const Pe={};var Y;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));const Ft=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class xm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(Y.INITIALIZING),this.textTracksManager=new Ce,this.trackLevels=new Map,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();if(t!==Y.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===B.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case Y.STOPPED:break;case Y.READY:case Y.PLAYING:case Y.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PLAYING:case Y.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case Y.PLAYING:break;case Y.STOPPED:this.prepare();break;case Y.READY:case Y.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case Y.PAUSED:break;case Y.STOPPED:this.prepare();break;case Y.READY:this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Y.PLAYING:this.pause();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.isLive$.next(!1),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.loadHlsJs()}destroy(){var e,t;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),(e=this.hls)===null||e===void 0||e.detachMedia(),(t=this.hls)===null||t===void 0||t.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}loadHlsJs(){let e=!1;const t=a=>{e||this.params.output.error$.next({id:a==="timeout"?"HlsJsTimeout":"HlsJsLoadError",category:r.ErrorCategory.NETWORK,message:"Failed to load Hls.js",thrown:a}),e=!0},i=window.setTimeout(()=>t("timeout"),this.params.tuning.dynamicImportTimeout);import("hls.js").then(a=>{e||(Pe.Hls=a.default,Pe.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Pe.Hls,"hls.js not loaded"),this.hls=new Pe.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Y.STOPPED)}subscribe(){r.assertNonNullable(Pe.Events,"hls.js not loaded");const{desiredState:e,output:t}=this.params,i=u=>{t.error$.next({id:"HlsJsProvider",category:r.ErrorCategory.WTF,message:"HlsJsProvider internal logic error",thrown:u})},a=Ye(this.video),n=(u,c)=>this.subscription.add(u.subscribe(c,i));n(a.timeUpdate$,t.position$),n(a.durationChange$,t.duration$),n(a.ended$,t.endedEvent$),n(a.looped$,t.loopedEvent$),n(a.error$,t.error$),n(a.isBuffering$,t.isBuffering$),n(a.currentBuffer$,t.currentBuffer$),n(a.loadStart$,t.firstBytesEvent$),n(a.playing$,t.firstFrameEvent$),n(a.canplay$,t.canplay$),n(a.seeked$,t.seekedEvent$),n(a.inPiP$,t.inPiP$),n(a.inFullscreen$,t.inFullscreen$),this.subscription.add(dt(this.video,e.isLooped,i)),this.subscription.add(je(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Xe(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(Ft(this.hls,Pe.Events.ERROR).subscribe(u=>{var c;u.fatal&&t.error$.next({id:["HlsJsFatal",u.type,u.details].join("_"),category:r.ErrorCategory.WTF,message:`HlsJs fatal ${u.type} ${u.details}, ${(c=u.err)===null||c===void 0?void 0:c.message} ${u.reason}`,thrown:u.error})})),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING),P(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED),P(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===Y.READY&&this.videoState.setState(Y.READY),this.videoState.getState()===Y.PLAYING&&this.playIfAllowed()},i)),n(Ft(this.hls,Pe.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var p,f;const m=h.name||h.height.toString(10),{width:S,height:g}=h,E=(f=Kt((p=h.attrs.QUALITY)!==null&&p!==void 0?p:""))!==null&&f!==void 0?f:r.videoSizeToQuality({width:S,height:g});if(!E)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,v={id:m.toString(),quality:E,bitrate:h.bitrate/1e3,size:{width:S,height:g},fps:y};return this.trackLevels.set(m,{track:v,level:h}),c.push(v),c},[]))),t.availableVideoTracks$),n(Ft(this.hls,Pe.Events.MANIFEST_PARSED),u=>{if(u.subtitleTracks.length>0){const c=[];for(const h of u.subtitleTracks){const p=h.name,f=h.attrs.URI||"",m=h.lang,S="internal";c.push({id:p,url:f,language:m,type:S})}e.internalTextTracks.startTransitionTo(c)}}),n(Ft(this.hls,Pe.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>le(u))),t.hostname$),this.subscription.add(ye(e.autoVideoTrackSwitching,()=>this.hls.autoLevelEnabled,u=>{this.hls.nextLevel=u?-1:this.hls.currentLevel,this.hls.loadLevel=u?-1:this.hls.loadLevel},{onError:i}));const o=u=>{var c;return(c=Array.from(this.trackLevels.values()).find(({level:h})=>h===u))===null||c===void 0?void 0:c.track},l=Ft(this.hls,Pe.Events.LEVEL_SWITCHED).pipe(r.map(({level:u})=>o(this.hls.levels[u])));l.pipe(r.filter(r.isNonNullable)).subscribe(t.currentVideoTrack$,i),this.subscription.add(ye(e.videoTrack,()=>{var u;return(u=o(this.hls.levels[this.hls.currentLevel]))===null||u===void 0?void 0:u.id},u=>{var c;if(r.isNullable(u))return;const h=(c=this.trackLevels.get(u))===null||c===void 0?void 0:c.level;if(!h)return;const p=this.hls.levels.indexOf(h),f=this.hls.currentLevel,m=this.hls.levels[f];!m||h.bitrate>m.bitrate?this.hls.nextLevel=p:(this.hls.loadLevel=p,this.hls.loadLevel=p)},{changed$:l.pipe(r.map(u=>u==null?void 0:u.id)),onError:i})),n(a.progress$,()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)}),this.textTracksManager.connect(this.video,e,t);const d=r.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(d.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Y.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(Y.PLAYING),await Ze(this.video).catch(t=>this.params.output.error$.next({id:"ForcePlay",message:"play() failed even with workarounds",category:r.ErrorCategory.DOM,thrown:t}))||(this.videoState.setState(Y.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.removeAttribute("src"),this.video.load(),this.videoState.setState(Y.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Hr="X-Playback-Duration";var Gr=async s=>{var e;const t=await Yt(s),i=await t.text(),a=(e=/#EXT-X-VK-PLAYBACK-DURATION:(\d+)/m.exec(i))===null||e===void 0?void 0:e[1];return a?parseInt(a,10):t.headers.has(Hr)?parseInt(t.headers.get(Hr),10):void 0};const Nm=s=>{let e=null;if(s.QUALITY&&(e=Kt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=r.videoSizeToQuality({width:t,height:i})}return e!=null?e:null},uo=async(s,e=s)=>{var t,i;const o=(await(await Yt(s)).text()).split(`
|
|
38
|
+
`),l=[],d=[];for(let u=0;u<o.length;u++){const c=o[u],h=c.match(/^#EXT-X-STREAM-INF:(.+)/),p=c.match(/^#EXT-X-MEDIA:TYPE=SUBTITLES,(.+)/);if(!(!h&&!p)){if(h){const f=kt(h[1].split(",").map(b=>b.split("="))),m=(t=f.QUALITY)!==null&&t!==void 0?t:`stream-${f.BANDWIDTH}`,S=Nm(f);let g;f.BANDWIDTH&&(g=parseInt(f.BANDWIDTH,10)/1e3||void 0),!g&&f["AVERAGE-BANDWIDTH"]&&(g=parseInt(f["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const E=f["FRAME-RATE"]?parseFloat(f["FRAME-RATE"]):void 0;let y;if(f.RESOLUTION){const[b,T]=f.RESOLUTION.split("x").map(k=>parseInt(k,10));b&&T&&(y={width:b,height:T})}const v=new URL(o[++u],e).toString();S&&l.push({id:m,quality:S,url:v,bandwidth:g,size:y,fps:E})}if(p){const f=kt(p[1].split(",").map(E=>E.split("=")).map(([E,y])=>[E,y.replace(/^"|"$/g,"")])),m=(i=f.URI)===null||i===void 0?void 0:i.replace(/playlist$/,"subtitles.vtt"),S=f.LANGUAGE,g=f.NAME;m&&S&&d.push({type:"internal",id:S,label:g,language:S,url:m,isAuto:!1})}}}return{qualityManifests:l,textTracks:d}};var z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class Lm{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new K(z.STOPPED),this.textTracksManager=new Ce,this.manifests$=new r.ValueSubject([]),this.liveOffset=new ji,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition(),d=this.params.desiredState.videoTrack.getTransition(),u=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(o===exports.PlaybackState.STOPPED){n!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const h=this.params.desiredState.seekState.getState();if(n===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(d||u){const p=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(p),this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested){this.videoState.startTransitionTo(z.READY),this.seek(h.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(n){case z.READY:o===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.liveOffset.pause(),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&(P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(n)}},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url};uo(Re(this.params.source.url),this.params.source.url).then(({qualityManifests:a})=>{this.manifests$.next([i,...a])},a=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:a})),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),this.maxSeekBackTime$=new r.ValueSubject((t=e.source.maxSeekBackTime)!==null&&t!==void 0?t:1/0),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsLiveProvider",category:r.ErrorCategory.WTF,message:"HlsLiveProvider internal logic error",thrown:l})},a=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.ended$,e.endedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(je(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(z.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===z.READY&&this.videoState.setState(z.READY),this.videoState.getState()===z.PLAYING&&this.playIfAllowed()},i)),this.subscription.add(this.maxSeekBackTime$.pipe(r.filterChanged(),r.map(l=>-l/1e3)).subscribe(this.params.output.duration$,i)),this.subscription.add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const p=this.manifests$.getValue().find(f=>f.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(le(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===B.Requested&&this.seek(l.position)},i)),this.subscription.add(a.loadedData$.subscribe(()=>{var l,d,u;const c=(u=(d=(l=this.video)===null||l===void 0?void 0:l.getStartDate)===null||d===void 0?void 0:d.call(l))===null||u===void 0?void 0:u.getTime();this.manifestStartTime$.next(c||void 0)},i)),this.subscription.add(r.combine({startTime:this.manifestStartTime$.pipe(r.filter(r.isNonNullable)),currentTime:a.timeUpdate$}).subscribe(({startTime:l,currentTime:d})=>this.params.output.liveTime$.next(l+d*1e3),i)),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=this.params.format===exports.VideoFormat.HLS_LIVE_CMAF?se.DASH_CMAF_OFFSET_P:se.OFFSET_P,i=Re(e.url,this.liveOffset.getTotalOffset(),t);this.video.setAttribute("src",i),this.video.load(),Gr(i).then(a=>{var n;if(!r.isNullable(a))this.maxSeekBackTime$.next(a);else{const o=(n=this.params.source.maxSeekBackTime)!==null&&n!==void 0?n:this.maxSeekBackTime$.getValue();if(r.isNullable(o)||!isFinite(o))try{Yt(i).then(l=>l.text()).then(l=>{var d;const u=(d=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(l))===null||d===void 0?void 0:d[1];if(u){const c=new URL(u,i).toString();Gr(c).then(h=>{r.isNullable(h)||this.maxSeekBackTime$.next(h)})}})}catch(l){}}})}playIfAllowed(){Ze(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),this.liveOffset.pause(),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}))}seek(e){this.params.output.willSeekEvent$.next();const t=-e,i=t<this.maxSeekBackTime$.getValue()?t:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}var Q;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(Q||(Q={}));class Om{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(Q.STOPPED),this.textTracksManager=new Ce,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{if(!this.manifests$.getValue().length)return;const a=this.videoState.getState(),n=this.params.desiredState.playbackState.getState(),o=this.params.desiredState.playbackState.getTransition(),l=this.params.desiredState.videoTrack.getTransition(),d=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(n===exports.PlaybackState.STOPPED){a!==Q.STOPPED&&(this.videoState.startTransitionTo(Q.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(Q.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===Q.STOPPED){this.videoState.startTransitionTo(Q.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(Q.CHANGING_MANIFEST),this.videoState.startTransitionTo(h);const{currentTime:p}=this.video;this.prepare(),c.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:p*1e3,forcePrecise:!0});return}switch((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===B.Requested&&this.seek(c.position),a){case Q.READY:n===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(Q.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed());return;case Q.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Q.PAUSED),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Q.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Q.PLAYING),this.playIfAllowed()):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case Q.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:r.VideoQuality.INVARIANT,url:this.params.source.url};this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(le(this.params.source.url)),uo(this.params.source.url).then(({qualityManifests:i,textTracks:a})=>{this.manifests$.next([t,...i]),this.params.tuning.useNativeHLSTextTracks||this.params.desiredState.internalTextTracks.startTransitionTo(a)},i=>this.params.output.error$.next({id:"ExtractHlsQualities",category:r.ErrorCategory.NETWORK,message:"Error fetching manifest and extracting qualities",thrown:i})),this.subscribe()}selectManifest(){var e,t;const{autoVideoTrackSwitching:i,videoTrack:a}=this.params.desiredState,n=i.getState(),o=a.getTransition(),l=(t=(e=o==null?void 0:o.to)!==null&&e!==void 0?e:a.getState())!==null&&t!==void 0?t:"master",d=this.manifests$.getValue();if(!d.length)return;const u=n?"master":l;return n&&!o&&a.startTransitionTo("master"),d.find(c=>c.id===u)}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"HlsProvider",category:r.ErrorCategory.WTF,message:"HlsProvider internal logic error",thrown:l})},a=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));if(n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(Q.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Q.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===Q.READY&&this.videoState.setState(Q.READY),this.videoState.getState()===Q.PLAYING&&this.playIfAllowed()},i).add(a.loadedMetadata$.subscribe(()=>{const l=this.params.desiredState.seekState.getState(),d=this.videoState.getTransition(),u=this.params.desiredState.videoTrack.getTransition(),c=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(u&&r.isNonNullable(u.to)){const h=u.to;this.params.desiredState.videoTrack.setState(h);const p=this.manifests$.getValue().find(f=>f.id===h);p&&(this.params.output.currentVideoTrack$.next(p),this.params.output.hostname$.next(le(p.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===Q.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===B.Requested&&this.seek(l.position)},i))),this.subscription.add(this.manifests$.pipe(r.map(l=>l.map(({id:d,quality:u,size:c,bandwidth:h,fps:p})=>({id:d,quality:u,size:c,fps:p,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i)),!this.params.tuning.useNativeHLSTextTracks){const{textTracks:l}=this.video;this.subscription.add(r.merge(r.fromEvent(l,"addtrack"),r.fromEvent(l,"removetrack"),r.fromEvent(l,"change"),r.observableFrom(["init"])).subscribe(()=>{for(let d=0;d<l.length;d++)l[d].mode="hidden"},i))}const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,this.manifests$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.params.output.element$.next(void 0),Ge(this.video)}prepare(){const e=this.selectManifest();r.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){Ze(this.video).then(e=>{e||(this.videoState.setState(Q.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var X;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(X||(X={}));class Bm{constructor(e){this.subscription=new r.Subscription,this.videoState=new K(X.STOPPED),this.trackUrls={},this.textTracksManager=new Ce,this.syncPlayback=()=>{var t,i,a;const n=this.videoState.getState(),o=this.params.desiredState.playbackState.getState(),l=this.params.desiredState.playbackState.getTransition();if(o===exports.PlaybackState.STOPPED){n!==X.STOPPED&&(this.videoState.startTransitionTo(X.STOPPED),this.video.removeAttribute("src"),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(X.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.autoVideoTrackLimits.getTransition(),c=this.params.desiredState.videoTrack.getTransition(),h=this.params.desiredState.seekState.getState();if(u&&n!==X.READY&&!c){this.handleQualityLimitTransition(u.to.max);return}if(n===X.STOPPED){this.videoState.startTransitionTo(X.READY),this.prepare();return}if(c){const{currentTime:p}=this.video;this.prepare(),h.state===B.None&&this.params.desiredState.seekState.setState({state:B.Requested,position:p*1e3,forcePrecise:!0}),c.to&&((t=this.params.desiredState.autoVideoTrackLimits.getState())===null||t===void 0?void 0:t.max)!==((a=(i=this.trackUrls[c.to])===null||i===void 0?void 0:i.track)===null||a===void 0?void 0:a.quality)&&this.params.output.autoVideoTrackLimits$.next({max:void 0});return}switch((l==null?void 0:l.to)!==exports.PlaybackState.PAUSED&&h.state===B.Requested&&this.seek(h.position),n){case X.READY:o===exports.PlaybackState.READY?P(this.params.desiredState.playbackState,exports.PlaybackState.READY):o===exports.PlaybackState.PAUSED?(this.videoState.setState(X.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):o===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed());return;case X.PLAYING:o===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(X.PAUSED),this.video.pause()):(l==null?void 0:l.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case X.PAUSED:o===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(X.PLAYING),this.playIfAllowed()):(l==null?void 0:l.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(n)}},this.params=e,this.video=He(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).reverse().forEach(([t,i],a)=>{const n=a.toString(10);this.trackUrls[n]={track:{quality:t,id:n},url:i}}),this.params.output.isLive$.next(!1),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map(({track:t})=>t)),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.desiredState.autoVideoTrackSwitching.setState(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=l=>{e.error$.next({id:"MpegProvider",category:r.ErrorCategory.WTF,message:"MpegProvider internal logic error",thrown:l})},a=Ye(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.loadedMetadata$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),n(a.inPiP$,e.inPiP$),n(a.inFullscreen$,e.inFullscreen$),this.subscription.add(dt(this.video,t.isLooped,i)),this.subscription.add(je(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Xe(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(X.PLAYING),P(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(X.PAUSED),P(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===X.READY&&this.videoState.setState(X.READY);const d=this.params.desiredState.videoTrack.getTransition();d&&r.isNonNullable(d.to)&&(this.params.desiredState.videoTrack.setState(d.to),this.params.output.currentVideoTrack$.next(this.trackUrls[d.to].track)),this.videoState.getState()===X.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,t.autoVideoTrackLimits.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.params.output.element$.next(void 0),Ge(this.video)}prepare(){const e=this.params.desiredState.videoTrack.getState();r.assertNonNullable(e,"MpegProvider: track is not selected");let{url:t}=this.trackUrls[e];r.assertNonNullable(t,`MpegProvider: No url for ${e}`),this.params.tuning.requestQuick&&(t=Pt(t)),this.video.setAttribute("src",t),this.video.load(),this.params.output.hostname$.next(le(t))}playIfAllowed(){Ze(this.video).then(e=>{e||(this.videoState.setState(X.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}))}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}handleQualityLimitTransition(e){var t,i,a;let n;if(e&&((t=this.params.output.currentVideoTrack$.getValue())===null||t===void 0?void 0:t.quality)!==e){const o=(i=Object.values(this.trackUrls).find(u=>r.isLowerOrEqual(u.track.quality,e)))===null||i===void 0?void 0:i.track,l=this.params.desiredState.videoTrack.getState(),d=(a=this.trackUrls[l!=null?l:"0"])===null||a===void 0?void 0:a.track;o&&d&&r.isHigherOrEqual(d.quality,o.quality)&&(n=o)}else if(!e){const o=Object.values(this.trackUrls).map(l=>l.track);n=Rt(o,{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,forwardBufferHealth:0,abrLogger:this.params.dependencies.abrLogger})}n&&(this.params.output.currentVideoTrack$.next(n),this.params.desiredState.videoTrack.startTransitionTo(n.id)),this.params.output.autoVideoTrackLimits$.next({max:e})}}const Yr=["stun:videostun.mycdn.me:80"],Mm=1e3,Vm=3,Ds=()=>null;class Fm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ds,this.externalStopCallback=Ds,this.externalErrorCallback=Ds,this.options=this.normalizeOptions(t);const i=e.split("/");this.serverUrl=i.slice(0,i.length-1).join("/"),this.streamKey=i[i.length-1]}onStart(e){try{this.externalStartCallback=e}catch(t){this.handleSystemError(t)}}onStop(e){try{this.externalStopCallback=e}catch(t){this.handleSystemError(t)}}onError(e){try{this.externalErrorCallback=e}catch(t){this.handleSystemError(t)}}connect(){this.connectWS()}disconnect(){try{this.externalStopCallback(),this.closeConnections()}catch(e){this.handleSystemError(e)}}connectWS(){this.ws||(this.ws=new WebSocket(this.serverUrl),this.ws.onopen=this.onSocketOpen.bind(this),this.ws.onmessage=this.onSocketMessage.bind(this),this.ws.onclose=this.onSocketClose.bind(this),this.ws.onerror=this.onSocketError.bind(this))}onSocketOpen(){this.handleLogin()}onSocketClose(e){try{if(!this.ws)return;this.ws=null,e.code>1e3?(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():this.scheduleRetry()):this.externalStopCallback()}catch(t){this.handleRTCError(t)}}onSocketError(e){try{this.externalErrorCallback(new Error(e.toString()))}catch(t){this.handleRTCError(t)}}onSocketMessage(e){try{const t=this.parseMessage(e.data);switch(t.type){case"JOIN":case"CALL_JOIN":this.handleJoinMessage(t);break;case"UPDATE":this.handleUpdateMessage(t);break;case"STATUS":this.handleStatusMessage(t);break}}catch(t){this.handleRTCError(t)}}handleJoinMessage(e){switch(e.inviteType){case"ANSWER":this.handleAnswer(e.sdp);break;case"CANDIDATE":this.handleCandidate(e.candidate);break}}handleStatusMessage(e){switch(e.status){case"UNPUBLISHED":this.handleUnpublished();break}}async handleUpdateMessage(e){try{const t=await this.createOffer();this.peerConnection&&await this.peerConnection.setLocalDescription(t),this.handleAnswer(e.sdp)}catch(t){this.handleRTCError(t)}}async handleLogin(){try{const e={iceServers:[{urls:Yr}]};this.peerConnection=new RTCPeerConnection(e),this.peerConnection.ontrack=this.onPeerConnectionStream.bind(this),this.peerConnection.onicecandidate=this.onPeerConnectionIceCandidate.bind(this),this.peerConnection.oniceconnectionstatechange=this.onPeerConnectionIceConnectionStateChange.bind(this);const t=await this.createOffer();await this.peerConnection.setLocalDescription(t),this.send({type:this.signalingType,inviteType:"OFFER",streamKey:this.streamKey,sdp:t.sdp,callSupport:!1})}catch(e){this.handleRTCError(e)}}async handleAnswer(e){try{this.peerConnection&&await this.peerConnection.setRemoteDescription(new RTCSessionDescription({type:"answer",sdp:e}))}catch(t){this.handleRTCError(t)}}async handleCandidate(e){if(e)try{this.peerConnection&&await this.peerConnection.addIceCandidate(e)}catch(t){this.handleRTCError(t)}}handleUnpublished(){try{this.closeConnections(),this.externalStopCallback()}catch(e){this.handleRTCError(e)}}handleSystemError(e){this.options.errorChanel&&this.options.errorChanel.next({id:"webrtc-provider-error",category:r.ErrorCategory.WTF,message:e.message})}async onPeerConnectionStream(e){const t=e.streams[0];this.stream&&this.stream.id===t.id||(this.stream=t,this.externalStartCallback(this.stream))}onPeerConnectionIceCandidate(e){e.candidate&&this.send({type:this.signalingType,inviteType:"CANDIDATE",candidate:e.candidate})}onPeerConnectionIceConnectionStateChange(){if(this.peerConnection){const e=this.peerConnection.iceConnectionState;["failed","closed"].indexOf(e)>-1&&(this.retryCount++,this.retryCount>this.options.maxRetryNumber?this.handleNetworkError():(this.closeConnections(),this.scheduleRetry()))}}async createOffer(){const e={offerToReceiveAudio:!0,offerToReceiveVideo:!0,voiceActivityDetection:!1};if(!this.peerConnection)throw new Error("Can not create offer - no peer connection instance ");const t=await this.peerConnection.createOffer(e),i=t.sdp||"";if(!/^a=rtpmap:\d+ H264\/\d+$/m.test(i))throw new Error("No h264 codec support error");return t}handleRTCError(e){try{this.externalErrorCallback(e||new Error("RTC connection error"))}catch(t){this.handleSystemError(t)}}handleNetworkError(){try{this.externalErrorCallback(new Error("Network error"))}catch(e){this.handleSystemError(e)}}send(e){this.ws&&this.ws.send(JSON.stringify(e))}parseMessage(e){try{return JSON.parse(e)}catch(t){throw new Error("Can not parse socket message")}}closeConnections(){const e=this.ws;e&&(this.ws=null,e.close(1e3)),this.removePeerConnection()}removePeerConnection(){let e=this.peerConnection;e&&(this.peerConnection=null,e.close(),e.ontrack=null,e.onicecandidate=null,e.oniceconnectionstatechange=null,e=null)}scheduleRetry(){this.retryTimeout=setTimeout(this.connectWS.bind(this),Mm)}normalizeOptions(e={}){const t={stunServerList:Yr,maxRetryNumber:Vm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var W;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(W||(W={}));class Um{constructor(e){this.videoState=new K(W.STOPPED),this.maxSeekBackTime$=new r.ValueSubject(0),this.syncPlayback=()=>{const t=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED){t!==W.STOPPED&&(this.videoState.startTransitionTo(W.STOPPED),this.video.pause(),this.video.srcObject=null,this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(W.STOPPED),P(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===W.STOPPED){this.videoState.startTransitionTo(W.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case W.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(W.PAUSED),P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed());return;case W.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(W.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case W.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(W.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&P(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("WebRTCLiveProvider"),this.video=He(e.container),this.liveStreamClient=new Fm(this.params.source.url,{maxRetryNumber:this.params.tuning.webrtc.connectionRetryMaxNumber,errorChanel:this.params.output.error$}),this.liveStreamClient.onStart(this.onLiveStreamStart.bind(this)),this.liveStreamClient.onStop(this.onLiveStreamStop.bind(this)),this.liveStreamClient.onError(this.onLiveStreamError.bind(this)),this.subscribe()}destroy(){this.subscription.unsubscribe(),this.liveStreamClient.disconnect(),this.params.output.element$.next(void 0),Ge(this.video)}subscribe(){const{output:e,desiredState:t}=this.params,i=o=>{e.error$.next({id:"WebRTCLiveProvider",category:r.ErrorCategory.WTF,message:"WebRTCLiveProvider internal logic error",thrown:o})};r.merge(this.videoState.stateChangeStarted$.pipe(r.map(o=>({transition:o,type:"start"}))),this.videoState.stateChangeEnded$.pipe(r.map(o=>({transition:o,type:"end"})))).subscribe(({transition:o,type:l})=>{this.log({message:`[videoState change] ${l}: ${JSON.stringify(o)}`})});const a=Ye(this.video),n=(o,l)=>this.subscription.add(o.subscribe(l,i));n(a.timeUpdate$,e.liveTime$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),this.subscription.add(a.durationChange$.subscribe(o=>{e.duration$.next(o===1/0?0:o)})).add(a.canplay$.subscribe(()=>{var o;((o=this.videoState.getTransition())===null||o===void 0?void 0:o.to)===W.READY&&this.videoState.setState(W.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(W.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(W.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(je(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case W.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case W.READY:break;case W.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case W.PLAYING:t.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return r.assertNever(o.to)}},i)).add(r.merge(t.playbackState.stateChangeStarted$,this.videoState.stateChangeEnded$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback.bind(this),i)),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(t.autoVideoTrackSwitching.stateChangeStarted$.subscribe(()=>t.autoVideoTrackSwitching.setState(!1),i))}onLiveStreamStart(e){this.params.output.element$.next(this.video),this.params.output.duration$.next(0),this.params.output.position$.next(0),this.params.output.isLive$.next(!0),this.params.output.canChangePlaybackSpeed$.next(!1),this.params.output.hostname$.next(le(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!1),this.params.output.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.currentVideoTrack$.next({id:"webrtc",quality:r.VideoQuality.INVARIANT}),this.video.srcObject=e,P(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(W.STOPPED),this.syncPlayback(),this.params.output.position$.next(0),this.params.output.duration$.next(0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.params.output.endedEvent$.next()}onLiveStreamError(e){this.onLiveStreamStop(),this.params.output.error$.next({id:"WebRTC stream runtime error",category:r.ErrorCategory.EXTERNAL_API,message:e.message,thrown:e})}playIfAllowed(){Ze(this.video).then(e=>{e||(this.videoState.setState(W.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}))}prepare(){this.liveStreamClient.connect()}}class qr{constructor(e){this.iterator=e[Symbol.iterator](),this.next()}next(){this.current=this.iterator.next()}getValue(){if(this.current.done)throw new Error("Iterable is completed");return this.current.value}isCompleted(){return!!this.current.done}}var Rs,Cs,Is,xs,Ns,Ls,vi,Os,Si,Bs,bi,Ms,gi,Vs,yi,Fs,Ti,Us;const co=r.getCurrentBrowser().device===r.CurrentClientDevice.Android,Je=document.createElement("video"),jm='video/mp4; codecs="avc1.42000a,mp4a.40.2"',Hm='video/mp4; codecs="hev1.1.6.L93.B0"',ho='video/webm; codecs="vp09.00.10.08"',po='video/webm; codecs="av01.0.00M.08"',Gm='audio/mp4; codecs="mp4a.40.2"',Ym='audio/webm; codecs="opus"',be={mse:!!(window.MediaSource&&window.MediaStreamTrack&&(!((Cs=(Rs=window.SourceBuffer)===null||Rs===void 0?void 0:Rs.prototype)===null||Cs===void 0)&&Cs.appendBuffer)),hls:!!(!((Is=Je.canPlayType)===null||Is===void 0)&&Is.call(Je,"application/x-mpegurl")||!((xs=Je.canPlayType)===null||xs===void 0)&&xs.call(Je,"vnd.apple.mpegURL")),webrtc:!!window.RTCPeerConnection,ws:!!window.WebSocket},ce={mp4:!!(!((Ns=Je.canPlayType)===null||Ns===void 0)&&Ns.call(Je,"video/mp4")),webm:!!(!((Ls=Je.canPlayType)===null||Ls===void 0)&&Ls.call(Je,"video/webm")),cmaf:!0},De={h264:!!(!((Os=(vi=window.MediaSource)===null||vi===void 0?void 0:vi.isTypeSupported)===null||Os===void 0)&&Os.call(vi,jm)),h265:!!(!((Bs=(Si=window.MediaSource)===null||Si===void 0?void 0:Si.isTypeSupported)===null||Bs===void 0)&&Bs.call(Si,Hm)),vp9:!!(!((Ms=(bi=window.MediaSource)===null||bi===void 0?void 0:bi.isTypeSupported)===null||Ms===void 0)&&Ms.call(bi,ho)),av1:!!(!((Vs=(gi=window.MediaSource)===null||gi===void 0?void 0:gi.isTypeSupported)===null||Vs===void 0)&&Vs.call(gi,po)),aac:!!(!((Fs=(yi=window.MediaSource)===null||yi===void 0?void 0:yi.isTypeSupported)===null||Fs===void 0)&&Fs.call(yi,Gm)),opus:!!(!((Us=(Ti=window.MediaSource)===null||Ti===void 0?void 0:Ti.isTypeSupported)===null||Us===void 0)&&Us.call(Ti,Ym))},yt=(De.h264||De.h265)&&De.aac;var Qe;(function(s){s.VP9="vp9",s.AV1="av1",s.NONE="none",s.SMOOTH="smooth",s.POWER_EFFICIENT="power_efficient"})(Qe||(Qe={}));var Oe;(function(s){s.DASH="dash",s.HLS="hls",s.MPEG="mpeg"})(Oe||(Oe={}));let at;const qm=async()=>{if(!window.navigator.mediaCapabilities)return;const s={type:"media-source",video:{contentType:"video/webm",width:1280,height:720,bitrate:1e6,framerate:30}},[e,t]=await Promise.all([window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:po}}),window.navigator.mediaCapabilities.decodingInfo({...s,video:{...s.video,contentType:ho}})]);at={[exports.VideoFormat.DASH_WEBM_AV1]:e,[exports.VideoFormat.DASH_WEBM]:t}};try{qm()}catch(s){console.error(s)}const qt=be.hls&&ce.mp4,zm=()=>Object.keys(De).filter(s=>De[s]),Wm=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.DASH_SEP:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.DASH_WEBM:return be.mse&&ce.webm&&De.vp9&&De.opus;case exports.VideoFormat.DASH_WEBM_AV1:return be.mse&&ce.webm&&De.av1&&De.opus;case exports.VideoFormat.DASH_LIVE:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.DASH_LIVE_CMAF:return be.mse&&ce.mp4&&yt&&ce.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return be.mse&&ce.mp4&&yt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:return qt||e&&be.mse&&ce.mp4&&yt;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:return qt;case exports.VideoFormat.MPEG:return ce.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return be.webrtc&&be.ws&&De.h264&&(ce.mp4||ce.webm);default:return r.assertNever(t)}}),Ut=s=>{const e=exports.VideoFormat.DASH_WEBM,t=exports.VideoFormat.DASH_WEBM_AV1;switch(s){case Qe.VP9:return[e,t];case Qe.AV1:return[t,e];case Qe.NONE:return[];case Qe.SMOOTH:return at?at[t].smooth?[t,e]:at[e].smooth?[e,t]:[t,e]:[e,t];case Qe.POWER_EFFICIENT:return at?at[t].powerEfficient?[t,e]:at[e].powerEfficient?[e,t]:[t,e]:[e,t];default:r.assertNever(s)}return[e,t]},Qm=({webmCodec:s,androidPreferredFormat:e})=>{if(co)switch(e){case Oe.MPEG:return[exports.VideoFormat.MPEG,...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND];case Oe.HLS:return[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.MPEG];case Oe.DASH:return[...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]}return qt?[...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[...Ut(s),exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG]},Km=({androidPreferredFormat:s,preferCMAF:e,preferWebRTC:t})=>{const i=e?[exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.DASH_LIVE]:[exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF],a=e?[exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],n=[...i,...a],o=[...a,...i];let l;if(co)switch(s){case Oe.DASH:{l=n;break}case Oe.HLS:case Oe.MPEG:{l=o;break}}else qt?l=o:l=n;return t?[exports.VideoFormat.WEB_RTC_LIVE,...l]:[...l,exports.VideoFormat.WEB_RTC_LIVE]},zr=s=>s?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_WEBM_AV1,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Jm=s=>new r.Observable(e=>{const t=new r.Subscription,i=s.desiredPlaybackState$.stateChangeStarted$.pipe(r.map(({from:u,to:c})=>`${u}-${c}`)),a=s.desiredPlaybackState$.stateChangeEnded$,n=s.providerChanged$.pipe(r.map(({type:u})=>u!==void 0)),o=new r.Subject;let l=0,d="unknown";return t.add(i.subscribe(u=>{l&&window.clearTimeout(l),d=u,l=window.setTimeout(()=>o.next(u),s.maxTransitionInterval)})),t.add(a.subscribe(()=>{window.clearTimeout(l),d="unknown",l=0})),t.add(n.subscribe(u=>{l&&(window.clearTimeout(l),l=0,u&&(l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval)))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Xm={cacheDuration:12e4},Zm={chunkDuration:5e3,maxParallelRequests:5};class ev{constructor(e){this.current$=new r.ValueSubject({type:void 0}),this.providerError$=new r.Subject,this.noAvailableProvidersError$=new r.Subject,this.providerOutput={position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),volume$:new r.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new r.ValueSubject(void 0),availableVideoTracks$:new r.ValueSubject([]),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),autoVideoTrackLimitingAvailable$:new r.ValueSubject(!1),autoVideoTrackLimits$:new r.ValueSubject(void 0),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$:new r.Subject,warning$:new r.Subject,willSeekEvent$:new r.Subject,seekedEvent$:new r.Subject,loopedEvent$:new r.Subject,endedEvent$:new r.Subject,firstBytesEvent$:new r.Subject,firstFrameEvent$:new r.Subject,canplay$:new r.Subject,isLive$:new r.ValueSubject(void 0),isLowLatency$:new r.ValueSubject(!1),canChangePlaybackSpeed$:new r.ValueSubject(!0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),inPiP$:new r.ValueSubject(!1),inFullscreen$:new r.ValueSubject(!1),element$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=Wm([...Km(this.params.tuning),...Qm(this.params.tuning)],this.params.tuning.useHlsJs).filter(l=>r.isNonNullable(e.sources[l])),{forceFormat:i,formatsToAvoid:a}=this.params.tuning;let n=[];i?n=[i]:a.length?n=[...t.filter(l=>!a.includes(l)),...t.filter(l=>a.includes(l))]:n=t,this.log({message:`Selected formats: ${n.join(" > ")}`}),this.screenFormatsIterator=new qr(n);const o=[...zr(!0),...zr(!1)];this.chromecastFormatsIterator=new qr(o.filter(l=>r.isNonNullable(e.sources[l]))),this.providerOutput.availableSources$.next(e.sources)}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe(()=>{this.reinitProvider()}))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),t=this.chooseFormat(e);if(r.isNullable(t)){this.handleNoFormatsError(e);return}let i;try{i=this.createProvider(e,t)}catch(a){this.providerError$.next({id:"ProviderNotConstructed",category:r.ErrorCategory.WTF,message:"Failed to create provider",thrown:a})}i?this.current$.next({type:t,provider:i,destination:e}):this.current$.next({type:void 0})}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(e){this.destroyProvider(),this.failoverIndex=void 0,this.skipFormat(e),this.initProvider()}destroyProvider(){const e=this.current$.getValue().provider;if(!e)return;this.log({message:"destroyProvider"});const t=this.providerOutput.position$.getValue()*1e3,i=this.params.desiredState.seekState.getState(),a=i.state!==B.None;if(this.params.desiredState.seekState.setState({state:B.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.scene3D){const o=e.scene3D.getCameraRotation();this.params.desiredState.cameraOrientation.setState({x:o.x,y:o.y})}e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case re.SCREEN:return this.createScreenProvider(t);case re.CHROMECAST:return this.createChromecastProvider(t);default:return r.assertNever(e)}}createScreenProvider(e){const{sources:t,container:i,desiredState:a}=this.params,n=this.providerOutput,o={container:i,source:null,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(e){case exports.VideoFormat.DASH:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Qp({...o,source:l,config:Xm})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_AV1:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new _r({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new Cm({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJsCMAF?new _r({...o,source:l,format:e,config:{maxPausedTime:this.params.tuning.live.maxPausedTime}}):new Im({...o,source:l})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),qt||!this.params.tuning.useHlsJs?new Om({...o,source:l}):new xm({...o,source:l})}case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Lm({...o,source:l,config:{maxPausedTime:this.params.tuning.live.maxPausedTime},format:e})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Bm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Gp({...o,source:l,config:{...Zm,maxPausedTime:this.params.tuning.live.maxPausedTime}})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Um({container:i,source:l,desiredState:a,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE_WEBM:throw new Error("DASH_LIVE_WEBM is no longer supported");default:return r.assertNever(e)}}createChromecastProvider(e){const{sources:t,container:i,desiredState:a,meta:n}=this.params,o=this.providerOutput,l=this.params.dependencies.chromecastInitializer.connection$.getValue();return r.assertNonNullable(l),new ep({connection:l,meta:n,container:i,source:t,format:e,desiredState:a,output:o,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?re.CHROMECAST:re.SCREEN}chooseFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case re.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case re.SCREEN:return this.screenFormatsIterator.next();case re.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case re.SCREEN:this.noAvailableProvidersError$.next(this.params.tuning.forceFormat),this.current$.next({type:void 0});return;case re.CHROMECAST:this.params.dependencies.chromecastInitializer.disconnect();return;default:return r.assertNever(e)}}applyFailoverHost(e){if(this.failoverIndex===void 0)return e;const t=this.params.failoverHosts[this.failoverIndex];if(!t)return e;const i=a=>{const n=new URL(a);return n.host=t,n.toString()};if(e===void 0)return e;if("type"in e){if(e.type==="raw")return e;if(e.type==="url")return{...e,url:i(e.url)}}return kt(Object.entries(e).map(([a,n])=>[a,i(n)]))}initProviderErrorHandling(){const e=new r.Subscription;let t=!1,i=0;return e.add(r.merge(this.providerOutput.error$,Jm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:this.params.tuning.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$}).pipe(r.map(a=>({id:`ProviderHangup:${a}`,category:r.ErrorCategory.WTF,message:`A ${a} transition failed to complete within reasonable time`})))).subscribe(this.providerError$)),e.add(this.current$.subscribe(()=>{t=!1;const a=this.params.desiredState.playbackState.transitionEnded$.pipe(r.filter(({to:n})=>n===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>t=!0);e.add(a)})),e.add(this.providerError$.subscribe(a=>{const n=this.current$.getValue().destination;if(n===re.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(re.SCREEN),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const o=a.category===r.ErrorCategory.NETWORK,l=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),d=i<this.params.tuning.providerErrorLimit;l&&(o&&t||!d)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):d?(i++,this.reinitProvider()):this.switchToNextProvider(n!=null?n:re.SCREEN)}})),e}}const ta=(s,e,t)=>t*e+(1-t)*s,fo=(s,e)=>s.reduce((t,i)=>t+i,0)/e,tv=(s,e,t,i)=>{let a=0,n=t;const o=fo(s,e),l=e<i?e:i;for(let d=0;d<l;d++)s[n]>o?a++:a--,n=(s.length+n-1)%s.length;return Math.abs(a)===l};class mo{constructor(e){var t;this.prevReported=void 0,this.pastMeasures=[],this.takenMeasures=0,this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.smoothed=this.prevReported=e.initial,this.smoothed$=new r.ValueSubject(e.initial),this.debounced$=new r.ValueSubject(e.initial);const i=(t=e.label)!==null&&t!==void 0?t:"value"+Math.random().toString(16).substring(2,6);this.rawSeries$=new we(`raw_${i}`),this.smoothedSeries$=new we(`smoothed_${i}`),this.reportedSeries$=new we(`reported_${i}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let t=0,i=0;for(let l=0;l<this.pastMeasures.length;l++)this.pastMeasures[l]!==void 0&&(t+=(this.pastMeasures[l]-this.smoothed)**2,i++);this.takenMeasures=i,t/=i;const a=Math.sqrt(t),n=this.smoothed+this.params.deviationFactor*a,o=this.smoothed-this.params.deviationFactor*a;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.updateSmoothedValue(e),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),!(this.smoothed>n||this.smoothed<o)&&(r.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}class iv extends mo{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=ta(this.slow,e,this.params.emaAlphaSlow),this.fast=ta(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class sv extends mo{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=fo(this.pastMeasures,this.takenMeasures);this.emaSmoothed=ta(this.emaSmoothed,e,this.params.emaAlpha);const i=tv(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Wr{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new iv({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new sv({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const av=5e3,Qr="one_video_throughput",Kr="one_video_rtt",Be=window.navigator.connection,Jr=()=>{const s=Be==null?void 0:Be.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},Xr=()=>{const s=Be==null?void 0:Be.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Zr=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class Ht{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Ht.load(Qr)||(e.useBrowserEstimation?Jr():void 0)||av,n=(i=(t=Ht.load(Kr))!==null&&t!==void 0?t:e.useBrowserEstimation?Xr():void 0)!==null&&i!==void 0?i:0;if(this.throughput$=new r.ValueSubject(a),this.rtt$=new r.ValueSubject(n),this.rttAdjustedThroughput$=new r.ValueSubject(Zr(a,n,e.rttPenaltyRequestSize)),this.throughput=Wr.getSmoothedValue(a,-1,e),this.rtt=Wr.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Jr();d&&this.throughput.next(d);const u=Xr();r.isNonNullable(u)&&this.rtt.next(u)};Be&&"onchange"in Be&&this.subscription.add(r.fromEvent(Be,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{r.safeStorage.set(Qr,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{r.safeStorage.set(Kr,o.toFixed(0))})),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(r.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(r.map(({throughput:o,rtt:l})=>Zr(o,l,e.rttPenaltyRequestSize)),r.filter(o=>{const l=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(o-l)/l>=e.changeThreshold})).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(e){let t=0,i=r.now();const a=new r.Subscription;switch(this.subscription.add(a),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:a.add(r.fromEvent(e,"progress").pipe(r.once()).subscribe(n=>{t=n.loaded,i=r.now()}));break;case 1:case 0:a.add(r.fromEvent(e,"loadstart").subscribe(()=>{t=0,i=r.now()}));break}a.add(r.fromEvent(e,"loadend").subscribe(n=>{if(e.status===200){const o=n.loaded,l=r.now(),d=o-t,u=l-i;this.addRawSpeed(d,u,1)}this.concurrentDownloads.delete(e),a.unsubscribe()}))}trackStream(e){const t=e.getReader();if(!t){e.cancel("Could not get reader");return}let i=0;const a=r.now();let n=0,o=r.now();const l=u=>{this.concurrentDownloads.delete(e),t.releaseLock(),e.cancel(`Throughput Estimator error: ${u}`).catch(()=>{})},d=async({done:u,value:c})=>{u?(this.addRawSpeed(i,r.now()-a,1),this.concurrentDownloads.delete(e)):c&&(i+=c.byteLength,n+=c.byteLength,n>=this.tuningConfig.streamMinSampleSize&&r.now()-o>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(n,r.now()-o,this.concurrentDownloads.size),n=0,o=r.now()),await(t==null?void 0:t.read().then(d,l)))};this.concurrentDownloads.add(e),t==null||t.read().then(d,l)}addRawSpeed(e,t,i=1){if(Ht.sanityCheck(e,t)){const a=e*8/t;this.throughput.next(a*i)}}addRawThroughput(e){this.throughput.next(e)}addRawRtt(e){this.rtt.next(e)}static sanityCheck(e,t){const i=e*8/t;return!(!i||!isFinite(i)||i>1e6||i<30||e<10*1024||t<=20)}static load(e){var t;const i=r.safeStorage.get(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const en={configName:["core"],throughputEstimator:{type:"EmaAndMa",emaAlphaSlow:.2,emaAlphaFast:.7,emaAlpha:.45,basisTrendChangeCount:10,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1*1024*1024,streamMinSampleSize:10*1024,streamMinSampleTime:300,deviationDepth:20,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.4,considerPlaybackRate:!1,trackCooldown:3e3},droppedFramesChecker:{enabled:!1,percentLimit:.1,checkTime:1e3,countLimit:3,tickCountAfterQualityChange:5,qualityUpWaitingTime:5e3,minQualityBanLimit:r.VideoQuality.Q_480P},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:5*6e4,forwardBufferTargetPreload:5e3,minSafeBufferThreshold:.5,bufferPruningSafeZone:1e3,segmentRequestSize:1*1024*1024,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1,isLiveCatchUpMode:!1,lowLatencyActiveLiveDelay:3e3,activeLiveDelay:5e3,maxPausedTime:5e3},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,forceFormat:void 0,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!1,webmCodec:Qe.VP9,androidPreferredFormat:Oe.MPEG,preferCMAF:!1,preferWebRTC:!1,bigRequestMinInitSize:50*1024,bigRequestMinDataSize:1*1024*1024,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:3*60*1e3,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1,useDashJs:!1,useDashJsCMAF:!0,useHlsJs:!0,useDashAbortPartiallyFedSegment:!1,useNativeHLSTextTracks:!1,isAudioDisabled:!1,autoplayOnlyInActiveTab:!0,dynamicImportTimeout:5e3,maxPlaybackTransitionInterval:2e4,providerErrorLimit:3,webrtc:{connectionRetryMaxNumber:3},spherical:{enabled:!1,fov:{x:135,y:76},rotationSpeed:45,maxYawAngle:175,rotationSpeedCorrection:10,degreeToPixelCorrection:5,speedFadeTime:2e3,speedFadeThreshold:50}},rv=s=>{var e;return{...r.fillWithDefault(s,en),configName:[...(e=s.configName)!==null&&e!==void 0?e:[],...en.configName]}};var tn=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===B.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===B.None))),nv=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};class ov{constructor(e={configName:[]}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.abrLogger=this.logger.createComponentLog("ABR"),this.isPlaybackStarted=!1,this.desiredState={playbackState:new K(exports.PlaybackState.STOPPED),seekState:new K({state:B.None}),volume:new K({volume:1,muted:!1}),videoTrack:new K(void 0),autoVideoTrackSwitching:new K(!0),autoVideoTrackLimits:new K({}),isLooped:new K(!1),playbackRate:new K(1),externalTextTracks:new K([]),internalTextTracks:new K([]),currentTextTrack:new K(void 0),textTrackCuesSettings:new K({}),cameraOrientation:new K({x:0,y:0})},this.info={playbackState$:new r.ValueSubject(exports.PlaybackState.STOPPED),position$:new r.ValueSubject(0),duration$:new r.ValueSubject(1/0),muted$:new r.ValueSubject(!1),volume$:new r.ValueSubject(1),availableQualities$:new r.ValueSubject([]),availableQualitiesFps$:new r.ValueSubject({}),availableAudioTracks$:new r.ValueSubject([]),isAudioAvailable$:new r.ValueSubject(!0),currentQuality$:new r.ValueSubject(void 0),isAutoQualityEnabled$:new r.ValueSubject(!0),autoQualityLimitingAvailable$:new r.ValueSubject(!1),autoQualityLimits$:new r.ValueSubject({}),currentPlaybackRate$:new r.ValueSubject(1),currentBuffer$:new r.ValueSubject({start:0,end:0}),isBuffering$:new r.ValueSubject(!0),isStalled$:new r.ValueSubject(!1),isEnded$:new r.ValueSubject(!1),isLooped$:new r.ValueSubject(!1),isLive$:new r.ValueSubject(void 0),canChangePlaybackSpeed$:new r.ValueSubject(void 0),atLiveEdge$:new r.ValueSubject(void 0),atLiveDurationEdge$:new r.ValueSubject(void 0),liveTime$:new r.ValueSubject(void 0),liveBufferTime$:new r.ValueSubject(void 0),currentFormat$:new r.ValueSubject(void 0),availableTextTracks$:new r.ValueSubject([]),currentTextTrack$:new r.ValueSubject(void 0),throughputEstimation$:new r.ValueSubject(void 0),rttEstimation$:new r.ValueSubject(void 0),videoBitrate$:new r.ValueSubject(void 0),hostname$:new r.ValueSubject(void 0),httpConnectionType$:new r.ValueSubject(void 0),httpConnectionReused$:new r.ValueSubject(void 0),surface$:new r.ValueSubject(exports.Surface.NONE),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),availableSources$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.events={inited$:new r.Subject,ready$:new r.Subject,started$:new r.Subject,playing$:new r.Subject,paused$:new r.Subject,stopped$:new r.Subject,willStart$:new r.Subject,willResume$:new r.Subject,willPause$:new r.Subject,willStop$:new r.Subject,willDestruct$:new r.Subject,watchCoverageRecord$:new r.Subject,watchCoverageLive$:new r.Subject,managedError$:new r.Subject,fatalError$:new r.Subject,ended$:new r.Subject,looped$:new r.Subject,seeked$:new r.Subject,willSeek$:new r.Subject,firstBytes$:new r.Subject,firstFrame$:new r.Subject,canplay$:new r.Subject,log$:new r.Subject},this.experimental={element$:new r.ValueSubject(void 0),tuningConfigName$:new r.ValueSubject([]),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:kp},this.initLogs(),this.tuning=rv(e),this.experimental.tuningConfigName$.next(this.tuning.configName),this.chromecastInitializer=new Vo({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Ht(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,i,a)=>{const n=Reflect.get(t,i,a);return typeof n!="function"?n:(...o)=>{try{return n.apply(t,o)}catch(l){const d=o.map(h=>JSON.stringify(h,(p,f)=>{const m=typeof f;return["number","string","boolean"].includes(m)?f:f===null?null:`<${m}>`})),u=`Player.${String(i)}`,c=`Exception calling ${u} (${d.join(", ")})`;throw this.events.fatalError$.next({id:u,category:r.ErrorCategory.WTF,message:c,thrown:l}),l}}}})}initVideo(e){var t,i,a;return this.config=e,this.domContainer=nv(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new ev({sources:e.sources,meta:(i=e.meta)!==null&&i!==void 0?i:{},failoverHosts:(a=e.failoverHosts)!==null&&a!==void 0?a:[],container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger,abrLogger:this.abrLogger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.setMuted(this.tuning.isAudioDisabled),this.initDebugTelemetry(),this.initWakeLock(),this}destroy(){var e;this.events.willDestruct$.next(),this.stop(),(e=this.providerContainer)===null||e===void 0||e.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}prepare(){const e=this.desiredState.playbackState;return e.getState()===exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.READY),this}play(){const e=()=>{const t=this.desiredState.playbackState;t.getState()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING)};return document.hidden&&this.tuning.autoplayOnlyInActiveTab?r.fromEvent(document,"visibilitychange").pipe(r.once()).subscribe(e):e(),this}pause(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PAUSED&&e.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const e=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.STOPPED&&e.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(e,t=!0){const i=this.info.duration$.getValue(),a=this.info.isLive$.getValue();return e>=i&&!a&&(e=i-.1),this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:B.Requested,position:e*1e3,forcePrecise:t}),this}seekPercent(e){const t=this.info.duration$.getValue();return isFinite(t)&&this.seekTime(Math.abs(t)*e,!1),this}setVolume(e){const t=this.tuning.isAudioDisabled||this.desiredState.volume.getState().muted;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setVolume(e):this.desiredState.volume.startTransitionTo({volume:e,muted:t}),this}setMuted(e){const t=this.tuning.isAudioDisabled||e;return this.chromecastInitializer.castState$.getValue()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){r.assertNonNullable(this.providerContainer);const t=this.providerContainer.providerOutput.availableVideoTracks$.getValue();t.length||(this.explicitInitialQuality=e);const i=t.find(a=>a.quality===e);return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(e){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(e),this}setAutoQualityLimits(e){return this.desiredState.autoVideoTrackLimits.startTransitionTo(e),this}setPlaybackRate(e){var t;r.assertNonNullable(this.providerContainer);const i=(t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.element$.getValue();return i&&(this.desiredState.playbackRate.setState(e),i.playbackRate=e),this}setExternalTextTracks(e){return this.desiredState.externalTextTracks.startTransitionTo(e.map(t=>({type:"external",...t}))),this}selectTextTrack(e){var t,i,a;return e!==void 0&&this.desiredState.currentTextTrack.getState()===void 0&&this.desiredState.currentTextTrack.getPrevState()===void 0&&((t=this.providerContainer)===null||t===void 0?void 0:t.providerOutput.availableTextTracks$.getValue().length)===0?(i=this.providerContainer)===null||i===void 0||i.providerOutput.availableTextTracks$.pipe(r.filter(n=>n.length>0),r.once()).subscribe(n=>{n.find(o=>o.id===e)&&this.desiredState.currentTextTrack.startTransitionTo(e)}):(e===void 0||!((a=this.providerContainer)===null||a===void 0)&&a.providerOutput.availableTextTracks$.getValue().find(n=>n.id===e))&&this.desiredState.currentTextTrack.startTransitionTo(e),this}setTextTrackCueSettings(e){return this.desiredState.textTrackCuesSettings.startTransitionTo(e),this}setLooped(e){return this.desiredState.isLooped.startTransitionTo(e),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}startCameraManualRotation(e,t){const i=this.getScene3D();return i&&i.startCameraManualRotation(e,t),this}stopCameraManualRotation(e=!1){const t=this.getScene3D();return t&&t.stopCameraManualRotation(e),this}moveCameraFocusPX(e,t){const i=this.getScene3D();if(i){const a=i.getCameraRotation(),n=i.pixelToDegree({x:e,y:t});this.desiredState.cameraOrientation.setState({x:a.x+n.x,y:a.y+n.y})}return this}holdCamera(){const e=this.getScene3D();return e&&e.holdCamera(),this}releaseCamera(){const e=this.getScene3D();return e&&e.releaseCamera(),this}getExactTime(){r.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r.isNullable(e))return this.info.position$.getValue();const t=this.desiredState.seekState.getState(),i=t.state===B.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}getScene3D(){var e,t;const i=(e=this.providerContainer)===null||e===void 0?void 0:e.current$.getValue();if(!((t=i==null?void 0:i.provider)===null||t===void 0)&&t.scene3D)return i.provider.scene3D}setIntrinsicVideoSize(...e){const t={width:e.reduce((i,{width:a})=>i||a||0,0),height:e.reduce((i,{height:a})=>i||a||0,0)};t.width&&t.height&&this.info.intrinsicVideoSize$.next({width:t.width,height:t.height})}initDesiredStateSubscriptions(){this.subscription.add(r.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(r.map(e=>e.to)).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isLooped$)).add(this.desiredState.playbackRate.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.currentPlaybackRate$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(r.map(e=>e.to)).subscribe(this.info.autoQualityLimits$)),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(r.filter(({from:e})=>e===exports.PlaybackState.STOPPED),r.once()).subscribe(()=>{this.initedAt=r.now(),this.events.inited$.next()})).add(this.desiredState.playbackState.stateChangeEnded$.subscribe(e=>{switch(e.to){case exports.PlaybackState.READY:this.events.ready$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted||this.events.started$.next(),this.isPlaybackStarted=!0,this.events.playing$.next();break;case exports.PlaybackState.PAUSED:this.events.paused$.next();break;case exports.PlaybackState.STOPPED:this.events.stopped$.next()}})).add(this.desiredState.playbackState.stateChangeStarted$.subscribe(e=>{switch(e.to){case exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted?this.events.willResume$.next():this.events.willStart$.next();break;case exports.PlaybackState.STOPPED:this.events.willStop$.next();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const o=this.desiredState.seekState.getState();o.state===B.Requested?this.desiredState.seekState.setState({...o,state:B.Applying}):this.events.managedError$.next({id:`WillSeekIn${o.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===B.Applying&&(this.desiredState.seekState.setState({state:B.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(o=>o.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(o=>o.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(o=>o.map(({quality:l})=>l).sort((l,d)=>r.isInvariantQuality(l)?1:r.isInvariantQuality(d)?-1:r.isHigher(d,l)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(o=>{const l={};for(const d of o)d.fps&&(l[d.quality]=d.fps);this.info.availableQualitiesFps$.next(l)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{this.info.currentQuality$.next(o==null?void 0:o.quality),this.info.videoBitrate$.next(o==null?void 0:o.bitrate)})).add(e.providerOutput.hostname$.pipe(r.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(r.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.autoVideoTrackLimits$.subscribe(o=>{this.desiredState.autoVideoTrackLimits.setState(o!=null?o:{})})).add(e.providerOutput.currentBuffer$.pipe(r.map(o=>o?{start:o.from,end:o.to}:{start:0,end:0})).subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.canChangePlaybackSpeed$.subscribe(this.info.canChangePlaybackSpeed$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.liveBufferTime$.subscribe(this.info.liveBufferTime$)).add(r.combine({isLive:e.providerOutput.isLive$,isLowLatency:e.providerOutput.isLowLatency$,position:tn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$})}).pipe(r.map(({isLive:o,position:l,isLowLatency:d})=>{const u=d?this.tuning.live.lowLatencyActiveLiveDelay:this.tuning.live.activeLiveDelay;return o&&Math.abs(l)<u/1e3}),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveEdge$)).add(r.combine({isLive:e.providerOutput.isLive$,position:e.providerOutput.position$,duration:e.providerOutput.duration$}).pipe(r.map(({isLive:o,position:l,duration:d})=>o&&Math.abs(d)-Math.abs(l)<this.tuning.live.activeLiveDelay),r.filterChanged(),r.tap(o=>o&&this.setPlaybackRate(1))).subscribe(this.info.atLiveDurationEdge$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(o=>o.volume),r.filterChanged()).subscribe(this.info.volume$)).add(tn({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(r.merge(e.providerOutput.endedEvent$.pipe(r.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(r.mapTo(!1))).pipe(r.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(r.map(o=>({id:o?`No${o}`:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:o?`${o} was forced but failed or not available`:"No suitable providers or all providers failed"}))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.pipe(r.once(),r.map(o=>o!=null?o:r.now()-this.initedAt)).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(r.once(),r.map(()=>r.now()-this.initedAt)).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$)).add(e.providerOutput.availableSources$.subscribe(this.info.availableSources$));const t=new r.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe(()=>t.next(!1))).add(e.providerOutput.willSeekEvent$.subscribe(()=>t.next(!0)));const i=new r.ValueSubject(!0);this.subscription.add(e.current$.subscribe(()=>i.next(!0))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(r.filter(({to:o})=>o===exports.PlaybackState.PLAYING),r.once()).subscribe(()=>i.next(!1)));let a=0;const n=r.merge(e.providerOutput.isBuffering$,t,i).pipe(r.map(()=>{const o=e.providerOutput.isBuffering$.getValue(),l=t.getValue()||i.getValue();return o&&!l}),r.filterChanged());this.subscription.add(n.subscribe(o=>{o?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))})),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const o=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:o==null?void 0:o.videoWidth,height:o==null?void 0:o.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(o=>{var l,d;const u=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(l=o==null?void 0:o.size)===null||l===void 0?void 0:l.width,height:(d=o==null?void 0:o.size)===null||d===void 0?void 0:d.height},{width:u==null?void 0:u.videoWidth,height:u==null?void 0:u.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(this.info.is3DVideo$)),this.subscription.add(r.merge(e.providerOutput.inPiP$,e.providerOutput.inFullscreen$,e.providerOutput.element$,this.chromecastInitializer.castState$).subscribe(()=>{const o=e.providerOutput.inPiP$.getValue(),l=e.providerOutput.inFullscreen$.getValue(),d=e.providerOutput.element$.getValue(),u=this.chromecastInitializer.castState$.getValue();let c;u===exports.ChromecastState.CONNECTED?c=exports.Surface.SECOND_SCREEN:d?o?c=exports.Surface.PIP:l?c=exports.Surface.FULLSCREEN:c=exports.Surface.INLINE:c=exports.Surface.NONE,this.info.surface$.getValue()!==c&&this.info.surface$.next(c)}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(r.map(e=>e==null?void 0:e.castDevice.friendlyName)).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const t=new r.Subscription;this.subscription.add(t),this.subscription.add(e.current$.pipe(r.filterChanged((i,a)=>i.provider===a.provider)).subscribe(()=>{t.unsubscribe(),t.add(e.providerOutput.availableVideoTracks$.pipe(r.filter(i=>i.length>0),r.once()).subscribe(i=>{this.setStartingVideoTrack(i)}))}))}setStartingVideoTrack(e){let t;this.explicitInitialQuality&&(t=e.find(({quality:i})=>i===this.explicitInitialQuality),this.explicitInitialQuality=void 0),t||(t=Rt(e,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),playbackRate:this.info.currentPlaybackRate$.getValue(),forwardBufferHealth:0,abrLogger:this.abrLogger})),this.desiredState.videoTrack.startTransitionTo(t.id),this.info.currentQuality$.next(t.quality),this.info.videoBitrate$.next(t.bitrate)}initLogs(){this.subscription.add(r.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"quality",type:"start"}))),this.desiredState.videoTrack.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"quality",type:"end"}))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"start"}))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"autoQualityEnabled",type:"end"}))),this.desiredState.seekState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"start"}))),this.desiredState.seekState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"seekState",type:"end"}))),this.desiredState.playbackState.stateChangeStarted$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"start"}))),this.desiredState.playbackState.stateChangeEnded$.pipe(r.map(e=>({transition:e,entity:"playbackState",type:"end"})))).pipe(r.map(e=>({component:"desiredState",message:`[${e.entity} change] ${e.type}: ${JSON.stringify(e.transition)}`}))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var e;const t=(e=this.providerContainer)===null||e===void 0?void 0:e.providerOutput;r.assertNonNullable(this.providerContainer),r.assertNonNullable(t),$p(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Ep(i)),this.providerContainer.current$.subscribe(({type:i})=>hi("provider",i)),t.duration$.subscribe(i=>hi("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>hi("tracks",i)),this.events.fatalError$.subscribe(new we("fatalError")),this.events.managedError$.subscribe(new we("managedError")),t.position$.subscribe(new we("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new we("quality")),this.info.currentBuffer$.subscribe(new we("buffer")),t.isBuffering$.subscribe(new we("isBuffering"))].forEach(i=>this.subscription.add(i)),hi("codecs",zm())}initWakeLock(){if(!window.navigator.wakeLock||!this.tuning.enableWakeLock)return;let e;const t=()=>{e==null||e.release(),e=void 0},i=async()=>{t(),e=await window.navigator.wakeLock.request("screen").catch(a=>{a instanceof DOMException&&a.name==="NotAllowedError"||this.events.managedError$.next({id:"WakeLock",category:r.ErrorCategory.DOM,message:String(a)})})};this.subscription.add(r.merge(r.fromEvent(document,"visibilitychange"),r.fromEvent(document,"fullscreenchange"),this.desiredState.playbackState.stateChangeEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=!!e&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const lv=`@vkontakte/videoplayer-core@${sn}`;Object.defineProperty(exports,"Observable",{enumerable:!0,get:function(){return r.Observable}});Object.defineProperty(exports,"Subject",{enumerable:!0,get:function(){return r.Subject}});Object.defineProperty(exports,"Subscription",{enumerable:!0,get:function(){return r.Subscription}});Object.defineProperty(exports,"ValueSubject",{enumerable:!0,get:function(){return r.ValueSubject}});Object.defineProperty(exports,"VideoQuality",{enumerable:!0,get:function(){return r.VideoQuality}});exports.Player=ov;exports.SDK_VERSION=lv;exports.VERSION=sn;
|