@vkontakte/videoplayer-core 2.0.82 → 2.0.83-dev.65744ed.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +64 -6
- package/es2015.esm.js +64 -6
- package/es2018.cjs.js +64 -6
- package/es2018.esm.js +64 -6
- package/esnext.cjs.js +64 -6
- package/esnext.esm.js +64 -6
- package/evergreen.esm.js +64 -6
- package/index.d.ts +9 -0
- package/package.json +1 -1
package/es2018.cjs.js
CHANGED
|
@@ -1,8 +1,66 @@
|
|
|
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.83-dev.65744ed.0
|
|
3
|
+
* Wed, 19 Apr 2023 17:05:19 GMT
|
|
4
|
+
* https://st.mycdn.me/static/vkontakte-videoplayer/2-0-83/doc/
|
|
5
5
|
*/
|
|
6
|
-
"use strict";var oo=Object.create;var da=Object.defineProperty;var lo=Object.getOwnPropertyDescriptor;var uo=Object.getOwnPropertyNames;var co=Object.getPrototypeOf,ho=Object.prototype.hasOwnProperty;var fo=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of uo(e))!ho.call(s,a)&&a!==t&&da(s,a,{get:()=>e[a],enumerable:!(i=lo(e,a))||i.enumerable});return s};var ca=(s,e,t)=>(t=s!=null?oo(co(s)):{},fo(e||!s||!s.__esModule?da(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),po=require("lodash/debounce.js");const mo="2.0.82",bo="es2018.cjs.js";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_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 le;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(le||(le={}));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 N;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(N||(N={}));var vo=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 So{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=Boolean(window.__onGCastApiAvailable);a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||vo("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(go),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 go=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 ha=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Le=function(s){try{return!!s()}catch(e){return!0}},yo=Le,wi=!yo(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),xr=wi,Or=Function.prototype,Ps=Or.call,To=xr&&Or.bind.bind(Ps,Ps),xe=xr?To:function(s){return function(){return Ps.apply(s,arguments)}},Br=xe,Eo=Br({}.toString),$o=Br("".slice),_i=function(s){return $o(Eo(s),8,-1)},ko=xe,Ao=Le,Po=_i,Ui=Object,wo=ko("".split),_o=Ao(function(){return!Ui("z").propertyIsEnumerable(0)})?function(s){return Po(s)=="String"?wo(s,""):Ui(s)}:Ui,Ri=function(s){return s==null},Ro=Ri,Io=TypeError,Ms=function(s){if(Ro(s))throw Io("Can't call method on "+s);return s},No=_o,Do=Ms,Vt=function(s){return No(Do(s))},Co=function(){},gt={},Qt=function(s){return s&&s.Math==Math&&s},Ae=Qt(typeof globalThis=="object"&&globalThis)||Qt(typeof window=="object"&&window)||Qt(typeof self=="object"&&self)||Qt(typeof ha=="object"&&ha)||function(){return this}()||Function("return this")(),ws=typeof document=="object"&&document.all,Lo=typeof ws=="undefined"&&ws!==void 0,Mr={all:ws,IS_HTMLDDA:Lo},Vr=Mr,xo=Vr.all,me=Vr.IS_HTMLDDA?function(s){return typeof s=="function"||s===xo}:function(s){return typeof s=="function"},Oo=Ae,Bo=me,fa=Oo.WeakMap,Mo=Bo(fa)&&/native code/.test(String(fa)),pa=me,Fr=Mr,Vo=Fr.all,tt=Fr.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:pa(s)||s===Vo}:function(s){return typeof s=="object"?s!==null:pa(s)},Fo=Le,Ge=!Fo(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),yt={},Uo=Ae,ma=tt,_s=Uo.document,jo=ma(_s)&&ma(_s.createElement),Ur=function(s){return jo?_s.createElement(s):{}},Ho=Ge,Go=Le,Yo=Ur,jr=!Ho&&!Go(function(){return Object.defineProperty(Yo("div"),"a",{get:function(){return 7}}).a!=7}),qo=Ge,zo=Le,Hr=qo&&zo(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),Wo=tt,Qo=String,Jo=TypeError,it=function(s){if(Wo(s))return s;throw Jo(Qo(s)+" is not an object")},Ko=wi,Jt=Function.prototype.call,Oe=Ko?Jt.bind(Jt):function(){return Jt.apply(Jt,arguments)},Vs={},ji=Vs,Hi=Ae,Xo=me,ba=function(s){return Xo(s)?s:void 0},Fs=function(s,e){return arguments.length<2?ba(ji[s])||ba(Hi[s]):ji[s]&&ji[s][e]||Hi[s]&&Hi[s][e]},Zo=xe,Us=Zo({}.isPrototypeOf),el=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Gr=Ae,Gi=el,va=Gr.process,Sa=Gr.Deno,ga=va&&va.versions||Sa&&Sa.version,ya=ga&&ga.v8,be,vi;ya&&(be=ya.split("."),vi=be[0]>0&&be[0]<4?1:+(be[0]+be[1]));!vi&&Gi&&(be=Gi.match(/Edge\/(\d+)/),(!be||be[1]>=74)&&(be=Gi.match(/Chrome\/(\d+)/),be&&(vi=+be[1])));var tl=vi,Ta=tl,il=Le,Yr=!!Object.getOwnPropertySymbols&&!il(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ta&&Ta<41}),sl=Yr,qr=sl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",al=Fs,rl=me,nl=Us,ol=qr,ll=Object,zr=ol?function(s){return typeof s=="symbol"}:function(s){var e=al("Symbol");return rl(e)&&nl(e.prototype,ll(s))},ul=String,js=function(s){try{return ul(s)}catch(e){return"Object"}},dl=me,cl=js,hl=TypeError,Hs=function(s){if(dl(s))return s;throw hl(cl(s)+" is not a function")},fl=Hs,pl=Ri,Ii=function(s,e){var t=s[e];return pl(t)?void 0:fl(t)},Yi=Oe,qi=me,zi=tt,ml=TypeError,bl=function(s,e){var t,i;if(e==="string"&&qi(t=s.toString)&&!zi(i=Yi(t,s))||qi(t=s.valueOf)&&!zi(i=Yi(t,s))||e!=="string"&&qi(t=s.toString)&&!zi(i=Yi(t,s)))return i;throw ml("Can't convert object to primitive value")},Si={},vl={get exports(){return Si},set exports(s){Si=s}},Sl=!0,Ea=Ae,gl=Object.defineProperty,yl=function(s,e){try{gl(Ea,s,{value:e,configurable:!0,writable:!0})}catch(t){Ea[s]=e}return e},Tl=Ae,El=yl,$a="__core-js_shared__",$l=Tl[$a]||El($a,{}),Wr=$l,ka=Wr;(vl.exports=function(s,e){return ka[s]||(ka[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var kl=Ms,Al=Object,Ni=function(s){return Al(kl(s))},Pl=xe,wl=Ni,_l=Pl({}.hasOwnProperty),Be=Object.hasOwn||function(e,t){return _l(wl(e),t)},Rl=xe,Il=0,Nl=Math.random(),Dl=Rl(1 .toString),Qr=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Dl(++Il+Nl,36)},Cl=Ae,Ll=Si,Aa=Be,xl=Qr,Ol=Yr,Bl=qr,ht=Cl.Symbol,Wi=Ll("wks"),Ml=Bl?ht.for||ht:ht&&ht.withoutSetter||xl,Se=function(s){return Aa(Wi,s)||(Wi[s]=Ol&&Aa(ht,s)?ht[s]:Ml("Symbol."+s)),Wi[s]},Vl=Oe,Pa=tt,wa=zr,Fl=Ii,Ul=bl,jl=Se,Hl=TypeError,Gl=jl("toPrimitive"),Yl=function(s,e){if(!Pa(s)||wa(s))return s;var t=Fl(s,Gl),i;if(t){if(e===void 0&&(e="default"),i=Vl(t,s,e),!Pa(i)||wa(i))return i;throw Hl("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ul(s,e)},ql=Yl,zl=zr,Gs=function(s){var e=ql(s,"string");return zl(e)?e:e+""},Wl=Ge,Ql=jr,Jl=Hr,Kt=it,_a=Gs,Kl=TypeError,Qi=Object.defineProperty,Xl=Object.getOwnPropertyDescriptor,Ji="enumerable",Ki="configurable",Xi="writable";yt.f=Wl?Jl?function(e,t,i){if(Kt(e),t=_a(t),Kt(i),typeof e=="function"&&t==="prototype"&&"value"in i&&Xi in i&&!i[Xi]){var a=Xl(e,t);a&&a[Xi]&&(e[t]=i.value,i={configurable:Ki in i?i[Ki]:a[Ki],enumerable:Ji in i?i[Ji]:a[Ji],writable:!1})}return Qi(e,t,i)}:Qi:function(e,t,i){if(Kt(e),t=_a(t),Kt(i),Ql)try{return Qi(e,t,i)}catch(a){}if("get"in i||"set"in i)throw Kl("Accessors not supported");return"value"in i&&(e[t]=i.value),e};var Di=function(s,e){return{enumerable:!(s&1),configurable:!(s&2),writable:!(s&4),value:e}},Zl=Ge,eu=yt,tu=Di,Ft=Zl?function(s,e,t){return eu.f(s,e,tu(1,t))}:function(s,e,t){return s[e]=t,s},iu=Si,su=Qr,Ra=iu("keys"),Ys=function(s){return Ra[s]||(Ra[s]=su(s))},qs={},au=Mo,Jr=Ae,ru=tt,nu=Ft,Zi=Be,es=Wr,ou=Ys,lu=qs,Ia="Object already initialized",Rs=Jr.TypeError,uu=Jr.WeakMap,gi,Mt,yi,du=function(s){return yi(s)?Mt(s):gi(s,{})},cu=function(s){return function(e){var t;if(!ru(e)||(t=Mt(e)).type!==s)throw Rs("Incompatible receiver, "+s+" required");return t}};if(au||es.state){var Ee=es.state||(es.state=new uu);Ee.get=Ee.get,Ee.has=Ee.has,Ee.set=Ee.set,gi=function(s,e){if(Ee.has(s))throw Rs(Ia);return e.facade=s,Ee.set(s,e),e},Mt=function(s){return Ee.get(s)||{}},yi=function(s){return Ee.has(s)}}else{var ot=ou("state");lu[ot]=!0,gi=function(s,e){if(Zi(s,ot))throw Rs(Ia);return e.facade=s,nu(s,ot,e),e},Mt=function(s){return Zi(s,ot)?s[ot]:{}},yi=function(s){return Zi(s,ot)}}var hu={set:gi,get:Mt,has:yi,enforce:du,getterFor:cu},fu=wi,Kr=Function.prototype,Na=Kr.apply,Da=Kr.call,pu=typeof Reflect=="object"&&Reflect.apply||(fu?Da.bind(Na):function(){return Da.apply(Na,arguments)}),mu=_i,bu=xe,Xr=function(s){if(mu(s)==="Function")return bu(s)},Zr={},en={},tn={}.propertyIsEnumerable,sn=Object.getOwnPropertyDescriptor,vu=sn&&!tn.call({1:2},1);en.f=vu?function(e){var t=sn(this,e);return!!t&&t.enumerable}:tn;var Su=Ge,gu=Oe,yu=en,Tu=Di,Eu=Vt,$u=Gs,ku=Be,Au=jr,Ca=Object.getOwnPropertyDescriptor;Zr.f=Su?Ca:function(e,t){if(e=Eu(e),t=$u(t),Au)try{return Ca(e,t)}catch(i){}if(ku(e,t))return Tu(!gu(yu.f,e,t),e[t])};var Pu=Le,wu=me,_u=/#|\.prototype\./,Ut=function(s,e){var t=Iu[Ru(s)];return t==Du?!0:t==Nu?!1:wu(e)?Pu(e):!!e},Ru=Ut.normalize=function(s){return String(s).replace(_u,".").toLowerCase()},Iu=Ut.data={},Nu=Ut.NATIVE="N",Du=Ut.POLYFILL="P",Cu=Ut,La=Xr,Lu=Hs,xu=wi,Ou=La(La.bind),an=function(s,e){return Lu(s),e===void 0?s:xu?Ou(s,e):function(){return s.apply(e,arguments)}},Xt=Ae,Bu=pu,Mu=Xr,Vu=me,Fu=Zr.f,Uu=Cu,lt=Vs,ju=an,ut=Ft,xa=Be,Hu=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 Bu(s,this,arguments)};return e.prototype=s.prototype,e},Ci=function(s,e){var t=s.target,i=s.global,a=s.stat,n=s.proto,o=i?Xt:a?Xt[t]:(Xt[t]||{}).prototype,l=i?lt:lt[t]||ut(lt,t,{})[t],d=l.prototype,u,c,h,f,m,b,p,v,S;for(f in e)u=Uu(i?f:t+(a?".":"#")+f,s.forced),c=!u&&o&&xa(o,f),b=l[f],c&&(s.dontCallGetSet?(S=Fu(o,f),p=S&&S.value):p=o[f]),m=c&&p?p:e[f],!(c&&typeof b==typeof m)&&(s.bind&&c?v=ju(m,Xt):s.wrap&&c?v=Hu(m):n&&Vu(m)?v=Mu(m):v=m,(s.sham||m&&m.sham||b&&b.sham)&&ut(v,"sham",!0),ut(l,f,v),n&&(h=t+"Prototype",xa(lt,h)||ut(lt,h,{}),ut(lt[h],f,m),s.real&&d&&(u||!d[f])&&ut(d,f,m)))},Is=Ge,Gu=Be,rn=Function.prototype,Yu=Is&&Object.getOwnPropertyDescriptor,zs=Gu(rn,"name"),qu=zs&&function(){}.name==="something",zu=zs&&(!Is||Is&&Yu(rn,"name").configurable),Wu={EXISTS:zs,PROPER:qu,CONFIGURABLE:zu},nn={},Qu=Math.ceil,Ju=Math.floor,Ku=Math.trunc||function(e){var t=+e;return(t>0?Ju:Qu)(t)},Xu=Ku,Ws=function(s){var e=+s;return e!==e||e===0?0:Xu(e)},Zu=Ws,ed=Math.max,td=Math.min,id=function(s,e){var t=Zu(s);return t<0?ed(t+e,0):td(t,e)},sd=Ws,ad=Math.min,rd=function(s){return s>0?ad(sd(s),9007199254740991):0},nd=rd,Qs=function(s){return nd(s.length)},od=Vt,ld=id,ud=Qs,Oa=function(s){return function(e,t,i){var a=od(e),n=ud(a),o=ld(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}},dd={includes:Oa(!0),indexOf:Oa(!1)},cd=xe,ts=Be,hd=Vt,fd=dd.indexOf,pd=qs,Ba=cd([].push),md=function(s,e){var t=hd(s),i=0,a=[],n;for(n in t)!ts(pd,n)&&ts(t,n)&&Ba(a,n);for(;e.length>i;)ts(t,n=e[i++])&&(~fd(a,n)||Ba(a,n));return a},on=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],bd=md,vd=on,Sd=Object.keys||function(e){return bd(e,vd)},gd=Ge,yd=Hr,Td=yt,Ed=it,$d=Vt,kd=Sd;nn.f=gd&&!yd?Object.defineProperties:function(e,t){Ed(e);for(var i=$d(t),a=kd(t),n=a.length,o=0,l;n>o;)Td.f(e,l=a[o++],i[l]);return e};var Ad=Fs,Pd=Ad("document","documentElement"),wd=it,_d=nn,Ma=on,Rd=qs,Id=Pd,Nd=Ur,Dd=Ys,Va=">",Fa="<",Ns="prototype",Ds="script",ln=Dd("IE_PROTO"),is=function(){},un=function(s){return Fa+Ds+Va+s+Fa+"/"+Ds+Va},Ua=function(s){s.write(un("")),s.close();var e=s.parentWindow.Object;return s=null,e},Cd=function(){var s=Nd("iframe"),e="java"+Ds+":",t;return s.style.display="none",Id.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(un("document.F=Object")),t.close(),t.F},Zt,hi=function(){try{Zt=new ActiveXObject("htmlfile")}catch(e){}hi=typeof document!="undefined"?document.domain&&Zt?Ua(Zt):Cd():Ua(Zt);for(var s=Ma.length;s--;)delete hi[Ns][Ma[s]];return hi()};Rd[ln]=!0;var dn=Object.create||function(e,t){var i;return e!==null?(is[Ns]=wd(e),i=new is,is[Ns]=null,i[ln]=e):i=hi(),t===void 0?i:_d.f(i,t)},Ld=Le,xd=!Ld(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Od=Be,Bd=me,Md=Ni,Vd=Ys,Fd=xd,ja=Vd("IE_PROTO"),Cs=Object,Ud=Cs.prototype,cn=Fd?Cs.getPrototypeOf:function(s){var e=Md(s);if(Od(e,ja))return e[ja];var t=e.constructor;return Bd(t)&&e instanceof t?t.prototype:e instanceof Cs?Ud:null},jd=Ft,hn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:jd(s,e,t),s},Hd=Le,Gd=me,Yd=tt,qd=dn,Ha=cn,zd=hn,Wd=Se,Ls=Wd("iterator"),fn=!1,De,ss,as;[].keys&&(as=[].keys(),"next"in as?(ss=Ha(Ha(as)),ss!==Object.prototype&&(De=ss)):fn=!0);var Qd=!Yd(De)||Hd(function(){var s={};return De[Ls].call(s)!==s});Qd?De={}:De=qd(De);Gd(De[Ls])||zd(De,Ls,function(){return this});var pn={IteratorPrototype:De,BUGGY_SAFARI_ITERATORS:fn},Jd=Se,Kd=Jd("toStringTag"),mn={};mn[Kd]="z";var Js=String(mn)==="[object z]",Xd=Js,Zd=me,fi=_i,ec=Se,tc=ec("toStringTag"),ic=Object,sc=fi(function(){return arguments}())=="Arguments",ac=function(s,e){try{return s[e]}catch(t){}},Li=Xd?fi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=ac(e=ic(s),tc))=="string"?t:sc?fi(e):(i=fi(e))=="Object"&&Zd(e.callee)?"Arguments":i},rc=Js,nc=Li,oc=rc?{}.toString:function(){return"[object "+nc(this)+"]"},lc=Js,uc=yt.f,dc=Ft,cc=Be,hc=oc,fc=Se,Ga=fc("toStringTag"),bn=function(s,e,t,i){if(s){var a=t?s:s.prototype;cc(a,Ga)||uc(a,Ga,{configurable:!0,value:e}),i&&!lc&&dc(a,"toString",hc)}},pc=pn.IteratorPrototype,mc=dn,bc=Di,vc=bn,Sc=gt,gc=function(){return this},yc=function(s,e,t,i){var a=e+" Iterator";return s.prototype=mc(pc,{next:bc(+!i,t)}),vc(s,a,!1,!0),Sc[a]=gc,s},Tc=Ci,Ec=Oe,vn=Wu,$c=yc,kc=cn,Ac=bn,Ya=hn,Pc=Se,qa=gt,Sn=pn,wc=vn.PROPER;vn.CONFIGURABLE;Sn.IteratorPrototype;var ei=Sn.BUGGY_SAFARI_ITERATORS,rs=Pc("iterator"),za="keys",ti="values",Wa="entries",_c=function(){return this},Rc=function(s,e,t,i,a,n,o){$c(t,e,i);var l=function(S){if(S===a&&f)return f;if(!ei&&S in c)return c[S];switch(S){case za:return function(){return new t(this,S)};case ti:return function(){return new t(this,S)};case Wa:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[rs]||c["@@iterator"]||a&&c[a],f=!ei&&h||l(a),m=e=="Array"&&c.entries||h,b,p,v;if(m&&(b=kc(m.call(new s)),b!==Object.prototype&&b.next&&(Ac(b,d,!0,!0),qa[d]=_c)),wc&&a==ti&&h&&h.name!==ti&&(u=!0,f=function(){return Ec(h,this)}),a)if(p={values:l(ti),keys:n?f:l(za),entries:l(Wa)},o)for(v in p)(ei||u||!(v in c))&&Ya(c,v,p[v]);else Tc({target:e,proto:!0,forced:ei||u},p);return o&&c[rs]!==f&&Ya(c,rs,f,{name:a}),qa[e]=f,p},Ic=function(s,e){return{value:s,done:e}},Nc=Vt,Ks=Co,Qa=gt,gn=hu,Dc=yt.f,Cc=Rc,ii=Ic,Lc=Sl,xc=Ge,yn="Array Iterator",Oc=gn.set,Bc=gn.getterFor(yn);Cc(Array,"Array",function(s,e){Oc(this,{type:yn,target:Nc(s),index:0,kind:e})},function(){var s=Bc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,ii(void 0,!0)):t=="keys"?ii(i,!1):t=="values"?ii(e[i],!1):ii([i,e[i]],!1)},"values");var Ja=Qa.Arguments=Qa.Array;Ks();Ks();Ks();if(!Lc&&xc&&Ja.name!=="values")try{Dc(Ja,"name",{value:"values"})}catch(s){}var Mc=Se,Vc=gt,Fc=Mc("iterator"),Uc=Array.prototype,jc=function(s){return s!==void 0&&(Vc.Array===s||Uc[Fc]===s)},Hc=Li,Ka=Ii,Gc=Ri,Yc=gt,qc=Se,zc=qc("iterator"),Tn=function(s){if(!Gc(s))return Ka(s,zc)||Ka(s,"@@iterator")||Yc[Hc(s)]},Wc=Oe,Qc=Hs,Jc=it,Kc=js,Xc=Tn,Zc=TypeError,eh=function(s,e){var t=arguments.length<2?Xc(s):e;if(Qc(t))return Jc(Wc(t,s));throw Zc(Kc(s)+" is not iterable")},th=Oe,Xa=it,ih=Ii,sh=function(s,e,t){var i,a;Xa(s);try{if(i=ih(s,"return"),!i){if(e==="throw")throw t;return t}i=th(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return Xa(i),t},ah=an,rh=Oe,nh=it,oh=js,lh=jc,uh=Qs,Za=Us,dh=eh,ch=Tn,er=sh,hh=TypeError,pi=function(s,e){this.stopped=s,this.result=e},tr=pi.prototype,fh=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=ah(e,i),u,c,h,f,m,b,p,v=function(g){return u&&er(u,"normal",g),new pi(!0,g)},S=function(g){return a?(nh(g),l?d(g[0],g[1],v):d(g[0],g[1])):l?d(g,v):d(g)};if(n)u=s.iterator;else if(o)u=s;else{if(c=ch(s),!c)throw hh(oh(s)+" is not iterable");if(lh(c)){for(h=0,f=uh(s);f>h;h++)if(m=S(s[h]),m&&Za(tr,m))return m;return new pi(!1)}u=dh(s,c)}for(b=n?s.next:u.next;!(p=rh(b,u)).done;){try{m=S(p.value)}catch(g){er(u,"throw",g)}if(typeof m=="object"&&m&&Za(tr,m))return m}return new pi(!1)},ph=Gs,mh=yt,bh=Di,vh=function(s,e,t){var i=ph(e);i in s?mh.f(s,i,bh(0,t)):s[i]=t},Sh=Ci,gh=fh,yh=vh;Sh({target:"Object",stat:!0},{fromEntries:function(e){var t={};return gh(e,function(i,a){yh(t,i,a)},{AS_ENTRIES:!0}),t}});var Th=Vs,Eh=Th.Object.fromEntries,$h={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},kh=$h,Ah=Ae,Ph=Li,wh=Ft,ir=gt,_h=Se,sr=_h("toStringTag");for(var ns in kh){var ar=Ah[ns],os=ar&&ar.prototype;os&&Ph(os)!==sr&&wh(os,sr,ns),ir[ns]=ir.Array}var Rh=Eh,Ih=Rh,Nh=Ih,Dh=Nh,jt=Dh,pt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(pt||(pt={}));var mt=(s,e=0,t=pt.OFFSET_P)=>{switch(t){case pt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case pt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s},k=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const ve={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},mi=(s,e)=>ve[s].height>ve[e].height,Ch=(s,e)=>ve[s].height>=ve[e].height,xt=(s,e)=>ve[s].height<ve[e].height,Lh=(s,e)=>ve[s].height<=ve[e].height,xh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:xt(e,t)?1:-1)[0],Oh=Object.keys(ve).sort((s,e)=>xt(s,e)?-1:1),st=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return Oh.find(a=>{const n=ve[a];return n.width>=i&&n.height>=t})},Bh=s=>ve[s].height,Ti=s=>s===exports.VideoQuality.INVARIANT;class W{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}setState(e){const t=this.transition,i=this.state;this.transition=void 0,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.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}}const Mh=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.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 Vh=5,Fh=5,Uh=500,rr=7e3;class jh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new W(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===N.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(Mh(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(Uh)).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===N.Applying||Math.abs(l-n)>Vh)&&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<Fh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),k(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),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(L.PLAYING),k(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:N.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),k(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),k(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&&k(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=xh(Object.keys(c));r.assertNonNullable(h);const f=c[h];r.assertNonNullable(f),a=f,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:{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=mt(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===N.Applying||i.state===N.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(rr).subscribe(()=>n(`timeout(${rr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===N.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)}`})}}class nr{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 En extends nr{constructor(){super(),this.listeners||nr.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 $n=class{constructor(){Object.defineProperty(this,"signal",{value:new En,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&&($n.prototype[Symbol.toStringTag]="AbortController",En.prototype[Symbol.toStringTag]="AbortSignal");function kn(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 Hh(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!kn({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 f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(m){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((m,b)=>{c.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const xi=kn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),An=xi?Hh({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,bt=xi?An.fetch:window.fetch;xi?An.Request:window.Request;const Ze=xi?$n:window.AbortController,Dt=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Ot{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,a=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];a.push(e),this.dashJsRequestQueue.set(i,a)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const a=t[0];if(!a||!a.request.range)continue;const[n,o]=Dt(a.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const a=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,a)}}}abort(e){var t;if(e){const{request:i}=e,a=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);a&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(Dt),a=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const m=i[f][1];m-a<=2*this.params.minDataSize&&(n=Math.max(n,m))}a===0?n=Math.max(n,a+this.params.minInitSize):n=Math.max(n,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${a}-${n}`);const l=o.toString(),d=new Ze,u=d.signal,c={url:e,from:a,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var m,b;throw(b=(m=this.params).onError)===null||b===void 0||b.call(m,{id:"BigRequestParsing",category:r.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return bt(l,{signal:u}).then(f=>{var m,b,p;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[v,S]=f.body.tee();(b=(m=this.params).onDownloadStream)===null||b===void 0||b.call(m,S);const g=v.getReader(),A=parseInt((p=f.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||n-a+1;c.data=new ArrayBuffer(A);const E=new Uint8Array(c.data),T=async({done:w,value:V})=>{w?this.onBigRequestProgress(c):V&&(E.set(V,c.loaded),c.loaded+=V.byteLength,this.onBigRequestProgress(c),await(g==null?void 0:g.read().then(T,Ot.suppressStreamErrors).catch(h)))};g==null||g.read().then(T,Ot.suppressStreamErrors).catch(h)},Ot.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:a,data:n,response:o}){var l,d,u,c,h,f,m,b;if(!this.activeRequests.has(e)||!n)return;const p=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const v of p){const{request:S}=v,[g,A]=Dt(S),E=g>=t&&A<=t+a,T=t>=g&&t+a<A,w=n.slice(g-t,Math.min(A-t+1,a));if((E||T)&&(S.requestStartDate=(d=S.requestStartDate)!==null&&d!==void 0?d:new Date,S.firstByteDate=(u=S.firstByteDate)!==null&&u!==void 0?u:new Date,S.bytesLoaded=w.byteLength,S.bytesTotal=i-t),E){S.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(C=>C!==v)),(h=v.success)===null||h===void 0||h.call(v,w,"",e);const V=o?Array.from(o.headers.entries()).map(([C,R])=>`${C}: ${R}`).join(`\r
|
|
7
|
-
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(S,e,(m=o==null?void 0:o.status)!==null&&m!==void 0?m:200,V,[])}else T&&((b=v.progress)===null||b===void 0||b.call(v,{loaded:a,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},a){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:r.ErrorCategory.NETWORK,message:"Download error",thrown:a}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=Dt(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:e,from:t,to:i}){var a,n;if(!this.activeRequests.has(e))return;const o=(a=this.dashJsRequestQueue.get(e))!==null&&a!==void 0?a:[];for(const l of o){const[d,u]=Dt(l.request);(d>=t&&d<i||u>t&&u<=i)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class Ei{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(Ei.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;Ei.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Gh=(s,e)=>t=>({create:i=>{const a=s(t).create(i);return new Ei(a,e,i)}}),Yh=(s,e)=>{const t=new Ot(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,a=i.getLoader;return{getLoader:n=>{const o=a(n);return Gh(o,t)}}},!0),()=>t.destroy()};var qh=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)},zh=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,f,m,b,p;const v=jt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(A=>A.split(": ")));if("x-playback-duration"in v||"x-playback-duration-millis"in v){const A=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(m=E!=null?E:A*1e3)!==null&&m!==void 0?m:NaN;r.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const S=(b=v["x-delivery-type"])!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,g=(p={1:!0,0:!1}[v["x-reused"]])!==null&&p!==void 0?p:void 0;i.next(S),a.next(g)},u=c=>{c.readyState>=2&&!o&&(o=!0,t.next(Date.now()-n))};return s.extend("XHRLoader",function(){const{parent:c}=this,h=c.load.bind(c);return{load:function(f){if(f.request.type==="MPD"){const m=f.onload,b=f.progress;f.onload=function(...p){return d(this),m(...p)},f.progress=function(...p){return u(this),b(...p)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},vt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},Wh=s=>s.extend("RequestModifier",()=>({modifyRequestURL:vt}),!0),Qh=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 ke=(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},at=(s,e,t)=>ke(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),Me=(s,e,t,i)=>ke(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}),Ye=(s,e,t,i)=>ke(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),Jh=s=>["__",s.language,s.label].join("|"),Kh=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class Pe{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}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(ke(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(ke(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(ke(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();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,f;const m=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;m&&m.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(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(Pe.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id!==""?e.id:Jh(e);return this.externalTracks.has(a)?{id:a,type:"external",language:t,label:i,url:this.externalTracks.get(a).url}:{id:a,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))r.isNonNullable(e)&&Kh(t,e)?t.mode="showing":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),this.externalTracks.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);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Ve=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class Xs{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Pn=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const xs=3;class Xh{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 wn=(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 Zh=50,ef=s=>s.webkitAudioDecodedByteCount!=="undefined"?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!=="undefined"?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,Fe=s=>{const e=b=>r.fromEvent(s,b).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(b=>r.fromEvent(s,b))).pipe(r.map(b=>b.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>wn(s.buffered,s.currentTime))),n=Pn()?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),o=r.fromEvent(s,"playing").pipe(r.debounce(Zh),r.map(()=>ef(s))),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(()=>Boolean(s.error||s.played.length)),r.map(()=>{var b;const p=s.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(b=s.error)!==null&&b!==void 0?b:void 0}})),c=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),h=new r.Subject,f=.3;let m;return c.subscribe(b=>{s.loop&&r.isNonNullable(m)&&r.isNonNullable(b)&&m>=s.duration-f&&b<=f&&h.next(m),m=b}),{playing$:n,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,isAudioAvailable$:o,playbackRateState$:d}},Zs=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var tf=Ci,sf=Ni,af=Qs,rf=Ws;tf({target:"Array",proto:!0},{at:function(e){var t=sf(this),i=af(t),a=rf(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var nf=Fs,_n=nf,of=_n,lf=of("Array","at"),uf=lf,df=uf,cf=df,hf=cf,Re=hf;let ea=!1,Ie={};const ff=s=>{ea=s},pf=()=>{Ie={}},mf=s=>{s(Ie)},si=(s,e)=>{var t;ea&&(Ie.meta=(t=Ie.meta)!==null&&t!==void 0?t:{},Ie.meta[s]=e)};class $e{constructor(e){this.name=e}next(e){var t,i;if(!ea)return;Ie.series=(t=Ie.series)!==null&&t!==void 0?t:{};const a=(i=Ie.series[this.name])!==null&&i!==void 0?i:[];a.push([Date.now(),e]),Ie.series[this.name]=a}}const bf=new $e("best_bitrate"),vf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Sf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Ht=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,m;const b=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*i.containerSizeFactor,height:e.height*b*i.containerSizeFactor},v=p&&st(p),S=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,g=s.filter(I=>!Ti(I.quality)).sort((I,_)=>mi(I.quality,_.quality)?-1:1),A=(h=Re(g,-1))===null||h===void 0?void 0:h.quality,E=(f=Re(g,0))===null||f===void 0?void 0:f.quality,T=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&xt(a.max,a.min)||r.isNonNullable(a.min)&&E&&mi(a.min,E)||r.isNonNullable(a.max)&&A&&xt(a.max,A),w=S*vf(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),C=g.filter(I=>{const _=v?xt(I.quality,v):!0,H=r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(I.bitrate)?t-n>=I.bitrate*w:!0,Q=i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!Ti(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&mi(I.quality,d.quality),Z=T||(r.isNullable(a.max)||Lh(I.quality,a.max))&&(r.isNullable(a.min)||Ch(I.quality,a.min));return _&&H&&!Q&&Z})[0];C&&C.bitrate&&bf.next(C.bitrate);const R=(m=C!=null?C:g[Math.ceil((g.length-1)/2)])!==null&&m!==void 0?m:s[0],F=R&&u&&u.history[R.id]&&r.now()-u.history[R.id]<=i.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!F&&u.recordSelection(R),F&&(u!=null&&u.last)){const I=u.last;return u==null||u.recordSwitch(I),I}return u==null||u.recordSwitch(R),R};var ne=s=>new URL(s).hostname;const gf=300,$i=(s,e=gf)=>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(po(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()}),yf=5e3,Ct={};var x;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(x||(x={}));const te=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class or{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(x.DOWNLOADING_LIB),this.textTracksManager=new Pe,this.videoTracks=[],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 Xs,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===x.DOWNLOADING_LIB||t===x.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&t!==x.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 x.STOPPED:break;case x.PLAYING:case x.PAUSED:case x.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case x.STOPPED:this.prepare();break;case x.PLAYING:case x.PAUSED:case x.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case x.PLAYING:break;case x.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 x.READY:this.play();break;case x.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case x.PLAYING:this.pause(),this.liveOffset.pause();break;case x.PAUSED:break;case x.READY:this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case x.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=Ve(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(ne(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"),yf);import("dashjs/dist/dash.mediaplayer.min.js").then(a=>{e||(Ct.MediaPlayer=a.MediaPlayer,Ct.Debug=a.Debug,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Ct.MediaPlayer,"dashjs not loaded"),r.assertNonNullable(Ct.Debug,"dashjs not loaded"),this.player=Ct.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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?Zs(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Yh(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&Qh(this.player),qh(this.player),this.params.tuning.requestQuick&&Wh(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(x.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=p=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:p})},a=(p,v)=>this.subscription.add(p.subscribe(v,i));a($i(this.video),this.elementSize$),a(te(this.player,"error").pipe(r.map(p=>{const v=typeof p.error=="object"?p.error.code:p.error,S=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${v}`,message:S}})),e.error$),a(te(this.player,"playbackError").pipe(r.map(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const n=te(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({newQuality:p})=>{var v;return(v=this.videoTracks.find(({bitrateInfo:S})=>S.qualityIndex===p))===null||v===void 0?void 0:v.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:p})=>p===x.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(ke(t.videoTrack,()=>{var p,v;const S=this.player.getQualityFor("video");return(v=(p=this.videoTracks.find(({bitrateInfo:g})=>g.qualityIndex===S))===null||p===void 0?void 0:p.track)===null||v===void 0?void 0:v.id},p=>{var v;if(r.isNullable(p))return;const S=(v=this.videoTracks.find(({track:g})=>g.id===p))===null||v===void 0?void 0:v.bitrateInfo;S&&this.player.setQualityFor("video",S.qualityIndex)},{changed$:n.pipe(r.map(p=>p==null?void 0:p.id)),onError:i}))},i)),this.subscription.add(ke(t.autoVideoTrackSwitching,()=>{var p,v,S;return(S=(v=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||v===void 0?void 0:v.autoSwitchBitrate)===null||S===void 0?void 0:S.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:i})),a(te(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({state:p})=>p==="bufferStalled")),e.isBuffering$),a(te(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:v}})=>{var S,g;const A=this.player.getDashMetrics(),E=A.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),T=(S=A.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,w=(g={1:!0,0:!1}[E])!==null&&g!==void 0?g:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(ne(v))}),a(te(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:v,availableFrom:S}}})=>{this.isLive$.next(v),this.availableFrom$.next(S.getTime()),v||e.duration$.next(p),this.videoTracks=[];const g=this.player.getQualityFor("video");let A;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=st(E),V=E.bitrate/1e3,C={width:E.width,height:E.height},R=this.frameRatesByFrameHeight[E.height];if(w){const F={id:T,quality:w,bitrate:V,size:C,fps:R};this.videoTracks.push({track:F,bitrateInfo:E}),E.qualityIndex===g&&(A=F)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),A&&e.currentVideoTrack$.next(A),this.videoState.setState(x.STREAM_INITIALIZED),this.videoState.startTransitionTo(x.READY)}),a(te(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const v=p.requestEndDate.getTime()-p.firstByteDate.getTime(),S=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(S,v)}),a(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),v=Ht(this.videoTracks.map(({track:g})=>g),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),S=this.videoTracks.find(({track:g})=>g===v);S!=null&&S.bitrateInfo&&this.player.setQualityFor("video",S==null?void 0:S.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:p})=>p),r.map(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const o=te(this.player,"playbackTimeUpdated").pipe(r.map(({time:p})=>p!=null?p:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:p,currentTime:v})=>this.params.output.liveTime$.next(p+v*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(te(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(te(this.player,"playbackEnded"),e.endedEvent$),a(te(this.player,"playbackProgress").pipe(r.map(()=>wn(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(te(this.player,"playbackPlaying"),()=>{this.videoState.setState(x.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)}),a(te(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(x.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(te(this.player,"playbackPaused"),()=>{this.videoState.setState(x.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)}),a(te(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===x.READY&&this.videoState.setState(x.READY)}),a(this.isLive$,e.isLive$),a($i(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}=zh(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(te(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(p=>p<60))}),({isLive:p,isShort:v})=>{const S=!p&&v;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:S}}})}),a(o.pipe(r.filter(p=>p>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(te(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(te(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(at(this.video,t.isLooped,i));const{volumeState$:f,looped$:m,playbackRateState$:b}=Fe(this.video);this.subscription.add(Me(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(m.subscribe(e.loopedEvent$)),this.subscription.add(Ye(this.video,t.playbackRate,b,i))}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(x.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(x.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=mt(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,pt.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(x.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(x.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Gt=s=>{switch(s){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},qe=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function ae(){return r.now()}function Rn(s){return ae()-s}function lr(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 Tf(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function bi(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,m="arraybuffer",b=7e3,p=2e3,v=()=>{if(d)return;r.assertNonNullable(c);const _=Rn(c);let H;if(_<p){H=p-_,setTimeout(v,H);return}p*=2,p>b&&(p=b),o&&o.abort(),o=new a,w()};const S=_=>(n=_,I),g=_=>(h=_,I),A=()=>(m="json",I),E=()=>{if(!d){if(--u>=0){v(),i&&i();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,I),w=()=>{c=ae(),o=new a,o.open("get",s);let _=0,H,Q=0;const Z=()=>(r.assertNonNullable(c),Math.max(c,Math.max(H||0,Q||0)));if(n&&o.addEventListener("progress",$=>{const D=ae();n.updateChunk&&$.loaded>_&&(n.updateChunk(Z(),$.loaded-_),_=$.loaded,H=D)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const D=o.response.byteLength-_;D&&n.updateChunk&&n.updateChunk(Z(),D)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=ae(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=m,o.send(),I},I={withBitrateReporting:S,withParallel:T,withJSONResponse:A,withRetryCount:_=>(u=_,I),withRetryInterval:(_,H)=>(r.isNonNullable(_)&&(p=_),r.isNonNullable(H)&&(b=H),I),withTimeout:_=>(l=_,I),withFinally:g,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return I}const Ef=100,$f=2e3,kf=500;let Af=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-kf;if(t-e>$f){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>Ef&&(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 Pf{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=ae(),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=ae()-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=bi(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=ae()}_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=ae();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 ai=1e4,ri=3,wf=300,_f=2e3,Rf=6e4,If=10,Nf=1,Df=500;class Cf{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 Af(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=lr(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=lr(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;Boolean(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=()=>{Tf(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 Pf(ri,ai,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 E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,w)=>{d&&d.abort(),d=bi(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(ai).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ri).withFinally(()=>{d=null}).send()},m=(E,T,w)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=E=>{const T=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),i.playbackRate=E)},p=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const w=ae()-1e4;let V=0;for(let R=0;R<this.bufferStates.length;R++){const F=this.bufferStates[R];E=Math.min(E,F.buf),F.ts<w&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${E} drop=${V} jitter=${this.sourceJitter}`);let C=E-Nf;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?b(1.15):C>1?b(1.1):C>.3?b(1.05):b(1)}},S=E=>{let T;const w=()=>T&&T.start?T.start.length:0,V=$=>T.start[$]/1e3,C=$=>T.dur[$]/1e3,R=$=>T.fragIndex+$,F=($,D)=>({chunkIdx:R($),startTS:V($),dur:C($),discontinuity:D}),I=()=>{let $=0;if(T&&T.dur){let D=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=D;this.sourceJitter>1&&(X+=this.sourceJitter-1);let ee=T.dur.length-1;for(;ee>=0&&(X-=T.dur[ee],!(X<=0));--ee);$=Math.min(ee,T.dur.length-1-q),$=Math.max($,0)}return F($,!0)},_=$=>{const D=w();if(!(D<=0)){if(r.isNonNullable($)){for(let q=0;q<D;q++)if(V(q)>$)return F(q)}return I()}},H=$=>{const D=w(),q=$?$.chunkIdx+1:0,X=q-T.fragIndex;if(!(D<=0)){if(!$||X<0||X-D>If)return t(`Resync: offset=${X} bChunks=${D} chunk=`+JSON.stringify($)),I();if(!(X>=D))return F(q-T.fragIndex,!1)}},Q=($,D,q)=>{u&&u.abort(),u=bi(this.urlResolver.resolve($,!0,this.lowLatency),D,q,()=>this._retryCallback()).withTimeout(ai).withRetryCount(ri).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,D)=>{Q(E,q=>{if(!h())return;T=q;const X=Boolean(T.lowLatency);X!==this.lowLatency&&p(X);let ee=0;for(let oe=0;oe<T.dur.length;++oe)ee+=T.dur[oe];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,$(_(D))},()=>this._handleNetworkError())},nextChunk:H}},g=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let V=S(e.jidxUrl),C,R,F,I,_=0,H,Q,Z;const $=()=>{H&&(clearTimeout(H),H=void 0);const U=Math.max(Df,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=_+U,re=ae(),ue=Math.min(1e4,ie-re);_=re;const ze=()=>{u||h()&&V.seek(()=>{h()&&(_=ae(),D(),$())})};ue>0?H=window.setTimeout(()=>{this.paused?$():ze()},ue):ze()},D=()=>{let U;for(;U=V.nextChunk(I);)I=U,ge(U);const ie=V.nextChunk(F);if(ie){if(F&&ie.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(g(),this._initPlayerWith(e));return}oe(ie)}else $()},q=(U,ie)=>{if(!h()||!this.sourceBuffer)return;let re,ue,ze;const ye=Ue=>{window.setTimeout(()=>{h()&&q(U,ie)},Ue)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),ye(100);else{const Ue=ae(),We=T.currentTime;!this.paused&&T.buffered.length>1&&Q===We&&Ue-Z>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),Q!==We&&(Q=We,Z=Ue);const Et=this._getBufferSizeSec();if(Et>30)w(`Buffered ${Et} seconds; delaying appendBuffer`),ye(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:Ue,buf:Et}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(rt){if(rt.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),ze=this.sourceBuffer.buffered.length,ze!==0&&(re=this.sourceBuffer.buffered.start(0),ue=We,ue-re>4&&this.sourceBuffer.remove(re,ue-3)),ye(1e3);else throw rt}}},X=()=>{R&&C&&(w([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(F)]),q(R,function(){R=null,D()}))},ee=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),oe=U=>{h()&&m(ee(U),(ie,re)=>{if(h()){if(re/=1e3,R=ie,F=U,o=U.startTS,re){const ue=Math.min(10,U.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}X()}},()=>this._handleNetworkError())},ge=U=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(U),!1)))},Tt=U=>{h()&&(e.cachedHeader=U,q(U,()=>{C=!0,X()}))};n=!0,V.seek(U=>{if(h()){if(_=ae(),!U){$();return}I=U,!r.isNullable(E)||U.startTS>E?oe(U):(F=U,D())}},E),e.cachedHeader?Tt(e.cachedHeader):f(e.headerUrl,Tt,()=>this._handleNetworkError())},stop:g,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 f,m,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(m=this._getBufferSizeSec(),b=h/this.bitrate,m>10&&b>.8||m>15&&b>.5||m>20&&b>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,m)=>{const b=ae();if(this.chunkRateEstimator.addInterval(f,b,m)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:b-f,speed:v}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Rn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const m=n.updateChunk(h,f);return m&&u(),m},notifySwitch:h=>{const f=ae();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=bi(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(ai).withRetryCount(ri).withRetryInterval(wf,_f).send().withFinally(()=>{this.manifestRequest=void 0})}_playVideoElement(e){const{videoElement:t}=this.params;qe(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))},Rf))}_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 Lf=[O.PAUSED,O.PLAYING,O.READY],xf=[O.PAUSED,O.PLAYING,O.READY];class Of{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(O.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new Pe,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new Xs,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 f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),m=(o=Gt(h.name))!==null&&o!==void 0?o:st(h.video),b=h.bitrate/1e3,p={...h.video};if(!m)continue;const v={id:f,quality:m,bitrate:b,size:p};c.push({track:v,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=()=>{var a;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(O.STOPPED));return}if(!o){if(xf.includes(n)){const c=(a=this.params.desiredState.videoTrack.getTransition())===null||a===void 0?void 0:a.to;r.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===N.Requested&&Lf.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case O.STOPPED:this.videoState.startTransitionTo(O.MANIFEST_READY),this.dash.attachSource(mt(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:l===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(n)}}},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=Ve(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.hostname$.next(ne(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=Fe(this.video);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===N.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(at(this.video,this.params.desiredState.isLooped,t)).add(Me(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(Ye(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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&Bh(a);this.dash.setMaxAutoQuality(n)})).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$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Cf({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=Ht(l.map(({track:f})=>f),{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()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;r.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(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=-e,i=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(i),this.dash.reinit(mt(this.params.source.url,i))}}var In=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}},Xe=(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 Bf=s=>{const e=document.createElement("a");return e.href=s,e.origin},Mf=s=>{const e=document.createElement("a");return e.href=s,e.host};class Nn{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(r.assertNonNullable(this._xhr),((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=jt(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(Mf(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 ki{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,f=0;const m=p=>{a(ki._str2ua(p.substr(d))),d=p.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=vt(b)),this._lastXhr=new Nn(b,e.failoverHosts,p=>{this._lastXhr=void 0,m(p);const v=Date.now()-u;this._params.onBandwidthChange({size:p.length,duration:v,speed:8*p.length/(v/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),n==null||n()},p=>{if(p.length-d>l&&m(p),h===0){h=Date.now();return}f=p.length-c;const v=Date.now()-h;f>=100*1024&&v>=1e3&&(this._params.onBandwidthChange({size:f,duration:v,speed:8*f/(v/1e3)}),f=0,c=p.length,h=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},o,(p,v,S)=>this._params.onError(p,v,S))})}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=ki._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 Vf{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=vt(i)),new Nn(i,t,a=>{this.attachManifest(a,t,Bf(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,f,m,b,p,v,S,g,A,E,T,w,V,C,R,F,I,_;const H=u.getElementsByTagName("SegmentBase")[0],Q=H&&o(H,"indexRange").split("-"),Z=H&&H.getElementsByTagName("Initialization")[0],$=Z&&o(Z,"range").split("-");if(!$||!Q){const ge=u.parentElement;if((ge==null?void 0:ge.getAttribute("contentType"))==="text"){const Tt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,U=(i?i+"/":"")+((b=(m=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||m===void 0?void 0:m[0])===null||b===void 0?void 0:b.data),ie=(p=ge.getAttribute("lang"))!==null&&p!==void 0?p:void 0;U&&d.push({id:Tt,url:U,language:ie})}return}const D=.1,q=Number((v=u.attributes.getNamedItem("bandwidth"))===null||v===void 0?void 0:v.value),X=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const oe=(g=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&g!==void 0?g:void 0;ee=oe?Zs(oe):void 0,l.push({width:Number((A=u.attributes.getNamedItem("width"))===null||A===void 0?void 0:A.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:q,baseURL:X,failoverHosts:t,indexFrom:Number(Q[0]),indexTo:Number(Q[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&w!==void 0?w:void 0,mimeType:(C=(V=u.attributes.getNamedItem("mimeType"))===null||V===void 0?void 0:V.value)!==null&&C!==void 0?C:void 0,fps:ee,bufferSize:D*q/8,bufferLength:D,name:(F=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&F!==void 0?F:void 0,id:(_=(I=u.attributes.getNamedItem("id"))===null||I===void 0?void 0:I.value)!==null&&_!==void 0?_:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_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 f=0;f<c;f+=1){const m=u+(o.getUint32(n,!1)&2147483647),b=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:b/l,fromOffset:u,toOffset:m-1}),u=m,d=b}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 m=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),m)}const c=this._appendVector[String(u.fromTime)];c!==a&&(a=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const m=this._buffer.getByTime(this._video.currentTime);if(!m){this._onDashCallback("buffering");return}h=m.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==m.to&&(n=m.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(m);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},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 ki({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 B;(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"})(B||(B={}));const Ff=[B.PAUSED,B.PLAYING];class Uf{constructor(e){this.videoState=new W(B.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new Pe,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=t=>{var i,a,n;const o=[];for(const l of t){const d=(a=(i=l.name)!==null&&i!==void 0?i:l.id)!==null&&a!==void 0?a:l.height.toString(10),u=(n=l.name&&Gt(l.name))!==null&&n!==void 0?n:st(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const m={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:m,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(B.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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("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(B.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===N.Requested&&Ff.includes(t)&&this.seek(o.position,o.forcePrecise),t){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:a===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(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=Ve(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(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Xh(this.video),this.dash=new Vf({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),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=Fe(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==N.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(at(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ye(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o($i(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.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.stateChangeEnded$,this.params.output.element$,this.elementSize$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=this.params.desiredState.videoTrack.getState(),b=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),v=a();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!v&&r.isNonNullable(m))S=m;else{const g=Xe(this.video.buffered,this.video.currentTime*1e3),A=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(g/A,1);S=(d=Ht(h.map(({track:T})=>T),{container:p,throughput:b,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:T})=>T===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return r.isNonNullable(S)?(u=h.find(({track:g})=>g.id===S))===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===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(B.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=Xe(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(ne(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=In(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.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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(){qe(this.video).then(e=>{e||(this.videoState.setState(B.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var he;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(he||(he={}));var Ai;(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"})(Ai||(Ai={}));var fe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(fe||(fe={}));var j;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(j||(j={}));var St;(function(s){s.MP4="mp4",s.WEBM="webm"})(St||(St={}));var Os=(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 jf=(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)},Hf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",ur=Hf?jf:window.requestIdleCallback;var ls,us;let Dn=!1;try{Dn=Pn()&&parseInt((us=(ls=navigator.userAgent.match(/Version\/(\d+)/))===null||ls===void 0?void 0:ls[1])!==null&&us!==void 0?us:"",10)<16}catch(s){console.error(s)}class Gf{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;Dn&&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)}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"&&i==="remove"||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 dr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};const Cn=new TextDecoder("ascii"),Ln=s=>{let e=0,t=s.getUint32(e);e+=4;const i=new DataView(s.buffer,s.byteOffset+e,4),a=Cn.decode(i);e+=4,t===0?t=1/0:t===1&&(e+=8,t=1/0);const n=Math.min(t,s.byteLength)-e,o=new DataView(s.buffer,s.byteOffset+e,n);return{id:a,size:t,contents:o}},Yf=s=>Cn.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",qf=(s,e,t)=>{const i=Ln(s),a=[];let n=0;const o=()=>{const p=i.contents.getUint32(n);return n+=4,p};if((o()&4278190080)!==0)throw new SyntaxError("Unsupported sidx version");o();const u=o(),c=o(),h=o(),f=o()&4294967295;let m=c/u*1e3,b=(t?t.to+1:s.byteOffset+s.byteLength)+h;for(let p=0;p<f;p++){const v=o(),S=v>>>31,g=v<<1>>>1,A=o();if(o(),S!==0)throw new Error("Unsupported multilevel sidx");const E=A/u*1e3;a.push({status:j.NONE,time:{from:m,to:m+E},byte:{from:b,to:b+g-1}}),m+=E,b+=g}return a},zf=s=>{let e=0,t=!1,i=!1;for(;e<=s.byteLength&&!t;){const a=new DataView(s.buffer,s.byteOffset+e);try{const n=Ln(a);if(i||(i=n.id==="mdat"),e+n.size<=s.byteLength)e+=n.size;else break}catch(n){t=!0}}return e>0&&e<=s.byteLength&&i?new DataView(s.buffer,s.byteOffset,e):null},Wf={validateData:Yf,parseInit:()=>null,getIndexRange:()=>{},parseSegments:qf,parseFeedableSegmentChunk:zf};var y;(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.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"})(y||(y={}));var P;(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"})(P||(P={}));const cr={[y.EBML]:{type:P.Master},[y.EBMLVersion]:{type:P.UnsignedInteger},[y.EBMLReadVersion]:{type:P.UnsignedInteger},[y.EBMLMaxIDLength]:{type:P.UnsignedInteger},[y.EBMLMaxSizeLength]:{type:P.UnsignedInteger},[y.DocType]:{type:P.String},[y.DocTypeVersion]:{type:P.UnsignedInteger},[y.DocTypeReadVersion]:{type:P.UnsignedInteger},[y.Void]:{type:P.Binary},[y.Segment]:{type:P.Master},[y.SeekHead]:{type:P.Master},[y.Seek]:{type:P.Master},[y.SeekID]:{type:P.Binary},[y.SeekPosition]:{type:P.UnsignedInteger},[y.Info]:{type:P.Master},[y.TimestampScale]:{type:P.UnsignedInteger},[y.Duration]:{type:P.Float},[y.Tracks]:{type:P.Master},[y.Chapters]:{type:P.Master},[y.Cluster]:{type:P.Master},[y.Timestamp]:{type:P.UnsignedInteger},[y.SilentTracks]:{type:P.Master},[y.SilentTrackNumber]:{type:P.UnsignedInteger},[y.Position]:{type:P.UnsignedInteger},[y.PrevSize]:{type:P.UnsignedInteger},[y.SimpleBlock]:{type:P.Binary},[y.BlockGroup]:{type:P.Master},[y.EncryptedBlock]:{type:P.Binary},[y.Attachments]:{type:P.Master},[y.Tags]:{type:P.Master},[y.Cues]:{type:P.Master},[y.CuePoint]:{type:P.Master},[y.CueTime]:{type:P.UnsignedInteger},[y.CueTrackPositions]:{type:P.Master},[y.CueTrack]:{type:P.UnsignedInteger},[y.CueClusterPosition]:{type:P.UnsignedInteger},[y.CueRelativePosition]:{type:P.UnsignedInteger},[y.CueDuration]:{type:P.UnsignedInteger},[y.CueBlockNumber]:{type:P.UnsignedInteger},[y.CueCodecState]:{type:P.UnsignedInteger},[y.CueReference]:{type:P.Master},[y.CueRefTime]:{type:P.UnsignedInteger}},xn=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=Pi(s,t),a=i in cr,n=a?cr[i].type:P.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=Pi(d),h=u*2**((l-1)*8)+c,f=t+l;let m;return f+h>s.byteLength?m=new DataView(s.buffer,s.byteOffset+f):m=new DataView(s.buffer,s.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:m,valueSize:h}},Pi=(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},Ne=(s,e)=>{switch(e){case P.SignedInteger:return s.getInt8(0);case P.UnsignedInteger:return Pi(s);case P.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case P.String:return new TextDecoder("ascii").decode(s);case P.UTF8:return new TextDecoder("utf-8").decode(s);case P.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case P.Master:return s;case P.Binary:return s;default:r.assertNever(e)}},Yt=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=xn(i);if(!e(a))return;a.type===P.Master&&Yt(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},Qf=s=>{if(s.getUint32(0)!==y.EBML)return!1;let e,t,i;const a=xn(s);return Yt(a.value,({tag:n,type:o,value:l})=>(n===y.EBMLReadVersion?e=Ne(l,o):n===y.DocType?t=Ne(l,o):n===y.DocTypeReadVersion&&(i=Ne(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},On=[y.Info,y.SeekHead,y.Tracks,y.Chapters,y.Cluster,y.Cues,y.Attachments,y.Tags],Jf=[y.Timestamp,y.SilentTracks,y.SilentTrackNumber,y.Position,y.PrevSize,y.SimpleBlock,y.BlockGroup,y.EncryptedBlock],Kf=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u;return Yt(s,({tag:c,type:h,value:f,valueSize:m})=>{if(c===y.SeekID){const b=Ne(f,h);u=Pi(b)}else c!==y.SeekPosition&&(u=void 0);return c===y.Segment?(e=f.byteOffset,t=f.byteOffset+m):c===y.Info?n=!0:c===y.SeekHead?o=!0:c===y.TimestampScale?i=Ne(f,h):c===y.Duration?a=Ne(f,h):c===y.SeekPosition&&u===y.Cues?d=Ne(f,h):n&&o&&On.includes(c)&&(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}},Xf=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},Zf=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return Yt(s,({tag:l,type:d,value:u})=>{switch(l){case y.Cues:t=!0;break;case y.CuePoint:o&&a(o)&&n.push(o),o={};break;case y.CueTime:o&&(o.time=Ne(u,d));break;case y.CueTrackPositions:break;case y.CueClusterPosition:o&&(o.position=Ne(u,d));break;default:t&&On.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:j.NONE,time:{from:u,to:h?h.time:e.segmentDuration},byte:{from:e.segmentStart+c,to:h?e.segmentStart+h.position-1:e.segmentEnd-1}}})},ep=s=>{let e=0,t=!1;try{Yt(s,i=>i.tag===y.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Jf.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[y.SimpleBlock,y.BlockGroup,y.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},tp={validateData:Qf,parseInit:Kf,getIndexRange:Xf,parseSegments:Zf,parseFeedableSegmentChunk:ep};class hr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){switch(this.onLastSegment$=new r.ValueSubject(!1),this.fullyBuffered$=new r.ValueSubject(!1),this.playingRepresentation$=new r.ValueSubject(void 0),this.error$=new r.Subject,this.gaps=[],this.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Ze,this.destroyAbortController=new Ze,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(u){const c=this.representations.get(u);r.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Gf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},b=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:b}))),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(b=>{if(!this.sourceBuffer)return;const p=Math.min(this.bufferLimit,dr(this.sourceBuffer.buffered)*.8);this.bufferLimit=p,this.pruneBuffer(this.getCurrentPosition(),b)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(b=>this.error$.next(b))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id);if(r.assertNonNullable(h,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return;let m=0;for(const b of f)b.time.from-m>0&&this.gaps.push({representation:c.id,from:m,to:b.time.from}),m=b.time.to;r.isNonNullable(c.duration)&&c.duration-m>0&&this.gaps.push({representation:c.id,from:m,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId)}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;this.switchingToRepresentationId=u;const c=this.representations.get(u);r.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(r.isNullable(h)?yield this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();r.isNonNullable(f)&&this.maintain(f)}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=i,i){case St.MP4:this.containerParser=Wf;break;case St.WEBM:this.containerParser=tp;break;default:r.assertNever(i)}this.initData=new Map(a.map(u=>[u.id,null])),this.segments=new Map,this.representations=new Map(a.map(u=>[u.id,u])),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 Ze,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer))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=Xe(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)&&dr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=Xe(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=Re(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===j.FED&&!l.length&&Xe(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Re(i,-1);d&&d.status===j.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}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;this.initData.clear(),this.segments.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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const a=e.findIndex(({status:h,time:{from:f,to:m}},b)=>{const p=f<=i&&m>=i,v=f>i||p||b===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),g=this.preloadOnly&&f<=i+S||m<=i+S;return(h===j.NONE||h===j.PARTIALLY_EJECTED&&v&&g&&this.sourceBuffer&&!Os(this.sourceBuffer.buffered,i))&&v&&g});if(a===-1)return[];if(t!==fe.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 f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===j.NONE||f.status===j.PARTIALLY_EJECTED)d.push(f);else break}return d}async loadSegments(e,t,i="auto"){if(!e.length)return;let a,n,o=e;const{type:l}=t.segmentReference;switch(l){case fe.BYTE_RANGE:{a=t.segmentReference.url,n={from:Re(e,0).byte.from,to:Re(e,-1).byte.to};break}case fe.TEMPLATE:{const u=Re(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=j.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=>{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=Xe((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 f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),h.segment.status=j.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const m of this.representations.values())if(m.id!==t)for(const b of(f=this.segments.get(m.id))!==null&&f!==void 0?f:[])b.status===j.FED&&b.time.from===h.segment.time.from&&b.time.to===h.segment.time.to&&(b.status=j.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,m=u===fe.BYTE_RANGE,b=m?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!m||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const v=m?f.byte.from-i:0,S=m?f.byte.to-i:e.byteLength,g=v<a,A=S<=a;if(f.status===j.DOWNLOADING&&g&&A){f.status=j.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+v,b);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&g&&(h.loadedBytes=Math.min(b,a-v),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+v+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===b?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=j.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=T.byteLength,h.fedBytes===b&&l(h);else{if(h.feedingBytes<b)return;o()}}))}}}abortSegment(e){e.status===j.PARTIALLY_FED||e.status===j.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=j.NONE),e.status=j.PARTIALLY_EJECTED):e.status=j.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);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=ur(()=>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(l=>{if(!l)return;const{dataView:d,segments:u}=l,c=d.buffer.slice(d.byteOffset,d.byteOffset+d.byteLength);this.initData.set(e.id,c),this.segments.set(e.id,u)}).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===j.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===j.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const m of f)if(m.status===j.NONE&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.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===j.FED&&d(h)}return l=isFinite(n)&&isFinite(o),l?this.sourceBufferTaskQueue.remove(n,o):!1}abortBuffer(){if(!this.sourceBuffer||this.mediaSource.readyState!=="open")return;const e=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),t=e instanceof ArrayBuffer?e:void 0;this.sourceBufferTaskQueue.abort(t)}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=ur(()=>{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!==j.FED&&n!==j.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=j.PARTIALLY_EJECTED:a.status=j.NONE)}}}var ft;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(ft||(ft={}));class ip{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 Ze,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=vt(n));const o=yield bt(n,{signal:this.abortAllController.signal}).catch(Lt);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?ft.HEADER:ft.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,m,b;let p=a;const v=new Headers;if(o)switch(n){case ft.HEADER:{v.append("Range",`bytes=${o.from}-${o.to}`);break}case ft.PARAM:{const $=new URL(p,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),p=$.toString();break}default:r.assertNever(n)}this.requestQuic&&(p=vt(p));let S=this.abortAllController.signal;if(u){const $=new Ze;if(this.subscription.add(r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(D){Lt(D)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(D){Lt(D)}S=$.signal}const g=r.now(),A=yield bt(p,{priority:d,headers:v,signal:S}).catch(Lt),E=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-g),!A)return null;if(!A.ok||!A.body)return Promise.reject(new Error(`Fetch error ${A.status}: ${A.statusText}`));this.onHeadersReceived(A.headers);const T=parseInt((f=A.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield A.arrayBuffer();return(m=this.throughputEstimator)===null||m===void 0||m.addRawSpeed($.byteLength,r.now()-E),l==null||l(new DataView($),$.byteLength),$}if(!l&&!c)return A.arrayBuffer();const[w,V]=A.body.tee(),C=w.getReader();c&&((b=this.throughputEstimator)===null||b===void 0||b.trackStream(V));let R=0;const F=new ArrayBuffer(T),I=new Uint8Array(F),_=new DataView(F);let H=!1;const Q=$=>{H=!0,Lt($)},Z=r.abortable(S,async function*({done:$,value:D}){R===0&&this.lastRequestFirstBytes$.next(r.now()-g),!S.aborted&&($?l==null||l(_,R):D&&(I.set(D,R),R+=D.byteLength,l==null||l(_,R),yield C==null?void 0:C.read().then(Z,Q)))}.bind(this));return yield C==null?void 0:C.read().then(Z,Q),H?null:F}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==fe.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,f=!1,m,b;a.indexRange&&(m=a.indexRange.from,b=a.indexRange.to,f=u+1===m,f&&(c=Math.min(m,d),h=Math.max(b,u))),c=Math.min(c,0);const p=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!p)return null;const v=new DataView(p,d-c,u-c+1);if(!n.validateData(v))throw new Error("Invalid media file");const S=n.parseInit(v),g=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!g)throw new ReferenceError("No way to load representation index");let A;if(f)A=new DataView(p,g.from-c,g.to-g.from+1);else{const T=yield this.fetch(a.url,{range:g,priority:o,measureThroughput:!1});if(!T)return null;A=new DataView(T)}const E=n.parseSegments(A,S,g);return{dataView:new DataView(p),segments:E}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==fe.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});return l?{segments:a.segments.map(u=>({...u,status:j.NONE,size:void 0})),dataView:new DataView(l)}:null}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=In(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 fe.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case fe.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 Lt=s=>{if(!(s instanceof DOMException)||!(s.name==="AbortError"||s.code===20))throw s};var sp=tt,ap=_i,rp=Se,np=rp("match"),op=function(s){var e;return sp(s)&&((e=s[np])!==void 0?!!e:ap(s)=="RegExp")},lp=Li,up=String,dp=function(s){if(lp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return up(s)},cp=it,hp=function(){var s=cp(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},fp=Oe,pp=Be,mp=Us,bp=hp,fr=RegExp.prototype,vp=function(s){var e=s.flags;return e===void 0&&!("flags"in fr)&&!pp(s,"flags")&&mp(fr,s)?fp(bp,s):e},ta=xe,Sp=Ni,gp=Math.floor,ds=ta("".charAt),yp=ta("".replace),cs=ta("".slice),Tp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Ep=/\$([$&'`]|\d{1,2})/g,$p=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=Ep;return a!==void 0&&(a=Sp(a),d=Tp),yp(n,d,function(u,c){var h;switch(ds(c,0)){case"$":return"$";case"&":return s;case"`":return cs(e,0,t);case"'":return cs(e,o);case"<":h=a[cs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var m=gp(f/10);return m===0?u:m<=l?i[m-1]===void 0?ds(c,1):i[m-1]+ds(c,1):u}h=i[f-1]}return h===void 0?"":h})},kp=Ci,Ap=Oe,ia=xe,pr=Ms,Pp=me,wp=Ri,_p=op,dt=dp,Rp=Ii,Ip=vp,Np=$p,Dp=Se,Cp=Dp("replace"),Lp=TypeError,Bn=ia("".indexOf),xp=ia("".replace),mr=ia("".slice),Op=Math.max,br=function(s,e,t){return t>s.length?-1:e===""?t:Bn(s,e,t)};kp({target:"String",proto:!0},{replaceAll:function(e,t){var i=pr(this),a,n,o,l,d,u,c,h,f,m=0,b=0,p="";if(!wp(e)){if(a=_p(e),a&&(n=dt(pr(Ip(e))),!~Bn(n,"g")))throw Lp("`.replaceAll` does not allow non-global regexes");if(o=Rp(e,Cp),o)return Ap(o,e,i,t);if(a)return xp(dt(i),e,t)}for(l=dt(i),d=dt(e),u=Pp(t),u||(t=dt(t)),c=d.length,h=Op(1,c),m=br(l,d,0);m!==-1;)f=u?dt(t(d,m,l)):Np(d,l,m,[],void 0,t),p+=mr(l,b,m)+f,b=m+c,m=br(l,d,m+h);return b<l.length&&(p+=mr(l,b)),p}});var Bp=_n,Mp=Bp("String","replaceAll"),Vp=Mp,Fp=Vp,Up=Fp,jp=Up,vr=jp;const Sr=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},hs=(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},Hp=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,f,m,b,p,v,S,g,A,E,T,w,V,C,R,F,I,_,H,Q,Z,$,D,q,X,ee,oe,ge;const U=new DOMParser().parseFromString(s,"application/xml"),ie={video:[],audio:[],text:[]},re=U.children[0],ue=re.getElementsByTagName("Period")[0],ze=ue.children;let ye;const Ue=re.getAttribute("mediaPresentationDuration"),We=ue.getAttribute("duration");if(Ue)ye=Sr(Ue);else if(We){const Te=Sr(We);r.isNonNullable(Te)&&(ye=Te)}let Et=0;const rt=(i=(t=re.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Hn=rt.includes(Ai.WEBM_AS_IN_FFMPEG)||rt.includes(Ai.WEBM_AS_IN_SPEC)?St.WEBM:St.MP4;for(const Te of ze){const qt=Te.getAttribute("mimeType"),Gn=Te.getAttribute("codecs"),sa=(a=Te.getAttribute("contentType"))!==null&&a!==void 0?a:qt==null?void 0:qt.split("/")[0],Yn=(o=(n=Te.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],qn=Te.querySelectorAll("Representation"),zn=Te.querySelector("SegmentTemplate");if(sa!=="text")for(const se of qn){const $t=(l=se.getAttribute("mimeType"))!==null&&l!==void 0?l:qt,aa=(u=(d=se.getAttribute("codecs"))!==null&&d!==void 0?d:Gn)!==null&&u!==void 0?u:"",zt=(h=(c=se.getAttribute("contentType"))!==null&&c!==void 0?c:$t==null?void 0:$t.split("/")[0])!==null&&h!==void 0?h:sa,Wn=(m=(f=Te.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&m!==void 0?m:[],Qn=parseInt((b=se.getAttribute("width"))!==null&&b!==void 0?b:"",10),ra=parseInt((p=se.getAttribute("height"))!==null&&p!==void 0?p:"",10),na=parseInt((v=se.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,oa=(S=se.getAttribute("frameRate"))!==null&&S!==void 0?S:"",Jn=(g=se.getAttribute("quality"))!==null&&g!==void 0?g:void 0,Kn=oa?Zs(oa):void 0,Xn=(A=se.getAttribute("id"))!==null&&A!==void 0?A:(Et++).toString(10),Zn=zt==="video"?`${ra}p`:zt==="audio"?`${na}Kbps`:aa,eo=`${Xn}@${Zn}`,to=(w=(T=(E=se.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",la=new URL(to,e).toString(),io=[...rt,...Yn,...Wn];let Bi;const so=se.querySelector("SegmentBase"),Qe=(V=se.querySelector("SegmentTemplate"))!==null&&V!==void 0?V:zn;if(so){const kt=(R=(C=se.querySelector("SegmentBase Initialization"))===null||C===void 0?void 0:C.getAttribute("range"))!==null&&R!==void 0?R:"",[At,Vi]=kt.split("-").map(Je=>parseInt(Je,10)),Pt={from:At,to:Vi},wt=(F=se.querySelector("SegmentBase"))===null||F===void 0?void 0:F.getAttribute("indexRange"),[Fi,Wt]=wt?wt.split("-").map(Je=>parseInt(Je,10)):[],_t=wt?{from:Fi,to:Wt}:void 0;Bi={type:fe.BYTE_RANGE,url:la,initRange:Pt,indexRange:_t}}else if(Qe){const kt={representationId:(I=se.getAttribute("id"))!==null&&I!==void 0?I:void 0,bandwidth:(_=se.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},At=parseInt((H=Qe.getAttribute("timescale"))!==null&&H!==void 0?H:"",10),Vi=(Q=Qe.getAttribute("initialization"))!==null&&Q!==void 0?Q:"",Pt=Qe.getAttribute("media"),wt=($=parseInt((Z=Qe.getAttribute("startNumber"))!==null&&Z!==void 0?Z:"",10))!==null&&$!==void 0?$:1,Fi=hs(Vi,kt);if(!Pt)throw new ReferenceError("No media attribute in SegmentTemplate");const Wt=(D=Qe.querySelectorAll("SegmentTimeline S"))!==null&&D!==void 0?D:[],_t=[];if(Wt.length){let Je=wt,Ke=0;for(const Rt of Wt){const nt=parseInt((q=Rt.getAttribute("d"))!==null&&q!==void 0?q:"",10)*1e3,It=parseInt((X=Rt.getAttribute("r"))!==null&&X!==void 0?X:"",10)||0,Nt=(oe=parseInt((ee=Rt.getAttribute("t"))!==null&&ee!==void 0?ee:"",10))!==null&&oe!==void 0?oe:void 0;for(let ua=0;ua<It+1;ua++){const ao=hs(Pt,{...kt,segmentNumber:Je.toString(10),segmentTime:Nt.toString(10)}),ro=Nt?Nt/At:Ke;Ke+=nt/At;const no=Ke;Je++,_t.push({time:{from:ro,to:no},url:ao})}}}else if(r.isNonNullable(ye)){const Ke=parseInt((ge=Qe.getAttribute("duration"))!==null&&ge!==void 0?ge:"",10)/At*1e3,Rt=Math.ceil(ye/Ke);let nt=0;for(let It=1;It<Rt;It++){const Nt=hs(Pt,{...kt,segmentNumber:It.toString(10),segmentTime:nt.toString(10)});_t.push({time:{from:nt,to:nt+Ke},url:Nt}),nt+=Ke}}Bi={type:fe.TEMPLATE,baseUrl:la,initUrl:Fi,segments:_t}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!zt||!$t)continue;const Mi={video:he.VIDEO,audio:he.AUDIO,text:he.TEXT}[zt];Mi&&ie[Mi].push({id:eo,kind:Mi,segmentReference:Bi,profiles:io,duration:ye,bitrate:na,mime:$t,codecs:aa,width:Qn,height:ra,fps:Kn,quality:Jn})}}return{duration:ye,container:Hn,representations:ie}},Gp=["timeupdate","progress","play","seeked","stalled","waiting"];var ce;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ce||(ce={}));let Yp=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.state$=new W(ce.NONE),this.currentVideoRepresentation$=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.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Ze,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(ce.MANIFEST_READY);const a=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!a)return;let n;try{n=Hp(a!=null?a:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return;const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest={...n,representations:jt(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(ce.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.state$.startTransitionTo(ce.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};this.videoBufferManager=new hr(he.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new hr(he.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));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.subscription.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.subscription.add(r.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),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(ce.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.jumGap(),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 ip({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(ce.RUNNING),this.subscription.add(r.merge(...Gp.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&&Os(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[he.VIDEO]:this.videoBufferManager,[he.AUDIO]:this.audioBufferManager,[he.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),Os(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(ce.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(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const a of i.gaps)i.playingRepresentation$.getValue()===a.representation&&a.from<=e&&a.to>e&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?t.push(1/0):t.push(a.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const qp=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?Gt(n):void 0)!==null&&o!==void 0?o:st({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},zp=({id:s,bitrate:e})=>({id:s,bitrate:e}),Wp=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=Re(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Re(s,-1)};class Qp{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new Pe,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Sf,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(!this.videoState.getTransition()){if(n.state===N.Requested&&(a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&t!==J.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.setAttribute("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),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.READY&&k(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}}},this.params=e,this.video=Ve(this.params.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(ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Yp({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=Fe(this.video),a=u=>{e.error$.next({id:"DashVKProvider",category:r.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,a));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),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.isAudioAvailable$,e.isAudioAvailable$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once(),r.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(at(this.video,t.isLooped,a)),this.subscription.add(Me(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(Ye(this.video,t.playbackRate,i.playbackRateState$,a)),n($i(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),k(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===ce.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();r.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((p,v)=>v.bitrate-p.bitrate),m=Array.from(h.video).sort((p,v)=>v.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of f){const v=zp(p);v&&this.audioTracks.push({track:v,representation:p})}for(const p of m){const v=qp(p);if(v){this.videoTracks.push({track:v,representation:p});const S=!this.params.tuning.isAudioDisabled&&Wp(f,m,p);S&&this.audioRepresentations.set(p.id,S)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const b=this.selectVideoRepresentation();r.assertNonNullable(b),this.player.initRepresentations(b.id,(c=this.audioRepresentations.get(b.id))===null||c===void 0?void 0:c.id)}else u===ce.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.stateChangeEnded$,this.elementSize$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ce.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(he.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(he.AUDIO,f.id).catch(o)}},a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var c;return u&&((c=this.videoTracks.find(({representation:{id:h}})=>h===u))===null||c===void 0?void 0:c.track)})).subscribe(e.currentVideoTrack$,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.find(({track:{id:S}})=>S===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=Xe(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=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),p=Ht(this.videoTracks.map(({track:S})=>S),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),v=l?p!=null?p:u:u!=null?u:p;return v&&((o=this.videoTracks.find(({track:S})=>S===v))===null||o===void 0?void 0:o.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){qe(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Jp=5e3,we={};var M;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(M||(M={}));const ni=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class Kp{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(M.INITIALIZING),this.textTracksManager=new Pe,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!==M.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===N.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(i)}},this.video=Ve(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(ne(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.video.remove(),this.params.output.element$.next(void 0)}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"),Jp);import("hls.js/dist/hls.min.js").then(a=>{e||(we.Hls=a.default,we.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(we.Hls,"hls.js not loaded"),this.hls=new we.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){r.assertNonNullable(we.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=Fe(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.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(at(this.video,e.isLooped,i)),this.subscription.add(Me(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ye(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(ni(this.hls,we.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(M.PLAYING),k(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),k(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},i)),n(ni(this.hls,we.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var f,m;const b=h.name||h.height.toString(10),{width:p,height:v}=h,S=(m=Gt((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&m!==void 0?m:st({width:p,height:v});if(!S)return c;const g=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,A={id:b.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:p,height:v},fps:g};return this.trackLevels.set(b,{track:A,level:h}),c.push(A),c},[]))),t.availableVideoTracks$),n(ni(this.hls,we.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>ne(u))),t.hostname$),this.subscription.add(ke(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=ni(this.hls,we.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(ke(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 f=this.hls.levels.indexOf(h),m=this.hls.currentLevel,b=this.hls.levels[m];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{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(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await qe(this.video)||(this.videoState.setState(M.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.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.setAttribute("src",""),this.video.load(),this.videoState.setState(M.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const gr="X-Playback-Duration";var yr=async s=>{const e=await bt(s,{method:"HEAD"});return e.headers.has(gr)?parseInt(e.headers.get(gr),10):void 0};const Xp=s=>{let e=null;if(s.QUALITY&&(e=Gt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=st({width:t,height:i})}return e!=null?e:null},Mn=async(s,e=s)=>{var t;const n=(await(await bt(s)).text()).split(`
|
|
8
|
-
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=jt(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Xp(c);let m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[S,g]=c.RESOLUTION.split("x").map(A=>parseInt(A,10));S&&g&&(p={width:S,height:g})}const v=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:v,bandwidth:m,size:p,fps:b})}return o};var G;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(G||(G={}));class Zp{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new W(G.STOPPED),this.textTracksManager=new Pe,this.manifests$=new r.ValueSubject([]),this.liveOffset=new Xs,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{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!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.video.setAttribute("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(G.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(G.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===N.Requested){this.videoState.startTransitionTo(G.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case G.READY:n===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.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())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case G.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),Mn(mt(this.params.source.url),this.params.source.url).then(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.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(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)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=Fe(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.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 f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===G.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===N.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:f})=>({id:d,quality:u,size:c,fps:f,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$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=mt(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),yr(t).then(i=>{var a;if(!r.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(r.isNullable(n)||!isFinite(n))try{bt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();yr(u).then(c=>{r.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){qe(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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 z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class em{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(z.STOPPED),this.textTracksManager=new Pe,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===exports.PlaybackState.STOPPED){i!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.setAttribute("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),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(i===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===N.Requested&&this.seek(u.position),i){case z.READY:a===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(i)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),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(ne(this.params.source.url)),Mn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},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)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=Fe(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(at(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(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),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),k(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).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 f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===N.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:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.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.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();r.isNullable(e)||(this.video.setAttribute("src",e.url),this.video.load())}playIfAllowed(){qe(this.video).then(e=>{e||(this.videoState.setState(z.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));class tm{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(K.STOPPED),this.trackUrls={},this.textTracksManager=new Pe,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!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===N.None&&this.params.desiredState.seekState.setState({state:N.Requested,position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&l.state===N.Requested&&this.seek(l.position),t){case K.READY:i===exports.PlaybackState.READY?k(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.video=Ve(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).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.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=Fe(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(at(this.video,t.isLooped,i)),this.subscription.add(Me(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(Ye(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),k(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),k(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.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()===K.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,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.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const i=(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();r.assertNonNullable(i,"MpegProvider: track is not selected");let{url:a}=this.trackUrls[i];r.assertNonNullable(a,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(a=vt(a)),this.video.setAttribute("src",a),this.video.load(),this.params.output.hostname$.next(ne(a))}playIfAllowed(){qe(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Tr=["stun:videostun.mycdn.me:80"],im=1e3,sm=3,fs=()=>null;class am{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=fs,this.externalStopCallback=fs,this.externalErrorCallback=fs,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:Tr}]};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),im)}normalizeOptions(e={}){const t={stunServerList:Tr,maxRetryNumber:sm,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));class rm{constructor(e){this.videoState=new W(Y.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!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),k(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case Y.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&k(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=Ve(e.container),this.liveStreamClient=new am(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}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=Fe(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$),n(a.isAudioAvailable$,e.isAudioAvailable$),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)===Y.READY&&this.videoState.setState(Y.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Me(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Y.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Y.READY:break;case Y.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Y.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.hostname$.next(ne(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:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,k(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Y.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(){qe(this.video).then(e=>{e||(this.videoState.setState(Y.PAUSED),k(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class Er{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 Boolean(this.current.done)}}var nm=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},ps,ms,bs,vs,Ss,gs,oi,ys,li,Ts,ui,Es,di,$s,ci,ks;const Vn=nm(),je=document.createElement("video"),_e={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&((ms=(ps=window.SourceBuffer)===null||ps===void 0?void 0:ps.prototype)===null||ms===void 0?void 0:ms.appendBuffer)),hls:Boolean(((bs=je.canPlayType)===null||bs===void 0?void 0:bs.call(je,"application/x-mpegurl"))||((vs=je.canPlayType)===null||vs===void 0?void 0:vs.call(je,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},de={mp4:Boolean((Ss=je.canPlayType)===null||Ss===void 0?void 0:Ss.call(je,"video/mp4")),webm:Boolean((gs=je.canPlayType)===null||gs===void 0?void 0:gs.call(je,"video/webm")),cmaf:!0},He={h264:Boolean((ys=(oi=window.MediaSource)===null||oi===void 0?void 0:oi.isTypeSupported)===null||ys===void 0?void 0:ys.call(oi,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Ts=(li=window.MediaSource)===null||li===void 0?void 0:li.isTypeSupported)===null||Ts===void 0?void 0:Ts.call(li,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Es=(ui=window.MediaSource)===null||ui===void 0?void 0:ui.isTypeSupported)===null||Es===void 0?void 0:Es.call(ui,'video/webm; codecs="vp9"')),aac:Boolean(($s=(di=window.MediaSource)===null||di===void 0?void 0:di.isTypeSupported)===null||$s===void 0?void 0:$s.call(di,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((ks=(ci=window.MediaSource)===null||ci===void 0?void 0:ci.isTypeSupported)===null||ks===void 0?void 0:ks.call(ci,'audio/webm; codecs="opus"'))},ct=(He.h264||He.h265)&&He.aac,Oi=_e.hls&&de.mp4,om=Boolean(window.WebSocket),lm=()=>Object.keys(He).filter(s=>He[s]),um=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return _e.mse&&de.mp4&&ct;case exports.VideoFormat.DASH_SEP:return _e.mse&&de.mp4&&ct;case exports.VideoFormat.DASH_WEBM:return _e.mse&&de.webm&&He.vp9&&He.opus;case exports.VideoFormat.DASH_LIVE:return _e.mse&&de.mp4&&ct;case exports.VideoFormat.DASH_LIVE_CMAF:return _e.mse&&de.mp4&&ct&&de.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return _e.mse&&de.mp4&&ct;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Oi||e&&_e.mse&&de.mp4&&ct;case exports.VideoFormat.MPEG:return de.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return _e.webrtc&&om&&He.h264&&(de.mp4||de.webm);default:return r.assertNever(t)}}),dm=()=>Vn?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Oi?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],cm=()=>Vn?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Oi?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],$r=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var hm=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$,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="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const kr={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},fm={cacheDuration:12e4},pm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},mm={maxPausedTime:3e4},Ar={maxPausedTime:3e4};class bm{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),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$: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),liveTime$: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),element$:new r.ValueSubject(void 0)},this.subscription=new r.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog("ProviderContainer");const t=um([...cm(),...dm()],this.params.tuning.useHlsJs).filter(o=>r.isNonNullable(e.sources[o])),{formatsToAvoid:i}=this.params.tuning,a=i.length?[...t.filter(o=>!i.includes(o)),...t.filter(o=>i.includes(o))]:t;this.screenFormatsIterator=new Er(a);const n=[...$r(!0),...$r(!1)];this.chromecastFormatsIterator=new Er(n.filter(o=>r.isNonNullable(e.sources[o])))}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.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;r.assertNonNullable(e,"No current provider"),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!==N.None;this.params.desiredState.seekState.setState({state:N.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.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 Uf({...o,source:l,config:fm})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new or({...o,source:l,format:e,config:Ar}):new Qp({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new or({...o,source:l,format:e,config:Ar})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Oi||!this.params.tuning.useHlsJs?new em({...o,source:l}):new Kp({...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 Zp({...o,source:l,config:mm})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new tm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Of({...o,source:l,config:pm})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new rm({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 jh({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()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case le.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 jt(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$,hm({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:kr.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(r.filter(({type:a})=>a!==void 0))}).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=>{if(this.current$.getValue().destination===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=a.category===r.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<kr.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var pe;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(pe||(pe={}));const Fn=new Map;let et=pe.RUNTIME;const As=`vk-videoplayer-dummy-key-${Math.random()}`,vm=()=>{try{localStorage.setItem(As,"test"),localStorage.removeItem(As),et=pe.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(As),et=pe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)et=pe.RUNTIME;else throw e}else throw s}};vm();const Sm=s=>{var e,t;switch(et){case pe.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case pe.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case pe.RUNTIME:return Fn.get(s);default:r.assertNever(et)}},Pr=(s,e)=>{switch(et){case pe.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.RUNTIME:return void Fn.set(s,e);default:r.assertNever(et)}},Bs=(s,e,t)=>t*e+(1-t)*s,Un=(s,e)=>s.reduce((t,i)=>t+i,0)/e,gm=(s,e,t,i)=>{let a=0,n=t;const o=Un(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 jn{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 $e(`raw_${i}`),this.smoothedSeries$=new $e(`smoothed_${i}`),this.reportedSeries$=new $e(`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 ym extends jn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Bs(this.slow,e,this.params.emaAlphaSlow),this.fast=Bs(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class Tm extends jn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Un(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Bs(this.emaSmoothed,e,this.params.emaAlpha);const i=gm(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 ym({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new Tm({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const Em=5e3,_r="one_video_throughput",Rr="one_video_rtt",Ce=window.navigator.connection,Ir=()=>{const s=Ce==null?void 0:Ce.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},Nr=()=>{const s=Ce==null?void 0:Ce.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Dr=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class Bt{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=Bt.load(_r)||(e.useBrowserEstimation?Ir():void 0)||Em,n=(i=(t=Bt.load(Rr))!==null&&t!==void 0?t:e.useBrowserEstimation?Nr():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(Dr(a,n,e.rttPenaltyRequestSize)),this.throughput=wr.getSmoothedValue(a,-1,e),this.rtt=wr.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Ir();d&&this.throughput.next(d);const u=Nr();r.isNonNullable(u)&&this.rtt.next(u)};Ce&&"onchange"in Ce&&this.subscription.add(r.fromEvent(Ce,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{Pr(_r,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{Pr(Rr,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})=>Dr(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(Bt.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=Sm(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Cr={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},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},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},$m=s=>{const e={};for(const t of Object.keys(Cr)){const i=Cr[t],a=s[t];Array.isArray(i)&&Array.isArray(a)?e[t]=a:typeof i=="object"&&typeof a=="object"?e[t]={...i,...a}:e[t]=a!=null?a:i}return e};var km=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===N.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===N.None))),Am=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const Lr=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:a})=>new r.Observable(n=>{let o;const l=s.transitionEnded$.pipe(r.filter(m=>(m.from===exports.PlaybackState.PAUSED||m.from===exports.PlaybackState.STOPPED)&&m.to===exports.PlaybackState.PLAYING)),d=s.stateChangeEnded$.pipe(r.filter(m=>m.from===exports.PlaybackState.PLAYING&&m.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(r.filter(({to:m})=>{var b,p;return m.state===N.Requested&&((p=(b=s.getTransition())===null||b===void 0?void 0:b.from)!==null&&p!==void 0?p:s.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(r.filter(({from:m,to:b})=>{var p,v;return m.state===N.Applying&&b.state===N.None&&((v=(p=s.getTransition())===null||p===void 0?void 0:p.from)!==null&&v!==void 0?v:s.getState())===exports.PlaybackState.PLAYING})),h=r.merge(l,c).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable)),f=r.merge(r.merge(d,u,t),i).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable));return new r.Subscription().add(h.subscribe(m=>{o=m})).add(f.subscribe(m=>{if(r.isNullable(o)||o===m)return;const b={from:o,to:m};o=void 0,n.next(b)}))});class Pm{constructor(e={}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new W(exports.PlaybackState.STOPPED),seekState:new W({state:N.None}),volume:new W({volume:1,muted:!1}),videoTrack:new W(void 0),autoVideoTrackSwitching:new W(!0),autoVideoTrackLimits:new W({}),isLooped:new W(!1),playbackRate:new W(1),externalTextTracks:new W([]),currentTextTrack:new W(void 0),textTrackCuesSettings:new W({})},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),liveTime$: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),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0)},this.events={inited$:new r.Subject,started$:new r.Subject,willPause$:new r.Subject,willResume$: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),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:mf},this.initLogs(),this.tuning=$m(e),this.chromecastInitializer=new So({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bt(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,(f,m)=>{const b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),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=Am(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new bm({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},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(),(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=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),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){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:N.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.setState(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;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.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()}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===N.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}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$.pipe(r.filter(()=>!this.isPlaybackStarted),r.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===N.Requested?this.desiredState.seekState.setState({...d,state:N.Applying}):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===N.Applying&&(this.desiredState.seekState.setState({state:N.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(d=>d.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(d=>d.map(({quality:u})=>u).sort((u,c)=>Ti(u)?1:Ti(c)?-1:mi(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.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.currentBuffer$.pipe(r.map(d=>d?{start:d.from,end:d.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.volume),r.filterChanged()).subscribe(this.info.volume$)).add(km({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(d=>({id:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:"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(()=>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$));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:d})=>d===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 d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return d&&!u}),r.filterChanged());this.subscription.add(n.subscribe(d=>{d?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))}));const o=new r.Subscription;this.subscription.add(o);const l=r.merge(r.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(r.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(r.filterChanged()).subscribe(d=>{switch(r.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new r.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(Lr({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(r.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(Lr({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(r.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{var u,c;const h=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=d==null?void 0:d.size)===null||u===void 0?void 0:u.width,height:(c=d==null?void 0:d.size)===null||c===void 0?void 0:c.height},{width:h==null?void 0:h.videoWidth,height:h==null?void 0:h.videoHeight})}))}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=Ht(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})),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),pf(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>ff(i)),this.providerContainer.current$.subscribe(({type:i})=>si("provider",i)),t.duration$.subscribe(i=>si("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>si("tracks",i)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),t.position$.subscribe(new $e("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),t.isBuffering$.subscribe(new $e("isBuffering"))].forEach(i=>this.subscription.add(i)),si("codecs",lm())}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=>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.transitionEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const wm=`${bo}@${mo}`;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}});exports.Player=Pm;exports.SDK_VERSION=wm;
|
|
6
|
+
"use strict";var bo=Object.create;var Sa=Object.defineProperty;var vo=Object.getOwnPropertyDescriptor;var So=Object.getOwnPropertyNames;var go=Object.getPrototypeOf,yo=Object.prototype.hasOwnProperty;var To=(s,e,t,i)=>{if(e&&typeof e=="object"||typeof e=="function")for(let a of So(e))!yo.call(s,a)&&a!==t&&Sa(s,a,{get:()=>e[a],enumerable:!(i=vo(e,a))||i.enumerable});return s};var ga=(s,e,t)=>(t=s!=null?bo(go(s)):{},To(e||!s||!s.__esModule?Sa(t,"default",{value:s,enumerable:!0}):t,s));var r=require("@vkontakte/videoplayer-shared/es2018.cjs.js"),Eo=require("lodash/debounce.js");const $o="2.0.83-dev.65744ed.0",Ao="es2018.cjs.js";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_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 le;(function(s){s.SCREEN="SCREEN",s.CHROMECAST="CHROMECAST"})(le||(le={}));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 I;(function(s){s.None="none",s.Requested="requested",s.Applying="applying"})(I||(I={}));var ko=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 Po{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=Boolean(window.__onGCastApiAvailable);a?this.initializeCastApi():(window.__onGCastApiAvailable=o=>{delete window.__onGCastApiAvailable,o&&this.initializeCastApi()},n||ko("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(wo),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 wo=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 ya=typeof globalThis!="undefined"?globalThis:typeof window!="undefined"?window:typeof global!="undefined"?global:typeof self!="undefined"?self:{},Le=function(s){try{return!!s()}catch(e){return!0}},_o=Le,xi=!_o(function(){var s=function(){}.bind();return typeof s!="function"||s.hasOwnProperty("prototype")}),Gr=xi,Yr=Function.prototype,xs=Yr.call,Ro=Gr&&Yr.bind.bind(xs,xs),Oe=Gr?Ro:function(s){return function(){return xs.apply(s,arguments)}},qr=Oe,Do=qr({}.toString),Io=qr("".slice),Li=function(s){return Io(Do(s),8,-1)},No=Oe,Co=Le,xo=Li,Qi=Object,Lo=No("".split),Oo=Co(function(){return!Qi("z").propertyIsEnumerable(0)})?function(s){return xo(s)=="String"?Lo(s,""):Qi(s)}:Qi,Oi=function(s){return s==null},Bo=Oi,Mo=TypeError,qs=function(s){if(Bo(s))throw Mo("Can't call method on "+s);return s},Vo=Oo,Fo=qs,Yt=function(s){return Vo(Fo(s))},Uo=function(){},$t={},ti=function(s){return s&&s.Math==Math&&s},Pe=ti(typeof globalThis=="object"&&globalThis)||ti(typeof window=="object"&&window)||ti(typeof self=="object"&&self)||ti(typeof ya=="object"&&ya)||function(){return this}()||Function("return this")(),Ls=typeof document=="object"&&document.all,Ho=typeof Ls=="undefined"&&Ls!==void 0,zr={all:Ls,IS_HTMLDDA:Ho},Wr=zr,jo=Wr.all,me=Wr.IS_HTMLDDA?function(s){return typeof s=="function"||s===jo}:function(s){return typeof s=="function"},Go=Pe,Yo=me,Ta=Go.WeakMap,qo=Yo(Ta)&&/native code/.test(String(Ta)),Ea=me,Qr=zr,zo=Qr.all,st=Qr.IS_HTMLDDA?function(s){return typeof s=="object"?s!==null:Ea(s)||s===zo}:function(s){return typeof s=="object"?s!==null:Ea(s)},Wo=Le,Ye=!Wo(function(){return Object.defineProperty({},1,{get:function(){return 7}})[1]!=7}),At={},Qo=Pe,$a=st,Os=Qo.document,Jo=$a(Os)&&$a(Os.createElement),Jr=function(s){return Jo?Os.createElement(s):{}},Ko=Ye,Xo=Le,Zo=Jr,Kr=!Ko&&!Xo(function(){return Object.defineProperty(Zo("div"),"a",{get:function(){return 7}}).a!=7}),el=Ye,tl=Le,Xr=el&&tl(function(){return Object.defineProperty(function(){},"prototype",{value:42,writable:!1}).prototype!=42}),il=st,sl=String,al=TypeError,at=function(s){if(il(s))return s;throw al(sl(s)+" is not an object")},rl=xi,ii=Function.prototype.call,Be=rl?ii.bind(ii):function(){return ii.apply(ii,arguments)},zs={},Ji=zs,Ki=Pe,nl=me,Aa=function(s){return nl(s)?s:void 0},Ws=function(s,e){return arguments.length<2?Aa(Ji[s])||Aa(Ki[s]):Ji[s]&&Ji[s][e]||Ki[s]&&Ki[s][e]},ol=Oe,Qs=ol({}.isPrototypeOf),ll=typeof navigator!="undefined"&&String(navigator.userAgent)||"",Zr=Pe,Xi=ll,ka=Zr.process,Pa=Zr.Deno,wa=ka&&ka.versions||Pa&&Pa.version,_a=wa&&wa.v8,be,$i;_a&&(be=_a.split("."),$i=be[0]>0&&be[0]<4?1:+(be[0]+be[1]));!$i&&Xi&&(be=Xi.match(/Edge\/(\d+)/),(!be||be[1]>=74)&&(be=Xi.match(/Chrome\/(\d+)/),be&&($i=+be[1])));var ul=$i,Ra=ul,dl=Le,en=!!Object.getOwnPropertySymbols&&!dl(function(){var s=Symbol();return!String(s)||!(Object(s)instanceof Symbol)||!Symbol.sham&&Ra&&Ra<41}),cl=en,tn=cl&&!Symbol.sham&&typeof Symbol.iterator=="symbol",hl=Ws,fl=me,pl=Qs,ml=tn,bl=Object,sn=ml?function(s){return typeof s=="symbol"}:function(s){var e=hl("Symbol");return fl(e)&&pl(e.prototype,bl(s))},vl=String,Js=function(s){try{return vl(s)}catch(e){return"Object"}},Sl=me,gl=Js,yl=TypeError,Ks=function(s){if(Sl(s))return s;throw yl(gl(s)+" is not a function")},Tl=Ks,El=Oi,Bi=function(s,e){var t=s[e];return El(t)?void 0:Tl(t)},Zi=Be,es=me,ts=st,$l=TypeError,Al=function(s,e){var t,i;if(e==="string"&&es(t=s.toString)&&!ts(i=Zi(t,s))||es(t=s.valueOf)&&!ts(i=Zi(t,s))||e!=="string"&&es(t=s.toString)&&!ts(i=Zi(t,s)))return i;throw $l("Can't convert object to primitive value")},Ai={},kl={get exports(){return Ai},set exports(s){Ai=s}},Pl=!0,Da=Pe,wl=Object.defineProperty,_l=function(s,e){try{wl(Da,s,{value:e,configurable:!0,writable:!0})}catch(t){Da[s]=e}return e},Rl=Pe,Dl=_l,Ia="__core-js_shared__",Il=Rl[Ia]||Dl(Ia,{}),an=Il,Na=an;(kl.exports=function(s,e){return Na[s]||(Na[s]=e!==void 0?e:{})})("versions",[]).push({version:"3.27.2",mode:"pure",copyright:"\xA9 2014-2023 Denis Pushkarev (zloirock.ru)",license:"https://github.com/zloirock/core-js/blob/v3.27.2/LICENSE",source:"https://github.com/zloirock/core-js"});var Nl=qs,Cl=Object,Mi=function(s){return Cl(Nl(s))},xl=Oe,Ll=Mi,Ol=xl({}.hasOwnProperty),Me=Object.hasOwn||function(e,t){return Ol(Ll(e),t)},Bl=Oe,Ml=0,Vl=Math.random(),Fl=Bl(1 .toString),rn=function(s){return"Symbol("+(s===void 0?"":s)+")_"+Fl(++Ml+Vl,36)},Ul=Pe,Hl=Ai,Ca=Me,jl=rn,Gl=en,Yl=tn,mt=Ul.Symbol,is=Hl("wks"),ql=Yl?mt.for||mt:mt&&mt.withoutSetter||jl,Se=function(s){return Ca(is,s)||(is[s]=Gl&&Ca(mt,s)?mt[s]:ql("Symbol."+s)),is[s]},zl=Be,xa=st,La=sn,Wl=Bi,Ql=Al,Jl=Se,Kl=TypeError,Xl=Jl("toPrimitive"),Zl=function(s,e){if(!xa(s)||La(s))return s;var t=Wl(s,Xl),i;if(t){if(e===void 0&&(e="default"),i=zl(t,s,e),!xa(i)||La(i))return i;throw Kl("Can't convert object to primitive value")}return e===void 0&&(e="number"),Ql(s,e)},eu=Zl,tu=sn,Xs=function(s){var e=eu(s,"string");return tu(e)?e:e+""},iu=Ye,su=Kr,au=Xr,si=at,Oa=Xs,ru=TypeError,ss=Object.defineProperty,nu=Object.getOwnPropertyDescriptor,as="enumerable",rs="configurable",ns="writable";At.f=iu?au?function(e,t,i){if(si(e),t=Oa(t),si(i),typeof e=="function"&&t==="prototype"&&"value"in i&&ns in i&&!i[ns]){var a=nu(e,t);a&&a[ns]&&(e[t]=i.value,i={configurable:rs in i?i[rs]:a[rs],enumerable:as in i?i[as]:a[as],writable:!1})}return ss(e,t,i)}:ss:function(e,t,i){if(si(e),t=Oa(t),si(i),su)try{return ss(e,t,i)}catch(a){}if("get"in i||"set"in i)throw ru("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}},ou=Ye,lu=At,uu=Vi,qt=ou?function(s,e,t){return lu.f(s,e,uu(1,t))}:function(s,e,t){return s[e]=t,s},du=Ai,cu=rn,Ba=du("keys"),Zs=function(s){return Ba[s]||(Ba[s]=cu(s))},ea={},hu=qo,nn=Pe,fu=st,pu=qt,os=Me,ls=an,mu=Zs,bu=ea,Ma="Object already initialized",Bs=nn.TypeError,vu=nn.WeakMap,ki,Gt,Pi,Su=function(s){return Pi(s)?Gt(s):ki(s,{})},gu=function(s){return function(e){var t;if(!fu(e)||(t=Gt(e)).type!==s)throw Bs("Incompatible receiver, "+s+" required");return t}};if(hu||ls.state){var Ee=ls.state||(ls.state=new vu);Ee.get=Ee.get,Ee.has=Ee.has,Ee.set=Ee.set,ki=function(s,e){if(Ee.has(s))throw Bs(Ma);return e.facade=s,Ee.set(s,e),e},Gt=function(s){return Ee.get(s)||{}},Pi=function(s){return Ee.has(s)}}else{var ut=mu("state");bu[ut]=!0,ki=function(s,e){if(os(s,ut))throw Bs(Ma);return e.facade=s,pu(s,ut,e),e},Gt=function(s){return os(s,ut)?s[ut]:{}},Pi=function(s){return os(s,ut)}}var yu={set:ki,get:Gt,has:Pi,enforce:Su,getterFor:gu},Tu=xi,on=Function.prototype,Va=on.apply,Fa=on.call,Eu=typeof Reflect=="object"&&Reflect.apply||(Tu?Fa.bind(Va):function(){return Fa.apply(Va,arguments)}),$u=Li,Au=Oe,ln=function(s){if($u(s)==="Function")return Au(s)},un={},dn={},cn={}.propertyIsEnumerable,hn=Object.getOwnPropertyDescriptor,ku=hn&&!cn.call({1:2},1);dn.f=ku?function(e){var t=hn(this,e);return!!t&&t.enumerable}:cn;var Pu=Ye,wu=Be,_u=dn,Ru=Vi,Du=Yt,Iu=Xs,Nu=Me,Cu=Kr,Ua=Object.getOwnPropertyDescriptor;un.f=Pu?Ua:function(e,t){if(e=Du(e),t=Iu(t),Cu)try{return Ua(e,t)}catch(i){}if(Nu(e,t))return Ru(!wu(_u.f,e,t),e[t])};var xu=Le,Lu=me,Ou=/#|\.prototype\./,zt=function(s,e){var t=Mu[Bu(s)];return t==Fu?!0:t==Vu?!1:Lu(e)?xu(e):!!e},Bu=zt.normalize=function(s){return String(s).replace(Ou,".").toLowerCase()},Mu=zt.data={},Vu=zt.NATIVE="N",Fu=zt.POLYFILL="P",Uu=zt,Ha=ln,Hu=Ks,ju=xi,Gu=Ha(Ha.bind),fn=function(s,e){return Hu(s),e===void 0?s:ju?Gu(s,e):function(){return s.apply(e,arguments)}},ai=Pe,Yu=Eu,qu=ln,zu=me,Wu=un.f,Qu=Uu,dt=zs,Ju=fn,ct=qt,ja=Me,Ku=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 Yu(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?ai:a?ai[t]:(ai[t]||{}).prototype,l=i?dt:dt[t]||ct(dt,t,{})[t],d=l.prototype,u,c,h,f,m,b,p,v,S;for(f in e)u=Qu(i?f:t+(a?".":"#")+f,s.forced),c=!u&&o&&ja(o,f),b=l[f],c&&(s.dontCallGetSet?(S=Wu(o,f),p=S&&S.value):p=o[f]),m=c&&p?p:e[f],!(c&&typeof b==typeof m)&&(s.bind&&c?v=Ju(m,ai):s.wrap&&c?v=Ku(m):n&&zu(m)?v=qu(m):v=m,(s.sham||m&&m.sham||b&&b.sham)&&ct(v,"sham",!0),ct(l,f,v),n&&(h=t+"Prototype",ja(dt,h)||ct(dt,h,{}),ct(dt[h],f,m),s.real&&d&&(u||!d[f])&&ct(d,f,m)))},Ms=Ye,Xu=Me,pn=Function.prototype,Zu=Ms&&Object.getOwnPropertyDescriptor,ta=Xu(pn,"name"),ed=ta&&function(){}.name==="something",td=ta&&(!Ms||Ms&&Zu(pn,"name").configurable),id={EXISTS:ta,PROPER:ed,CONFIGURABLE:td},mn={},sd=Math.ceil,ad=Math.floor,rd=Math.trunc||function(e){var t=+e;return(t>0?ad:sd)(t)},nd=rd,ia=function(s){var e=+s;return e!==e||e===0?0:nd(e)},od=ia,ld=Math.max,ud=Math.min,dd=function(s,e){var t=od(s);return t<0?ld(t+e,0):ud(t,e)},cd=ia,hd=Math.min,fd=function(s){return s>0?hd(cd(s),9007199254740991):0},pd=fd,sa=function(s){return pd(s.length)},md=Yt,bd=dd,vd=sa,Ga=function(s){return function(e,t,i){var a=md(e),n=vd(a),o=bd(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}},Sd={includes:Ga(!0),indexOf:Ga(!1)},gd=Oe,us=Me,yd=Yt,Td=Sd.indexOf,Ed=ea,Ya=gd([].push),$d=function(s,e){var t=yd(s),i=0,a=[],n;for(n in t)!us(Ed,n)&&us(t,n)&&Ya(a,n);for(;e.length>i;)us(t,n=e[i++])&&(~Td(a,n)||Ya(a,n));return a},bn=["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf"],Ad=$d,kd=bn,Pd=Object.keys||function(e){return Ad(e,kd)},wd=Ye,_d=Xr,Rd=At,Dd=at,Id=Yt,Nd=Pd;mn.f=wd&&!_d?Object.defineProperties:function(e,t){Dd(e);for(var i=Id(t),a=Nd(t),n=a.length,o=0,l;n>o;)Rd.f(e,l=a[o++],i[l]);return e};var Cd=Ws,xd=Cd("document","documentElement"),Ld=at,Od=mn,qa=bn,Bd=ea,Md=xd,Vd=Jr,Fd=Zs,za=">",Wa="<",Vs="prototype",Fs="script",vn=Fd("IE_PROTO"),ds=function(){},Sn=function(s){return Wa+Fs+za+s+Wa+"/"+Fs+za},Qa=function(s){s.write(Sn("")),s.close();var e=s.parentWindow.Object;return s=null,e},Ud=function(){var s=Vd("iframe"),e="java"+Fs+":",t;return s.style.display="none",Md.appendChild(s),s.src=String(e),t=s.contentWindow.document,t.open(),t.write(Sn("document.F=Object")),t.close(),t.F},ri,Si=function(){try{ri=new ActiveXObject("htmlfile")}catch(e){}Si=typeof document!="undefined"?document.domain&&ri?Qa(ri):Ud():Qa(ri);for(var s=qa.length;s--;)delete Si[Vs][qa[s]];return Si()};Bd[vn]=!0;var gn=Object.create||function(e,t){var i;return e!==null?(ds[Vs]=Ld(e),i=new ds,ds[Vs]=null,i[vn]=e):i=Si(),t===void 0?i:Od.f(i,t)},Hd=Le,jd=!Hd(function(){function s(){}return s.prototype.constructor=null,Object.getPrototypeOf(new s)!==s.prototype}),Gd=Me,Yd=me,qd=Mi,zd=Zs,Wd=jd,Ja=zd("IE_PROTO"),Us=Object,Qd=Us.prototype,yn=Wd?Us.getPrototypeOf:function(s){var e=qd(s);if(Gd(e,Ja))return e[Ja];var t=e.constructor;return Yd(t)&&e instanceof t?t.prototype:e instanceof Us?Qd:null},Jd=qt,Tn=function(s,e,t,i){return i&&i.enumerable?s[e]=t:Jd(s,e,t),s},Kd=Le,Xd=me,Zd=st,ec=gn,Ka=yn,tc=Tn,ic=Se,Hs=ic("iterator"),En=!1,Ce,cs,hs;[].keys&&(hs=[].keys(),"next"in hs?(cs=Ka(Ka(hs)),cs!==Object.prototype&&(Ce=cs)):En=!0);var sc=!Zd(Ce)||Kd(function(){var s={};return Ce[Hs].call(s)!==s});sc?Ce={}:Ce=ec(Ce);Xd(Ce[Hs])||tc(Ce,Hs,function(){return this});var $n={IteratorPrototype:Ce,BUGGY_SAFARI_ITERATORS:En},ac=Se,rc=ac("toStringTag"),An={};An[rc]="z";var aa=String(An)==="[object z]",nc=aa,oc=me,gi=Li,lc=Se,uc=lc("toStringTag"),dc=Object,cc=gi(function(){return arguments}())=="Arguments",hc=function(s,e){try{return s[e]}catch(t){}},Ui=nc?gi:function(s){var e,t,i;return s===void 0?"Undefined":s===null?"Null":typeof(t=hc(e=dc(s),uc))=="string"?t:cc?gi(e):(i=gi(e))=="Object"&&oc(e.callee)?"Arguments":i},fc=aa,pc=Ui,mc=fc?{}.toString:function(){return"[object "+pc(this)+"]"},bc=aa,vc=At.f,Sc=qt,gc=Me,yc=mc,Tc=Se,Xa=Tc("toStringTag"),kn=function(s,e,t,i){if(s){var a=t?s:s.prototype;gc(a,Xa)||vc(a,Xa,{configurable:!0,value:e}),i&&!bc&&Sc(a,"toString",yc)}},Ec=$n.IteratorPrototype,$c=gn,Ac=Vi,kc=kn,Pc=$t,wc=function(){return this},_c=function(s,e,t,i){var a=e+" Iterator";return s.prototype=$c(Ec,{next:Ac(+!i,t)}),kc(s,a,!1,!0),Pc[a]=wc,s},Rc=Fi,Dc=Be,Pn=id,Ic=_c,Nc=yn,Cc=kn,Za=Tn,xc=Se,er=$t,wn=$n,Lc=Pn.PROPER;Pn.CONFIGURABLE;wn.IteratorPrototype;var ni=wn.BUGGY_SAFARI_ITERATORS,fs=xc("iterator"),tr="keys",oi="values",ir="entries",Oc=function(){return this},Bc=function(s,e,t,i,a,n,o){Ic(t,e,i);var l=function(S){if(S===a&&f)return f;if(!ni&&S in c)return c[S];switch(S){case tr:return function(){return new t(this,S)};case oi:return function(){return new t(this,S)};case ir:return function(){return new t(this,S)}}return function(){return new t(this)}},d=e+" Iterator",u=!1,c=s.prototype,h=c[fs]||c["@@iterator"]||a&&c[a],f=!ni&&h||l(a),m=e=="Array"&&c.entries||h,b,p,v;if(m&&(b=Nc(m.call(new s)),b!==Object.prototype&&b.next&&(Cc(b,d,!0,!0),er[d]=Oc)),Lc&&a==oi&&h&&h.name!==oi&&(u=!0,f=function(){return Dc(h,this)}),a)if(p={values:l(oi),keys:n?f:l(tr),entries:l(ir)},o)for(v in p)(ni||u||!(v in c))&&Za(c,v,p[v]);else Rc({target:e,proto:!0,forced:ni||u},p);return o&&c[fs]!==f&&Za(c,fs,f,{name:a}),er[e]=f,p},Mc=function(s,e){return{value:s,done:e}},Vc=Yt,ra=Uo,sr=$t,_n=yu,Fc=At.f,Uc=Bc,li=Mc,Hc=Pl,jc=Ye,Rn="Array Iterator",Gc=_n.set,Yc=_n.getterFor(Rn);Uc(Array,"Array",function(s,e){Gc(this,{type:Rn,target:Vc(s),index:0,kind:e})},function(){var s=Yc(this),e=s.target,t=s.kind,i=s.index++;return!e||i>=e.length?(s.target=void 0,li(void 0,!0)):t=="keys"?li(i,!1):t=="values"?li(e[i],!1):li([i,e[i]],!1)},"values");var ar=sr.Arguments=sr.Array;ra();ra();ra();if(!Hc&&jc&&ar.name!=="values")try{Fc(ar,"name",{value:"values"})}catch(s){}var qc=Se,zc=$t,Wc=qc("iterator"),Qc=Array.prototype,Jc=function(s){return s!==void 0&&(zc.Array===s||Qc[Wc]===s)},Kc=Ui,rr=Bi,Xc=Oi,Zc=$t,eh=Se,th=eh("iterator"),Dn=function(s){if(!Xc(s))return rr(s,th)||rr(s,"@@iterator")||Zc[Kc(s)]},ih=Be,sh=Ks,ah=at,rh=Js,nh=Dn,oh=TypeError,lh=function(s,e){var t=arguments.length<2?nh(s):e;if(sh(t))return ah(ih(t,s));throw oh(rh(s)+" is not iterable")},uh=Be,nr=at,dh=Bi,ch=function(s,e,t){var i,a;nr(s);try{if(i=dh(s,"return"),!i){if(e==="throw")throw t;return t}i=uh(i,s)}catch(n){a=!0,i=n}if(e==="throw")throw t;if(a)throw i;return nr(i),t},hh=fn,fh=Be,ph=at,mh=Js,bh=Jc,vh=sa,or=Qs,Sh=lh,gh=Dn,lr=ch,yh=TypeError,yi=function(s,e){this.stopped=s,this.result=e},ur=yi.prototype,Th=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=hh(e,i),u,c,h,f,m,b,p,v=function(y){return u&&lr(u,"normal",y),new yi(!0,y)},S=function(y){return a?(ph(y),l?d(y[0],y[1],v):d(y[0],y[1])):l?d(y,v):d(y)};if(n)u=s.iterator;else if(o)u=s;else{if(c=gh(s),!c)throw yh(mh(s)+" is not iterable");if(bh(c)){for(h=0,f=vh(s);f>h;h++)if(m=S(s[h]),m&&or(ur,m))return m;return new yi(!1)}u=Sh(s,c)}for(b=n?s.next:u.next;!(p=fh(b,u)).done;){try{m=S(p.value)}catch(y){lr(u,"throw",y)}if(typeof m=="object"&&m&&or(ur,m))return m}return new yi(!1)},Eh=Xs,$h=At,Ah=Vi,kh=function(s,e,t){var i=Eh(e);i in s?$h.f(s,i,Ah(0,t)):s[i]=t},Ph=Fi,wh=Th,_h=kh;Ph({target:"Object",stat:!0},{fromEntries:function(e){var t={};return wh(e,function(i,a){_h(t,i,a)},{AS_ENTRIES:!0}),t}});var Rh=zs,Dh=Rh.Object.fromEntries,Ih={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},Nh=Ih,Ch=Pe,xh=Ui,Lh=qt,dr=$t,Oh=Se,cr=Oh("toStringTag");for(var ps in Nh){var hr=Ch[ps],ms=hr&&hr.prototype;ms&&xh(ms)!==cr&&Lh(ms,cr,ps),dr[ps]=dr.Array}var Bh=Dh,Mh=Bh,Vh=Mh,Fh=Vh,Wt=Fh,vt;(function(s){s[s.OFFSET_P=0]="OFFSET_P",s[s.PLAYBACK_SHIFT=1]="PLAYBACK_SHIFT"})(vt||(vt={}));var St=(s,e=0,t=vt.OFFSET_P)=>{switch(t){case vt.OFFSET_P:return s.replace("_offset_p",e===0?"":"_"+e.toFixed(0));case vt.PLAYBACK_SHIFT:{if(e===0)return s;const i=new URL(s);return i.searchParams.append("playback_shift",e.toFixed(0)),i.toString()}default:r.assertNever(t)}return s},A=(s,e,t=!1)=>{const i=s.getTransition();(t||!i||i.to===e)&&s.setState(e)};exports.VideoQuality=void 0;(function(s){s.INVARIANT="Invariant quality",s.Q_144P="144p",s.Q_240P="240p",s.Q_360P="360p",s.Q_480P="480p",s.Q_720P="720p",s.Q_1080P="1080p",s.Q_1440P="1440p",s.Q_2160P="2160p",s.Q_4320P="4320p"})(exports.VideoQuality||(exports.VideoQuality={}));const ve={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Ti=(s,e)=>ve[s].height>ve[e].height,Uh=(s,e)=>ve[s].height>=ve[e].height,Ut=(s,e)=>ve[s].height<ve[e].height,Hh=(s,e)=>ve[s].height<=ve[e].height,jh=s=>s.sort((e,t)=>e===t?0:e===exports.VideoQuality.INVARIANT?1:t===exports.VideoQuality.INVARIANT?-1:Ut(e,t)?1:-1)[0],Gh=Object.keys(ve).sort((s,e)=>Ut(s,e)?-1:1),rt=({width:s,height:e})=>{const t=Math.min(s,e),i=Math.max(s,e);return Gh.find(a=>{const n=ve[a];return n.width>=i&&n.height>=t})},Yh=s=>ve[s].height,wi=s=>s===exports.VideoQuality.INVARIANT;class W{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}setState(e){const t=this.transition,i=this.state;this.transition=void 0,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.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}}const qh=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.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 x;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(x||(x={}));const zh=5,Wh=5,Qh=500,fr=7e3;class Jh{constructor(e){this.subscription=new r.Subscription,this.loadMediaTimeoutSubscription=new r.Subscription,this.videoState=new W(x.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!==x.STOPPED&&(this.videoState.startTransitionTo(x.STOPPED),this.stop());return}if(!a){if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&l.state===I.Requested&&i!==x.STOPPED){this.seek(l.position/1e3);return}switch(n){case exports.PlaybackState.READY:{switch(i){case x.PLAYING:case x.PAUSED:case x.READY:break;case x.STOPPED:this.videoState.startTransitionTo(x.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PLAYING:{switch(i){case x.PLAYING:break;case x.PAUSED:this.videoState.startTransitionTo(x.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case x.READY:this.videoState.startTransitionTo(x.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case x.STOPPED:this.videoState.startTransitionTo(x.READY),this.prepare();break;default:r.assertNever(i)}break}case exports.PlaybackState.PAUSED:{switch(i){case x.PLAYING:this.videoState.startTransitionTo(x.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case x.PAUSED:break;case x.READY:this.videoState.startTransitionTo(x.PAUSED),this.videoState.setState(x.PAUSED);break;case x.STOPPED:this.videoState.startTransitionTo(x.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(qh(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(Qh)).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===I.Applying||Math.abs(l-n)>zh)&&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<Wh&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:{this.handleRemotePause();break}case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default: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(x.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(x.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));const i=this.params.output.isLive$.getValue();this.params.output.duration$.next(i?0:t.duration),this.params.output.position$.next(i?0:t.currentTime),this.params.desiredState.seekState.setState({state:I.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)===x.PAUSED||e===x.PLAYING)&&(this.videoState.setState(x.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const e=this.videoState.getState(),t=this.videoState.getTransition();((t==null?void 0:t.to)===x.PLAYING||e===x.PAUSED)&&(this.videoState.setState(x.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){var e;const t=this.videoState.getTransition();(t==null?void 0:t.to)===x.READY&&this.videoState.setState(x.READY),((e=this.params.desiredState.playbackState.getTransition())===null||e===void 0?void 0:e.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY)}handleRemoteStop(){this.videoState.getState()!==x.STOPPED&&this.videoState.setState(x.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=jh(Object.keys(c));r.assertNonNullable(h);const f=c[h];r.assertNonNullable(f),a=f,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:{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=St(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===I.Applying||i.state===I.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(fr).subscribe(()=>n(`timeout(${fr})`)))});Promise.race([t,i]).then(()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`}),this.params.desiredState.seekState.getState().state===I.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)}`})}}class pr{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 In extends pr{constructor(){super(),this.listeners||pr.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 Nn=class{constructor(){Object.defineProperty(this,"signal",{value:new In,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&&(Nn.prototype[Symbol.toStringTag]="AbortController",In.prototype[Symbol.toStringTag]="AbortSignal");function Cn(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 Kh(s){typeof s=="function"&&(s={fetch:s});const{fetch:e,Request:t=e.Request,AbortController:i,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:a=!1}=s;if(!Cn({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 f=new t(u,c);return h&&Object.defineProperty(f,"signal",{writable:!1,enumerable:!1,configurable:!0,value:h}),f},n.prototype=t.prototype);const o=e;return{fetch:(d,u)=>{const c=n&&n.prototype.isPrototypeOf(d)?d.signal:u?u.signal:void 0;if(c){let h;try{h=new DOMException("Aborted","AbortError")}catch(m){h=new Error("Aborted"),h.name="AbortError"}if(c.aborted)return Promise.reject(h);const f=new Promise((m,b)=>{c.addEventListener("abort",()=>b(h),{once:!0})});return u&&u.signal&&delete u.signal,Promise.race([f,o(d,u)])}return o(d,u)},Request:n}}const Hi=Cn({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),xn=Hi?Kh({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,gt=Hi?xn.fetch:window.fetch;Hi?xn.Request:window.Request;const tt=Hi?Nn:window.AbortController,Bt=s=>s.range?s.range.split("-").map(e=>parseInt(e,10)):[NaN,NaN];class Ht{constructor(e){this.params=e,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(e){this.dashMetrics=e}queueDashJSRequest(e){var t;const{url:i}=e.request,a=(t=this.dashJsRequestQueue.get(i))!==null&&t!==void 0?t:[];a.push(e),this.dashJsRequestQueue.set(i,a)}async executeNextRequests(){for(const[e,t]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(e);if(i){t.length&&this.onBigRequestProgress(i);const a=t[0];if(!a||!a.request.range)continue;const[n,o]=Bt(a.request);if(n>=i.from&&o<=i.to)continue;this.activeRequests.delete(e)}if(t.length){const a=this.sendBigRequest(e,t.map(({request:n})=>n));this.activeRequests.set(e,a)}}}abort(e){var t;if(e){const{request:i}=e,a=((t=this.dashJsRequestQueue.get(i.url))!==null&&t!==void 0?t:[]).includes(e),n=this.activeRequests.get(i.url);a&&n&&n.abortController.abort()}else for(const{abortController:i}of this.activeRequests.values())i.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(e,t){const i=t.map(Bt),a=i[0][0];let n=i[0][1];for(let f=1;f<i.length&&n<this.params.minDataSize;f++){const m=i[f][1];m-a<=2*this.params.minDataSize&&(n=Math.max(n,m))}a===0?n=Math.max(n,a+this.params.minInitSize):n=Math.max(n,a+this.params.minDataSize);const o=new URL(e,location.href);o.searchParams.append("bytes",`${a}-${n}`);const l=o.toString(),d=new tt,u=d.signal,c={url:e,from:a,to:n,loaded:0,data:null,abortController:d};u.addEventListener("abort",()=>this.onBigRequestAbort(c));const h=f=>{var m,b;throw(b=(m=this.params).onError)===null||b===void 0||b.call(m,{id:"BigRequestParsing",category:r.ErrorCategory.PARSER,message:"Error parsing response data",thrown:f}),f};return gt(l,{signal:u}).then(f=>{var m,b,p;if(c.response=f,!f.ok||!f.body){this.onBigRequestError(c);return}const[v,S]=f.body.tee();(b=(m=this.params).onDownloadStream)===null||b===void 0||b.call(m,S);const y=v.getReader(),P=parseInt((p=f.headers.get("Content-Length"))!==null&&p!==void 0?p:"",10)||n-a+1;c.data=new ArrayBuffer(P);const E=new Uint8Array(c.data),T=async({done:w,value:V})=>{w?this.onBigRequestProgress(c):V&&(E.set(V,c.loaded),c.loaded+=V.byteLength,this.onBigRequestProgress(c),await(y==null?void 0:y.read().then(T,Ht.suppressStreamErrors).catch(h)))};y==null||y.read().then(T,Ht.suppressStreamErrors).catch(h)},Ht.suppressAbort).catch(f=>this.onBigRequestError(c,f)),c}onBigRequestProgress({url:e,from:t,to:i,loaded:a,data:n,response:o}){var l,d,u,c,h,f,m,b;if(!this.activeRequests.has(e)||!n)return;const p=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const v of p){const{request:S}=v,[y,P]=Bt(S),E=y>=t&&P<=t+a,T=t>=y&&t+a<P,w=n.slice(y-t,Math.min(P-t+1,a));if((E||T)&&(S.requestStartDate=(d=S.requestStartDate)!==null&&d!==void 0?d:new Date,S.firstByteDate=(u=S.firstByteDate)!==null&&u!==void 0?u:new Date,S.bytesLoaded=w.byteLength,S.bytesTotal=i-t),E){S.requestEndDate=new Date,this.dashJsRequestQueue.set(e,((c=this.dashJsRequestQueue.get(e))!==null&&c!==void 0?c:[]).filter(C=>C!==v)),(h=v.success)===null||h===void 0||h.call(v,w,"",e);const V=o?Array.from(o.headers.entries()).map(([C,R])=>`${C}: ${R}`).join(`\r
|
|
7
|
+
`):"";(f=this.dashMetrics)===null||f===void 0||f.addHttpRequest(S,e,(m=o==null?void 0:o.status)!==null&&m!==void 0?m:200,V,[])}else T&&((b=v.progress)===null||b===void 0||b.call(v,{loaded:a,total:i-t,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:e,from:t,to:i},a){var n,o,l,d;if((o=(n=this.params).onError)===null||o===void 0||o.call(n,{id:"BigRequest",category:r.ErrorCategory.NETWORK,message:"Download error",thrown:a}),!this.activeRequests.has(e))return;const u=(l=this.dashJsRequestQueue.get(e))!==null&&l!==void 0?l:[];for(const c of u){const[h,f]=Bt(c.request);(h>=t&&h<i||f>t&&f<=i)&&((d=c==null?void 0:c.error)===null||d===void 0||d.call(c,c.request,String(a)))}if(this.activeRequests.delete(e),a)throw a}onBigRequestAbort({url:e,from:t,to:i}){var a,n;if(!this.activeRequests.has(e))return;const o=(a=this.dashJsRequestQueue.get(e))!==null&&a!==void 0?a:[];for(const l of o){const[d,u]=Bt(l.request);(d>=t&&d<i||u>t&&u<=i)&&((n=l==null?void 0:l.abort)===null||n===void 0||n.call(l,l.request))}this.activeRequests.delete(e)}static suppressAbort(e){if(!(e instanceof DOMException)||!(e.name==="AbortError"||e.code===20))throw e}static suppressStreamErrors(){}}class _i{constructor(e,t,i){this.baseLoader=e,this.config=i,this.bigRequest=t,t.setMetrics(i.dashMetrics)}static shouldDelegateToBase(e){return e.action!=="download"||e.mediaType==="text"||!e.range||e.responseType!=="arraybuffer"}load(e){const{request:t}=e;if(_i.shouldDelegateToBase(t))return this.baseLoader.load(e);this.bigRequest.queueDashJSRequest(e),this.bigRequest.executeNextRequests()}abort(e){if(!e){this.baseLoader.abort(),this.bigRequest.abort();return}const{request:t}=e;_i.shouldDelegateToBase(t)?this.baseLoader.abort(e):this.bigRequest.abort(e)}}const Xh=(s,e)=>t=>({create:i=>{const a=s(t).create(i);return new _i(a,e,i)}}),Zh=(s,e)=>{const t=new Ht(e);return s.extend("SchemeLoaderFactory",function(){const{parent:i}=this,a=i.getLoader;return{getLoader:n=>{const o=a(n);return Xh(o,t)}}},!0),()=>t.destroy()};var ef=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)},tf=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,f,m,b,p;const v=Wt(c.getAllResponseHeaders().trim().split(/[\n\r]+/).map(P=>P.split(": ")));if("x-playback-duration"in v||"x-playback-duration-millis"in v){const P=parseInt((h=c.getResponseHeader("X-Playback-Duration"))!==null&&h!==void 0?h:"",10),E=parseInt((f=c.getResponseHeader("X-Playback-Duration-Millis"))!==null&&f!==void 0?f:"",10),T=(m=E!=null?E:P*1e3)!==null&&m!==void 0?m:NaN;r.isNonNullable(T)&&!isNaN(T)&&e.next(T)}const S=(b=v["x-delivery-type"])!==null&&b!==void 0?b:exports.HttpConnectionType.HTTP1,y=(p={1:!0,0:!1}[v["x-reused"]])!==null&&p!==void 0?p:void 0;i.next(S),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(f){if(f.request.type==="MPD"){const m=f.onload,b=f.progress;f.onload=function(...p){return d(this),m(...p)},f.progress=function(...p){return u(this),b(...p)},l()}return h(f)}}},!0),{playbackDuration$:e,ping$:t,connectionReused$:a,connectionType$:i}},yt=s=>{const e=new URL(s);return e.searchParams.set("quic","1"),e.toString()},sf=s=>s.extend("RequestModifier",()=>({modifyRequestURL:yt}),!0),af=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 ke=(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},nt=(s,e,t)=>ke(e,()=>s.loop,i=>{r.isNonNullable(i)&&(s.loop=i)},{onError:t}),Ve=(s,e,t,i)=>ke(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}),qe=(s,e,t,i)=>ke(e,()=>s.playbackRate,a=>{r.isNonNullable(a)&&(s.playbackRate=a)},{changed$:t,onError:i}),rf=s=>["__",s.language,s.label].join("|"),nf=(s,e)=>{if(s.id===e)return!0;const[t,i,a]=e.split("|");return s.language===i&&s.label===a};class we{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}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(ke(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(ke(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(ke(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();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,f;const m=(u=(d=l.target)===null||d===void 0?void 0:d.cues)!==null&&u!==void 0?u:null;m&&m.length&&(this.applyCueSettings((h=(c=l.target)===null||c===void 0?void 0:c.cues)!==null&&h!==void 0?h:null),(f=l.target)===null||f===void 0||f.removeEventListener("cuechange",o))};(n=i.track)===null||n===void 0||n.addEventListener("cuechange",o)})),this.subscription.add(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(we.isHealthyTrack)}htmlTextTrackToITextTrack(e){const{language:t,label:i}=e,a=e.id!==""?e.id:rf(e);return this.externalTracks.has(a)?{id:a,type:"external",language:t,label:i,url:this.externalTracks.get(a).url}:{id:a,type:"internal",language:t,label:i}}static isHealthyTrack(e){return!(e.kind==="metadata"||e.id===""&&e.label===""&&e.language==="")}setExternal(e){e.filter(({id:t})=>!this.externalTracks.has(t)).forEach(t=>this.attach(t)),Array.from(this.externalTracks.keys()).filter(t=>!e.find(i=>i.id===t)).forEach(t=>this.detach(t))}select(e){r.assertNonNullable(this.video);for(const t of this.htmlTextTracksAsArray(!0))r.isNonNullable(e)&&nf(t,e)?t.mode="showing":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),this.externalTracks.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);t&&this.video.removeChild(t),this.externalTracks.delete(e)}}var Fe=s=>{const e=document.createElement("video");return e.setAttribute("crossorigin","anonymous"),e.setAttribute("playsinline","playsinline"),e.setAttribute("poster","data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII="),s.appendChild(e),e};class na{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){this.streamOffset=e,this.pauseTimestamp=0,this.pausedTime=0}}var Ln=()=>{const{userAgent:s}=window.navigator;return!/chrome/i.test(s)&&/webkit|safari|khtml/i.test(s)};const js=3;class of{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 On=(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 lf=50,uf=s=>s.webkitAudioDecodedByteCount!=="undefined"?!!s.webkitAudioDecodedByteCount:s.mozHasAudio!=="undefined"?s.mozHasAudio:s.audioTracks?!!s.audioTracks.length:!0,Ue=s=>{const e=b=>r.fromEvent(s,b).pipe(r.mapTo(void 0)),t=["waiting","pause","canplay","play","canplaythrough","playing","seeking","seeked","ended"],i=r.merge(...t.map(b=>r.fromEvent(s,b))).pipe(r.map(b=>b.type==="ended"?s.readyState<2:s.readyState<3),r.filterChanged()),a=r.merge(r.fromEvent(s,"progress"),r.fromEvent(s,"timeupdate")).pipe(r.map(()=>On(s.buffered,s.currentTime))),n=Ln()?r.combine({play:e("play").pipe(r.once()),playing:e("playing")}).pipe(r.mapTo(void 0)):e("playing"),o=r.fromEvent(s,"playing").pipe(r.debounce(lf),r.map(()=>uf(s))),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(()=>Boolean(s.error||s.played.length)),r.map(()=>{var b;const p=s.error;return{id:p?`MediaError#${p.code}`:"HtmlVideoError",category:r.ErrorCategory.VIDEO_PIPELINE,message:p?p.message:"Error event from HTML video element",thrown:(b=s.error)!==null&&b!==void 0?b:void 0}})),c=r.fromEvent(s,"timeupdate").pipe(r.map(()=>s.currentTime)),h=new r.Subject,f=.3;let m;return c.subscribe(b=>{s.loop&&r.isNonNullable(m)&&r.isNonNullable(b)&&m>=s.duration-f&&b<=f&&h.next(m),m=b}),{playing$:n,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,isAudioAvailable$:o,playbackRateState$:d}},oa=s=>{if(s.includes("/")){const e=s.split("/");return parseInt(e[0])/parseInt(e[1])}else return parseFloat(s)};var df=Fi,cf=Mi,hf=sa,ff=ia;df({target:"Array",proto:!0},{at:function(e){var t=cf(this),i=hf(t),a=ff(e),n=a>=0?a:i+a;return n<0||n>=i?void 0:t[n]}});var pf=Ws,Bn=pf,mf=Bn,bf=mf("Array","at"),vf=bf,Sf=vf,gf=Sf,yf=gf,Ie=yf;let la=!1,Ne={};const Tf=s=>{la=s},Ef=()=>{Ne={}},$f=s=>{s(Ne)},ui=(s,e)=>{var t;la&&(Ne.meta=(t=Ne.meta)!==null&&t!==void 0?t:{},Ne.meta[s]=e)};class $e{constructor(e){this.name=e}next(e){var t,i;if(!la)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}}const Af=new $e("best_bitrate"),kf=(s,e,t)=>(e-t)*Math.pow(2,-10*s)+t;class Pf{constructor(){this.history={}}recordSelection(e){this.history[e.id]=r.now()}recordSwitch(e){this.last=e}clear(){this.last=void 0,this.history={}}}const Qt=(s,{container:e,throughput:t,tuning:i,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:l,current:d,history:u})=>{var c,h,f,m;const b=i.usePixelRatio&&(c=window.devicePixelRatio)!==null&&c!==void 0?c:1,p=i.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*b*i.containerSizeFactor,height:e.height*b*i.containerSizeFactor},v=p&&rt(p),S=i.considerPlaybackRate&&r.isNonNullable(l)?l:1,y=s.filter(D=>!wi(D.quality)).sort((D,_)=>Ti(D.quality,_.quality)?-1:1),P=(h=Ie(y,-1))===null||h===void 0?void 0:h.quality,E=(f=Ie(y,0))===null||f===void 0?void 0:f.quality,T=r.isNullable(a)||r.isNonNullable(a.min)&&r.isNonNullable(a.max)&&Ut(a.max,a.min)||r.isNonNullable(a.min)&&E&&Ti(a.min,E)||r.isNonNullable(a.max)&&P&&Ut(a.max,P),w=S*kf(o!=null?o:.5,i.bitrateFactorAtEmptyBuffer,i.bitrateFactorAtFullBuffer),C=y.filter(D=>{const _=v?Ut(D.quality,v):!0,j=r.isNonNullable(t)&&isFinite(t)&&r.isNonNullable(D.bitrate)?t-n>=D.bitrate*w:!0,Q=i.lazyQualitySwitch&&r.isNonNullable(i.minBufferToSwitchUp)&&d&&!wi(d.quality)&&(o!=null?o:0)<i.minBufferToSwitchUp&&Ti(D.quality,d.quality),Z=T||(r.isNullable(a.max)||Hh(D.quality,a.max))&&(r.isNullable(a.min)||Uh(D.quality,a.min));return _&&j&&!Q&&Z})[0];C&&C.bitrate&&Af.next(C.bitrate);const R=(m=C!=null?C:y[Math.ceil((y.length-1)/2)])!==null&&m!==void 0?m:s[0],F=R&&u&&u.history[R.id]&&r.now()-u.history[R.id]<=i.trackCooldown&&(!u.last||R.id!==u.last.id);if(R!=null&&R.id&&u&&!F&&u.recordSelection(R),F&&(u!=null&&u.last)){const D=u.last;return u==null||u.recordSwitch(D),D}return u==null||u.recordSwitch(R),R};var ne=s=>new URL(s).hostname;const wf=300,Ri=(s,e=wf)=>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(Eo(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()}),_f=5e3,Mt={};var L;(function(s){s.DOWNLOADING_LIB="downloading_lib",s.STOPPED="stopped",s.STREAM_INITIALIZED="stream_initialized",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(L||(L={}));const te=(s,e)=>new r.Observable(t=>{const i=a=>t.next(a);return s.on(e,i),()=>s.off(e,i)});class mr{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(L.DOWNLOADING_LIB),this.textTracksManager=new we,this.videoTracks=[],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 na,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===L.DOWNLOADING_LIB||t===L.STREAM_INITIALIZED))switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&t!==L.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 L.STOPPED:break;case L.PLAYING:case L.PAUSED:case L.READY:this.stop();break;default:r.assertNever(t)}break}case exports.PlaybackState.READY:{switch(t){case L.STOPPED:this.prepare();break;case L.PLAYING:case L.PAUSED:case L.READY:break;default:r.assertNever(t)}break}case exports.PlaybackState.PLAYING:{switch(t){case L.PLAYING:break;case L.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 L.READY:this.play();break;case L.STOPPED:this.prepare();break;default:r.assertNever(t)}break}case exports.PlaybackState.PAUSED:{switch(t){case L.PLAYING:this.pause(),this.liveOffset.pause();break;case L.PAUSED:break;case L.READY:this.videoState.setState(L.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case L.STOPPED:this.prepare();break;default:r.assertNever(t)}break}default:r.assertNever(i)}},this.video=Fe(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(ne(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"),_f);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(t=>(t.height&&(this.frameRatesByFrameHeight[t.height]=t.frameRate?oa(t.frameRate+""):void 0),!0)),(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Zh(this.player,{minInitSize:this.params.tuning.bigRequestMinInitSize,minDataSize:this.params.tuning.bigRequestMinDataSize,onError:t=>this.params.output.error$.next(t),onDownloadStream:t=>this.params.dependencies.throughputEstimator.trackStream(t)}):this.params.tuning.stripRangeHeader&&af(this.player),ef(this.player),this.params.tuning.requestQuick&&sf(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(L.STOPPED)}subscribe(){const{output:e,desiredState:t}=this.params,i=p=>{e.error$.next({id:"DashIFProvider",category:r.ErrorCategory.WTF,message:"DashIFProvider internal logic error",thrown:p})},a=(p,v)=>this.subscription.add(p.subscribe(v,i));a(Ri(this.video),this.elementSize$),a(te(this.player,"error").pipe(r.map(p=>{const v=typeof p.error=="object"?p.error.code:p.error,S=typeof p.error=="object"?p.error.message:void 0;return{id:`DashJS#${v}`,message:S}})),e.error$),a(te(this.player,"playbackError").pipe(r.map(p=>({id:"DashJSPlayback",message:p.error}))),e.error$);const n=te(this.player,"qualityChangeRendered").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({newQuality:p})=>{var v;return(v=this.videoTracks.find(({bitrateInfo:S})=>S.qualityIndex===p))===null||v===void 0?void 0:v.track}));n.pipe(r.filter(r.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(r.filter(({to:p})=>p===L.STREAM_INITIALIZED),r.once()).subscribe(()=>{this.subscription.add(ke(t.videoTrack,()=>{var p,v;const S=this.player.getQualityFor("video");return(v=(p=this.videoTracks.find(({bitrateInfo:y})=>y.qualityIndex===S))===null||p===void 0?void 0:p.track)===null||v===void 0?void 0:v.id},p=>{var v;if(r.isNullable(p))return;const S=(v=this.videoTracks.find(({track:y})=>y.id===p))===null||v===void 0?void 0:v.bitrateInfo;S&&this.player.setQualityFor("video",S.qualityIndex)},{changed$:n.pipe(r.map(p=>p==null?void 0:p.id)),onError:i}))},i)),this.subscription.add(ke(t.autoVideoTrackSwitching,()=>{var p,v,S;return(S=(v=(p=this.player.getSettings().streaming)===null||p===void 0?void 0:p.abr)===null||v===void 0?void 0:v.autoSwitchBitrate)===null||S===void 0?void 0:S.video},p=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:p}}}}),{onError:i})),a(te(this.player,"bufferStateChanged").pipe(r.filter(({mediaType:p})=>p==="video"),r.map(({state:p})=>p==="bufferStalled")),e.isBuffering$),a(te(this.player,"fragmentLoadingStarted"),({mediaType:p,request:{url:v}})=>{var S,y;const P=this.player.getDashMetrics(),E=P.getLatestFragmentRequestHeaderValueByID(p,"X-Reused"),T=(S=P.getLatestFragmentRequestHeaderValueByID(p,"X-Delivery-Type"))!==null&&S!==void 0?S:exports.HttpConnectionType.HTTP1,w=(y={1:!0,0:!1}[E])!==null&&y!==void 0?y:void 0;this.params.output.httpConnectionType$.next(T),this.params.output.httpConnectionReused$.next(w),e.hostname$.next(ne(v))}),a(te(this.player,"streamInitialized"),({streamInfo:{duration:p,manifestInfo:{isDynamic:v,availableFrom:S}}})=>{this.isLive$.next(v),this.availableFrom$.next(S.getTime()),v||e.duration$.next(p),this.videoTracks=[];const y=this.player.getQualityFor("video");let P;for(const E of this.player.getBitrateInfoListFor("video")){const T=E.qualityIndex.toString(10),w=rt(E),V=E.bitrate/1e3,C={width:E.width,height:E.height},R=this.frameRatesByFrameHeight[E.height];if(w){const F={id:T,quality:w,bitrate:V,size:C,fps:R};this.videoTracks.push({track:F,bitrateInfo:E}),E.qualityIndex===y&&(P=F)}}e.availableVideoTracks$.next(this.videoTracks.map(({track:E})=>E)),P&&e.currentVideoTrack$.next(P),this.videoState.setState(L.STREAM_INITIALIZED),this.videoState.startTransitionTo(L.READY)}),a(te(this.player,"fragmentLoadingCompleted"),({request:p})=>{if(!p.requestEndDate||!p.firstByteDate||!p.bytesLoaded)return;const v=p.requestEndDate.getTime()-p.firstByteDate.getTime(),S=p.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(S,v)}),a(r.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,t.autoVideoTrackLimits.stateChangeEnded$),()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const p=this.params.dependencies.throughputEstimator.throughput$.getValue(),v=Qt(this.videoTracks.map(({track:y})=>y),{container:this.elementSize$.getValue(),throughput:p,tuning:this.params.tuning.autoTrackSelection,limits:t.autoVideoTrackLimits.getState()}),S=this.videoTracks.find(({track:y})=>y===v);S!=null&&S.bitrateInfo&&this.player.setQualityFor("video",S==null?void 0:S.bitrateInfo.qualityIndex,!1)}),a(r.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(r.filter(r.isNonNullable))}).pipe(r.filter(({isLive:p})=>p),r.map(({maxSeekBackTime:p})=>-p/1e3)),this.params.output.duration$);const o=te(this.player,"playbackTimeUpdated").pipe(r.map(({time:p})=>p!=null?p:0));a(r.combine({availableFrom:this.availableFrom$.pipe(r.filter(r.isNonNullable)),currentTime:o}),({availableFrom:p,currentTime:v})=>this.params.output.liveTime$.next(p+v*1e3)),a(o.pipe(r.filter(()=>this.isLive$.getValue()===!1)),e.position$),a(te(this.player,"playbackSeeked"),()=>e.seekedEvent$.next()),a(te(this.player,"playbackEnded"),e.endedEvent$),a(te(this.player,"playbackProgress").pipe(r.map(()=>On(this.video.buffered,this.video.currentTime))),e.currentBuffer$),a(te(this.player,"playbackPlaying"),()=>{this.videoState.setState(L.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)}),a(te(this.player,"playbackNotAllowed"),()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(L.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())}),a(te(this.player,"playbackPaused"),()=>{this.videoState.setState(L.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)}),a(te(this.player,"canPlay"),()=>{var p;((p=this.videoState.getTransition())===null||p===void 0?void 0:p.to)===L.READY&&this.videoState.setState(L.READY)}),a(this.isLive$,e.isLive$),a(Ri(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}=tf(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(te(this.player,"canPlay"),e.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(r.combine({isLive:this.isLive$,isShort:e.duration$.pipe(r.map(p=>p<60))}),({isLive:p,isShort:v})=>{const S=!p&&v;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:S}}})}),a(o.pipe(r.filter(p=>p>this.params.tuning.insufficientBufferRuleMargin),r.once()),()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}})),this.textTracksManager.connect(this.video,t,e),this.subscription.add(te(this.player,"manifestLoaded").pipe(r.once()).subscribe(()=>{this.subscription.add(te(this.player,"playbackPlaying").pipe(r.once(),r.mapTo(void 0)).subscribe(e.firstFrameEvent$,i))},i)),this.subscription.add(nt(this.video,t.isLooped,i));const{volumeState$:f,looped$:m,playbackRateState$:b}=Ue(this.video);this.subscription.add(Ve(this.video,t.volume,f,i)),this.subscription.add(f.subscribe(e.volume$,i)),this.subscription.add(m.subscribe(e.loopedEvent$)),this.subscription.add(qe(this.video,t.playbackRate,b,i))}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(L.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(L.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=St(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,vt.PLAYBACK_SHIFT);this.player.attachSource(a)}else this.player.seek(e/1e3)}play(){this.videoState.startTransitionTo(L.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(L.PAUSED),this.video.pause()}destroy(){var e,t;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{(e=this.player)===null||e===void 0||e.destroy()}catch(i){}this.video.remove(),this.params.output.element$.next(void 0),(t=this.destroyBigRequest)===null||t===void 0||t.call(this)}}var Jt=s=>{switch(s){case"mobile":return exports.VideoQuality.Q_144P;case"lowest":return exports.VideoQuality.Q_240P;case"low":return exports.VideoQuality.Q_360P;case"sd":case"medium":return exports.VideoQuality.Q_480P;case"hd":case"high":return exports.VideoQuality.Q_720P;case"fullhd":case"full":return exports.VideoQuality.Q_1080P;case"quadhd":case"quad":return exports.VideoQuality.Q_1440P;case"ultrahd":case"ultra":return exports.VideoQuality.Q_2160P}},ze=async s=>{const e=s.muted;try{await s.play()}catch(t){if(t instanceof DOMException&&(t.code===20||t.name==="AbortError"))return!1;if(e)return console.warn(t),!1;s.muted=!0;try{await s.play()}catch(i){return s.muted=!1,console.warn(i),!1}}return!0};function ae(){return r.now()}function Mn(s){return ae()-s}function br(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 Rf(s,e,t){const i=(...a)=>{t.apply(null,a),s.removeEventListener(e,i)};s.addEventListener(e,i)}function Ei(s,e,t,i){const a=window.XMLHttpRequest;let n,o,l,d=!1,u=0,c,h,f=!1,m="arraybuffer",b=7e3,p=2e3,v=()=>{if(d)return;r.assertNonNullable(c);const _=Mn(c);let j;if(_<p){j=p-_,setTimeout(v,j);return}p*=2,p>b&&(p=b),o&&o.abort(),o=new a,w()};const S=_=>(n=_,D),y=_=>(h=_,D),P=()=>(m="json",D),E=()=>{if(!d){if(--u>=0){v(),i&&i();return}d=!0,h&&h(),t&&t()}},T=_=>(f=_,D),w=()=>{c=ae(),o=new a,o.open("get",s);let _=0,j,Q=0;const Z=()=>(r.assertNonNullable(c),Math.max(c,Math.max(j||0,Q||0)));if(n&&o.addEventListener("progress",$=>{const N=ae();n.updateChunk&&$.loaded>_&&(n.updateChunk(Z(),$.loaded-_),_=$.loaded,j=N)}),l&&(o.timeout=l,o.addEventListener("timeout",()=>E())),o.addEventListener("load",()=>{if(d)return;r.assertNonNullable(o);const $=o.status;if($>=200&&$<300){if(o.response.byteLength&&n){const N=o.response.byteLength-_;N&&n.updateChunk&&n.updateChunk(Z(),N)}h&&h(),o&&e(o.response)}else E()}),o.addEventListener("error",()=>{E()}),f){const $=()=>{r.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(Q=ae(),o.removeEventListener("readystatechange",$))};o.addEventListener("readystatechange",$)}return o.responseType=m,o.send(),D},D={withBitrateReporting:S,withParallel:T,withJSONResponse:P,withRetryCount:_=>(u=_,D),withRetryInterval:(_,j)=>(r.isNonNullable(_)&&(p=_),r.isNonNullable(j)&&(b=j),D),withTimeout:_=>(l=_,D),withFinally:y,send:w,abort:()=>{o&&(o.abort(),o=void 0),d=!0,h&&h()}};return D}const Df=100,If=2e3,Nf=500;let Cf=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-Nf;if(t-e>If){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>Df&&(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 xf{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=ae(),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=ae()-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=Ei(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=ae()}_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=ae();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 di=1e4,ci=3,Lf=300,Of=2e3,Bf=6e4,Mf=10,Vf=1,Ff=500;class Uf{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 Cf(this.params.logger),this._initVideo()}attachSource(e){this.manifestUrl=e,this.urlResolver=br(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=br(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;Boolean(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=()=>{Rf(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 xf(ci,di,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 E=n&&(!c||c===this.rep);return E||t("Not running!"),E},f=(E,T,w)=>{d&&d.abort(),d=Ei(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withTimeout(di).withBitrateReporting(this.bitrateSwitcher).withRetryCount(ci).withFinally(()=>{d=null}).send()},m=(E,T,w)=>{r.assertNonNullable(this.filesFetcher),l==null||l.abort(),l=this.filesFetcher.requestData(this.urlResolver.resolve(E,!1),T,w,()=>this._retryCallback()).withFinally(()=>{l=null}).send()},b=E=>{const T=i.playbackRate;i.playbackRate!==E&&(t(`Playback rate switch: ${T}=>${E}`),i.playbackRate=E)},p=E=>{this.lowLatency=E,t(`lowLatency changed to ${E}`),v()},v=()=>{if(!this.lowLatency&&!this.params.config.isLiveCatchUpMode)b(1);else{let E=this._getBufferSizeSec();if(this.bufferStates.length<5){b(1);return}const w=ae()-1e4;let V=0;for(let R=0;R<this.bufferStates.length;R++){const F=this.bufferStates[R];E=Math.min(E,F.buf),F.ts<w&&V++}this.bufferStates.splice(0,V),t(`update playback rate; minBuffer=${E} drop=${V} jitter=${this.sourceJitter}`);let C=E-Vf;this.sourceJitter>=0?C-=this.sourceJitter/2:this.sourceJitter-=1,C>3?b(1.15):C>1?b(1.1):C>.3?b(1.05):b(1)}},S=E=>{let T;const w=()=>T&&T.start?T.start.length:0,V=$=>T.start[$]/1e3,C=$=>T.dur[$]/1e3,R=$=>T.fragIndex+$,F=($,N)=>({chunkIdx:R($),startTS:V($),dur:C($),discontinuity:N}),D=()=>{let $=0;if(T&&T.dur){let N=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,q=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,X=N;this.sourceJitter>1&&(X+=this.sourceJitter-1);let ee=T.dur.length-1;for(;ee>=0&&(X-=T.dur[ee],!(X<=0));--ee);$=Math.min(ee,T.dur.length-1-q),$=Math.max($,0)}return F($,!0)},_=$=>{const N=w();if(!(N<=0)){if(r.isNonNullable($)){for(let q=0;q<N;q++)if(V(q)>$)return F(q)}return D()}},j=$=>{const N=w(),q=$?$.chunkIdx+1:0,X=q-T.fragIndex;if(!(N<=0)){if(!$||X<0||X-N>Mf)return t(`Resync: offset=${X} bChunks=${N} chunk=`+JSON.stringify($)),D();if(!(X>=N))return F(q-T.fragIndex,!1)}},Q=($,N,q)=>{u&&u.abort(),u=Ei(this.urlResolver.resolve($,!0,this.lowLatency),N,q,()=>this._retryCallback()).withTimeout(di).withRetryCount(ci).withFinally(()=>{u=null}).withJSONResponse().send()};return{seek:($,N)=>{Q(E,q=>{if(!h())return;T=q;const X=Boolean(T.lowLatency);X!==this.lowLatency&&p(X);let ee=0;for(let oe=0;oe<T.dur.length;++oe)ee+=T.dur[oe];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,$(_(N))},()=>this._handleNetworkError())},nextChunk:j}},y=()=>{n=!1,l&&l.abort(),d&&d.abort(),u&&u.abort(),r.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:E=>{const{videoElement:T,logger:w}=this.params;let V=S(e.jidxUrl),C,R,F,D,_=0,j,Q,Z;const $=()=>{j&&(clearTimeout(j),j=void 0);const U=Math.max(Ff,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),ie=_+U,re=ae(),ue=Math.min(1e4,ie-re);_=re;const We=()=>{u||h()&&V.seek(()=>{h()&&(_=ae(),N(),$())})};ue>0?j=window.setTimeout(()=>{this.paused?$():We()},ue):We()},N=()=>{let U;for(;U=V.nextChunk(D);)D=U,ge(U);const ie=V.nextChunk(F);if(ie){if(F&&ie.discontinuity){w("Detected discontinuity; restarting playback"),this.paused?$():(y(),this._initPlayerWith(e));return}oe(ie)}else $()},q=(U,ie)=>{if(!h()||!this.sourceBuffer)return;let re,ue,We;const ye=He=>{window.setTimeout(()=>{h()&&q(U,ie)},He)};if(this.sourceBuffer.updating)w("Source buffer is updating; delaying appendBuffer"),ye(100);else{const He=ae(),Qe=T.currentTime;!this.paused&&T.buffered.length>1&&Q===Qe&&He-Z>500&&(w("Stall suspected; trying to fix"),this._fixupStall()),Q!==Qe&&(Q=Qe,Z=He);const wt=this._getBufferSizeSec();if(wt>30)w(`Buffered ${wt} seconds; delaying appendBuffer`),ye(2e3);else try{this.sourceBuffer.appendBuffer(U),this.videoPlayStarted?(this.bufferStates.push({ts:He,buf:wt}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),ie&&ie()}catch(ot){if(ot.name==="QuotaExceededError")w("QuotaExceededError; delaying appendBuffer"),We=this.sourceBuffer.buffered.length,We!==0&&(re=this.sourceBuffer.buffered.start(0),ue=Qe,ue-re>4&&this.sourceBuffer.remove(re,ue-3)),ye(1e3);else throw ot}}},X=()=>{R&&C&&(w([`Appending chunk, sz=${R.byteLength}:`,JSON.stringify(F)]),q(R,function(){R=null,N()}))},ee=U=>e.fragUrlTemplate.replace("%%id%%",U.chunkIdx),oe=U=>{h()&&m(ee(U),(ie,re)=>{if(h()){if(re/=1e3,R=ie,F=U,o=U.startTS,re){const ue=Math.min(10,U.dur/re);this.downloadRate=this.downloadRate?(1-.3)*this.downloadRate+.3*ue:ue}X()}},()=>this._handleNetworkError())},ge=U=>{h()&&(r.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(ee(U),!1)))},Pt=U=>{h()&&(e.cachedHeader=U,q(U,()=>{C=!0,X()}))};n=!0,V.seek(U=>{if(h()){if(_=ae(),!U){$();return}D=U,!r.isNullable(E)||U.startTS>E?oe(U):(F=U,N())}},E),e.cachedHeader?Pt(e.cachedHeader):f(e.headerUrl,Pt,()=>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 f,m,b;if(this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&h<this.bitrate&&(m=this._getBufferSizeSec(),b=h/this.bitrate,m>10&&b>.8||m>15&&b>.5||m>20&&b>.3)){e(`Not switching: buffer=${Math.floor(m)}; bitrate=${this.bitrate}; newRate=${Math.floor(h)}`);return}f=this._selectQuality(h),f?this._switchToQuality(f):e(`Could not find quality by bitrate ${h}`)},n=(()=>({updateChunk:(f,m)=>{const b=ae();if(this.chunkRateEstimator.addInterval(f,b,m)){const v=this.chunkRateEstimator.getBitRate();return t({name:"bandwidth",size:m,duration:b-f,speed:v}),!0}},get:()=>{const f=this.chunkRateEstimator.getBitRate();return f?f*.85:0}}))();let o=-1/0,l,d=!0;const u=()=>{let h=n.get();if(h&&l&&this.autoQuality){if(d&&h>l&&Mn(o)<3e4)return;i(h)}d=this.autoQuality};return{updateChunk:(h,f)=>{const m=n.updateChunk(h,f);return m&&u(),m},notifySwitch:h=>{const f=ae();h<l&&(o=f),l=h}}}_fetchManifest(e,t,i){this.manifestRequest=Ei(this.urlResolver.resolve(e,!0),t,i,()=>this._retryCallback()).withJSONResponse().withTimeout(di).withRetryCount(ci).withRetryInterval(Lf,Of).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))},Bf))}_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 Hf=[O.PAUSED,O.PLAYING,O.READY],jf=[O.PAUSED,O.PLAYING,O.READY];class Gf{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(O.STOPPED),this.representations$=new r.ValueSubject([]),this.textTracksManager=new we,this.maxSeekBackTime$=new r.ValueSubject(1/0),this.zeroTime$=new r.ValueSubject(void 0),this.liveOffset=new na,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 f=(n=h.name)!==null&&n!==void 0?n:h.index.toString(10),m=(o=Jt(h.name))!==null&&o!==void 0?o:rt(h.video),b=h.bitrate/1e3,p={...h.video};if(!m)continue;const v={id:f,quality:m,bitrate:b,size:p};c.push({track:v,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=()=>{var a;const n=this.videoState.getState(),o=this.videoState.getTransition(),l=this.params.desiredState.playbackState.getState(),d=this.params.desiredState.playbackState.getTransition(),u=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${n}; videoTransition: ${JSON.stringify(o)}; desiredPlaybackState: ${l}; seekState: ${JSON.stringify(u)};`}),l===exports.PlaybackState.STOPPED){n!==O.STOPPED&&(this.videoState.startTransitionTo(O.STOPPED),this.dash.destroy(),this.video.setAttribute("src",""),this.video.load(),this.videoState.setState(O.STOPPED));return}if(!o){if(jf.includes(n)){const c=(a=this.params.desiredState.videoTrack.getTransition())===null||a===void 0?void 0:a.to;r.isNonNullable(c)&&this.setVideoTrack(c);const h=this.params.desiredState.autoVideoTrackSwitching.getTransition();h&&this.setAutoQuality(h.to)}if((d==null?void 0:d.to)!==exports.PlaybackState.PAUSED&&u.state===I.Requested&&Hf.includes(n)){this.seek(u.position-this.liveOffset.getTotalPausedTime());return}switch(n){case O.STOPPED:this.videoState.startTransitionTo(O.MANIFEST_READY),this.dash.attachSource(St(this.params.source.url));return;case O.MANIFEST_READY:this.videoState.startTransitionTo(O.READY),this.prepare();break;case O.READY:if(l===exports.PlaybackState.PAUSED)this.videoState.setState(O.PAUSED);else if(l===exports.PlaybackState.PLAYING){this.videoState.startTransitionTo(O.PLAYING);const c=d==null?void 0:d.from;c&&c===exports.PlaybackState.READY&&this.dash.catchUp(),this.dash.play(()=>{this.liveOffset.pause(),this.videoState.setState(O.PAUSED)})}return;case O.PLAYING:l===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(O.PAUSED),this.liveOffset.pause(),this.dash.pause());return;case O.PAUSED:l===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(n)}}},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=Fe(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.hostname$.next(ne(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=Ue(this.video);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===I.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(nt(this.video,this.params.desiredState.isLooped,t)).add(Ve(this.video,this.params.desiredState.volume,i.volumeState$,t)).add(i.volumeState$.subscribe(this.params.output.volume$,t)).add(qe(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(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe(({to:{max:a}})=>{const n=a&&Yh(a);this.dash.setMaxAutoQuality(n)})).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$,r.observableFrom(["init"])).pipe(r.debounce(0)).subscribe(this.syncPlayback,t))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const e=new Uf({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=Qt(l.map(({track:f})=>f),{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()}))===null||n===void 0?void 0:n.id,h=(o=l.find(({track:f})=>f.id===c))===null||o===void 0?void 0:o.representation;r.assertNonNullable(h,"Representations missing"),this.dash.startPlay(h,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(c),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(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=-e,i=t<=this.maxSeekBackTime$.getValue()?t:0;this.params.output.position$.next(e/1e3),this.liveOffset.resetTo(i),this.dash.reinit(St(this.params.source.url,i))}}var Vn=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}},et=(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 Yf=s=>{const e=document.createElement("a");return e.href=s,e.origin},qf=s=>{const e=document.createElement("a");return e.href=s,e.host};class Fn{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(r.assertNonNullable(this._xhr),((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=Wt(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map(h=>h.split(":").map(f=>f.trim())));(o=this._headersCb)===null||o===void 0||o.call(this,new Headers(c))}else this._xhr.readyState===4?(l=this._completeCb)===null||l===void 0||l.call(this,this._xhr.response):this._xhr.readyState===3&&((d=this._progressCb)===null||d===void 0||d.call(this,this._xhr.response))}catch(c){throw(u=this._errorCb)===null||u===void 0||u.call(this,"XHR2CallbackError",`xhr2 callback threw ${String(c)}`,c),c}},this._xhr.onerror=()=>{var t;(t=this._xhr)===null||t===void 0||t.abort(),this._retryTimeout=window.setTimeout(()=>{var i;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,(i=this._errorCb)===null||i===void 0||i.call(this,"XHR2Failover","XHR failed, retrying failover host");else{let a;this._failoverIndex>=this._failoverHosts.length?(a=this._url,this._failoverIndex=0):(a=this._url.replace(qf(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 Di{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,f=0;const m=p=>{a(Di._str2ua(p.substr(d))),d=p.length};let b=e.baseURL+"&bytes="+t+"-"+i;this._params.requestQuic&&(b=yt(b)),this._lastXhr=new Fn(b,e.failoverHosts,p=>{this._lastXhr=void 0,m(p);const v=Date.now()-u;this._params.onBandwidthChange({size:p.length,duration:v,speed:8*p.length/(v/1e3)}),this._onDashCallback("loading",{size:p.length,done:!0}),n==null||n()},p=>{if(p.length-d>l&&m(p),h===0){h=Date.now();return}f=p.length-c;const v=Date.now()-h;f>=100*1024&&v>=1e3&&(this._params.onBandwidthChange({size:f,duration:v,speed:8*f/(v/1e3)}),f=0,c=p.length,h=Date.now()),this._onDashCallback("loading",{size:p.length,done:!1})},o,(p,v,S)=>this._params.onError(p,v,S))})}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=Di._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 zf{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=yt(i)),new Fn(i,t,a=>{this.attachManifest(a,t,Yf(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,f,m,b,p,v,S,y,P,E,T,w,V,C,R,F,D,_;const j=u.getElementsByTagName("SegmentBase")[0],Q=j&&o(j,"indexRange").split("-"),Z=j&&j.getElementsByTagName("Initialization")[0],$=Z&&o(Z,"range").split("-");if(!$||!Q){const ge=u.parentElement;if((ge==null?void 0:ge.getAttribute("contentType"))==="text"){const Pt=(c=u.getAttribute("id"))!==null&&c!==void 0?c:void 0,U=(i?i+"/":"")+((b=(m=(f=(h=u.getElementsByTagName("BaseURL"))===null||h===void 0?void 0:h[0])===null||f===void 0?void 0:f.childNodes)===null||m===void 0?void 0:m[0])===null||b===void 0?void 0:b.data),ie=(p=ge.getAttribute("lang"))!==null&&p!==void 0?p:void 0;U&&d.push({id:Pt,url:U,language:ie})}return}const N=.1,q=Number((v=u.attributes.getNamedItem("bandwidth"))===null||v===void 0?void 0:v.value),X=(i?i+"/":"")+u.getElementsByTagName("BaseURL")[0].childNodes[0].data;let ee;const oe=(y=(S=u.attributes.getNamedItem("frameRate"))===null||S===void 0?void 0:S.value)!==null&&y!==void 0?y:void 0;ee=oe?oa(oe):void 0,l.push({width:Number((P=u.attributes.getNamedItem("width"))===null||P===void 0?void 0:P.value),height:Number((E=u.attributes.getNamedItem("height"))===null||E===void 0?void 0:E.value),bandwidth:q,baseURL:X,failoverHosts:t,indexFrom:Number(Q[0]),indexTo:Number(Q[1]),initFrom:Number($[0]),initTo:Number($[1]),codecs:(w=(T=u.attributes.getNamedItem("codecs"))===null||T===void 0?void 0:T.value)!==null&&w!==void 0?w:void 0,mimeType:(C=(V=u.attributes.getNamedItem("mimeType"))===null||V===void 0?void 0:V.value)!==null&&C!==void 0?C:void 0,fps:ee,bufferSize:N*q/8,bufferLength:N,name:(F=(R=u.attributes.getNamedItem("okQuality"))===null||R===void 0?void 0:R.value)!==null&&F!==void 0?F:void 0,id:(_=(D=u.attributes.getNamedItem("id"))===null||D===void 0?void 0:D.value)!==null&&_!==void 0?_:void 0})}),l.length)this._representations=l;else{this._onDashCallback("error");return}d.forEach(({id:u,language:c,url:h})=>{const f=document.createElement("track");f.setAttribute("src",h),u&&f.setAttribute("id",u),c&&f.setAttribute("srclang",c),this._video.appendChild(f)}),this._representations.sort((u,c)=>c.bandwidth-u.bandwidth),this._params.onManifestReady(this._representations)}_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 f=0;f<c;f+=1){const m=u+(o.getUint32(n,!1)&2147483647),b=d+o.getUint32(n+4,!1);n+=12,e.refs.push({fromTime:d/l,toTime:b/l,fromOffset:u,toOffset:m-1}),u=m,d=b}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 m=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),m)}const c=this._appendVector[String(u.fromTime)];c!==a&&(a=c,this._params.onRepresentationPlay(c));let h;if(this._findRef(u.toTime)){const m=this._buffer.getByTime(this._video.currentTime);if(!m){this._onDashCallback("buffering");return}h=m.to-this._video.currentTime,h<e.bufferLength&&(this._onDashCallback("buffering"),n!==m.to&&(n=m.to,window.setTimeout(()=>{try{const b=this._buffer.getNextWithGap(m);b&&(this._video.currentTime=b.from)}catch(b){throw this._params.onError("GapSyncError",`Seek Error ${String(b)}`,b),b}},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 Di({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 B;(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"})(B||(B={}));const Wf=[B.PAUSED,B.PLAYING];class Qf{constructor(e){this.videoState=new W(B.STOPPED),this.subscription=new r.Subscription,this.representations$=new r.ValueSubject([]),this.currentRepresentation$=new r.ValueSubject(void 0),this.textTracksManager=new we,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=t=>{var i,a,n;const o=[];for(const l of t){const d=(a=(i=l.name)!==null&&i!==void 0?i:l.id)!==null&&a!==void 0?a:l.height.toString(10),u=(n=l.name&&Jt(l.name))!==null&&n!==void 0?n:rt(l),c=l.bandwidth/1e3,h={width:l.width,height:l.height},f=l.fps;if(!u)continue;const m={id:d,quality:u,bitrate:c,size:h,fps:f};o.push({track:m,representation:l})}this.representations$.next(o),this.params.output.availableVideoTracks$.next(o.map(({track:l})=>l)),this.videoState.setState(B.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!==B.STOPPED&&(this.videoState.startTransitionTo(B.STOPPED),this.dash.destroy(),this.video.setAttribute("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(B.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(!i)switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&o.state===I.Requested&&Wf.includes(t)&&this.seek(o.position,o.forcePrecise),t){case B.STOPPED:this.videoState.startTransitionTo(B.MANIFEST_LOADED),this.prepare();return;case B.MANIFEST_LOADED:this.videoState.startTransitionTo(B.INITIAL_REPRESENTATION_SELECTED);return;case B.INITIAL_REPRESENTATION_SELECTED:this.videoState.startTransitionTo(B.METADATA_LOADED),this.dash.startPlay(this.selectRepresentation());return;case B.METADATA_LOADED:this.videoState.startTransitionTo(B.READY),this.dash.updateRefsForCurrentTime();return;case B.READY:a===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed());return;case B.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(B.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case B.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(B.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(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=Fe(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(ne(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new of(this.video),this.dash=new zf({video:this.video,buffer:this.buffer,selectRepresentation:this.selectRepresentation,onIdxRequestPing:t=>this.dashLiteEvents.idxRequestPing$.next(t),onResponseHeaders:t=>this.dashLiteEvents.responseHeaders$.next(t),onManifestReady:t=>this.dashLiteEvents.manifestReady$.next(t),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=Ue(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(n.seeking$.subscribe(()=>{r.isNullable(this.params.desiredState.seekState.getState().state!==I.Applying)&&(this.videoState.getState()===B.PLAYING||this.videoState.getState()===B.PAUSED)&&this.dash.updateRefsForCurrentTime()})),this.subscription.add(n.seeked$.subscribe(e.seekedEvent$,i)),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ve(this.video,t.volume,n.volumeState$,i)),this.subscription.add(n.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,t.playbackRate,n.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),o(Ri(this.video),this.elementSize$),this.subscription.add(n.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===B.READY&&this.videoState.setState(B.READY)},i)).add(n.pause$.subscribe(()=>{this.videoState.setState(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)})).add(n.playing$.subscribe(()=>{this.videoState.setState(B.PLAYING),A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)},i)).add(n.loadedMetadata$.subscribe(()=>{this.videoState.setState(B.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.stateChangeEnded$,this.params.output.element$,this.elementSize$,r.fromEvent(this.video,"progress")).pipe(r.map(()=>{var l,d,u;const c=this.currentRepresentation$.getValue(),h=this.representations$.getValue(),f=this.params.desiredState.autoVideoTrackSwitching.getTransition(),m=this.params.desiredState.videoTrack.getState(),b=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),p=this.elementSize$.getValue(),v=a();f&&this.params.desiredState.autoVideoTrackSwitching.setState(f.to);let S;if(!v&&r.isNonNullable(m))S=m;else{const y=et(this.video.buffered,this.video.currentTime*1e3),P=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/P,1);S=(d=Qt(h.map(({track:T})=>T),{container:p,throughput:b,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:E,playbackRate:this.video.playbackRate,current:(l=h.find(({representation:T})=>T===c))===null||l===void 0?void 0:l.track}))===null||d===void 0?void 0:d.id}return r.isNonNullable(S)?(u=h.find(({track:y})=>y.id===S))===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===B.INITIAL_REPRESENTATION_SELECTED)),currentRepresentationSelected:this.currentRepresentation$.pipe(r.filter(r.isNonNullable))}).pipe(r.once()).subscribe(()=>this.videoState.setState(B.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=et(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(ne(l.baseURL)))},i)).add(this.dashLiteEvents.responseHeaders$.subscribe(l=>{const{type:d,reused:u}=Vn(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.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}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(B.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}var he;(function(s){s.VIDEO="video",s.AUDIO="audio",s.TEXT="text"})(he||(he={}));var Ii;(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"})(Ii||(Ii={}));var fe;(function(s){s.BYTE_RANGE="byteRange",s.TEMPLATE="template"})(fe||(fe={}));var H;(function(s){s.NONE="none",s.DOWNLOADING="downloading",s.DOWNLOADED="downloaded",s.PARTIALLY_FED="partially_fed",s.PARTIALLY_EJECTED="partially_ejected",s.FED="fed"})(H||(H={}));var Tt;(function(s){s.MP4="mp4",s.WEBM="webm"})(Tt||(Tt={}));var Ni;(function(s){s[s.RECTANGULAR=0]="RECTANGULAR",s[s.EQUIRECTANGULAR=1]="EQUIRECTANGULAR",s[s.CUBEMAP=2]="CUBEMAP",s[s.MESH=3]="MESH"})(Ni||(Ni={}));var Gs=(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 Jf=(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)},Kf=typeof window.requestIdleCallback!="function"||typeof window.cancelIdleCallback!="function",vr=Kf?Jf:window.requestIdleCallback;var bs,vs;let Un=!1;try{Un=Ln()&&parseInt((vs=(bs=navigator.userAgent.match(/Version\/(\d+)/))===null||bs===void 0?void 0:bs[1])!==null&&vs!==void 0?vs:"",10)<16}catch(s){console.error(s)}class Xf{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;Un&&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)}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"&&i==="remove"||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 Sr=s=>{let e=0;for(let t=0;t<s.length;t++)e+=s.end(t)-s.start(t);return e*1e3};class _e{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 Hn extends _e{}class Zf extends _e{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 ep extends _e{parseChildrenBoxes(){return kt(this.content)}}class tp extends _e{constructor(e){super(e),this.data=this.content}}class Kt extends _e{constructor(e){super(e);const t=this.readUint32();this.version=t>>>24,this.flags=t&16777215}}class ip extends Kt{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 sp extends _e{parseChildrenBoxes(){return kt(this.content)}}class ap extends _e{parseChildrenBoxes(){return kt(this.content)}}var Ze;(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"})(Ze||(Ze={}));class rp extends Kt{constructor(e){switch(super(e),this.readUint8()){case 0:this.stereoMode=Ze.MONOSCOPIC;break;case 1:this.stereoMode=Ze.TOP_BOTTOM;break;case 2:this.stereoMode=Ze.LEFT_RIGHT;break;case 3:this.stereoMode=Ze.STEREO_CUSTOM;break;case 4:this.stereoMode=Ze.RIGHT_LEFT;break}this.cursor+=1}}class np extends Kt{constructor(e){super(e),this.poseYawDegrees=this.readUint32(),this.posePitchDegrees=this.readUint32(),this.poseRollDegrees=this.readUint32()}}class op extends Kt{constructor(e){super(e),this.projectionBoundsTop=this.readUint32(),this.projectionBoundsBottom=this.readUint32(),this.projectionBoundsLeft=this.readUint32(),this.projectionBoundsRight=this.readUint32()}}class lp extends _e{parseChildrenBoxes(){return kt(this.content)}}class up extends Kt{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 dp extends _e{parseChildrenBoxes(){return kt(this.content)}}class cp extends _e{parseChildrenBoxes(){return kt(this.content)}}const hp={ftyp:Zf,moov:ep,mdat:tp,sidx:ip,trak:sp,mdia:lp,tkhd:up,minf:dp,sv3d:ap,st3d:rp,prhd:np,proj:cp,equi:op,unknown:Hn};class fp{createBox(e,t){const i=hp[e];return i?new i(t):new Hn(t)}createFromView(e){const i=new TextDecoder("ascii").decode(new DataView(e.buffer,e.byteOffset+4,4));return ji.createBox(i,new DataView(e.buffer,e.byteOffset))}}const ji=new fp;function Ft(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:ji.createBox(e,new DataView(s.buffer,i-7))}i++}return null}function pp(s,e){const t=[];let i=s.byteOffset;for(;i<s.byteLength;){const a=Ft(new DataView(s.buffer,i,s.byteLength),e);if(a)t.push(a),i+=a.source.byteOffset+a.source.byteLength;else break}return t}function kt(s){const e=[];let t=0;for(;t<s.byteLength;){const i=ji.createFromView(new DataView(s.buffer,s.byteOffset+t));if(e.push(i),!i.size)break;t+=i.size}return e}const mp=new TextDecoder("ascii"),bp=s=>mp.decode(new DataView(s.buffer,s.byteOffset+4,4))==="ftyp",vp=s=>{const e=ji.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:H.NONE,time:{from:t,to:t+o},byte:{from:i,to:i+n.referencedSize-1}};return t+=o,i+=n.referencedSize,l})},Sp=s=>{const e=pp(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},gp=s=>{const e={is3dVideo:!1,stereoMode:0,projectionType:Ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}};if(Ft(s,"sv3d")){e.is3dVideo=!0;const i=Ft(s,"st3d");i&&(e.stereoMode=i.stereoMode);const a=Ft(s,"prhd");a&&(e.projectionData.pose.yaw=a.poseYawDegrees,e.projectionData.pose.pitch=a.posePitchDegrees,e.projectionData.pose.roll=a.poseRollDegrees);const n=Ft(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},yp={validateData:bp,parseInit:gp,getIndexRange:()=>{},parseSegments:vp,parseFeedableSegmentChunk:Sp};var g;(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"})(g||(g={}));var k;(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"})(k||(k={}));const gr={[g.EBML]:{type:k.Master},[g.EBMLVersion]:{type:k.UnsignedInteger},[g.EBMLReadVersion]:{type:k.UnsignedInteger},[g.EBMLMaxIDLength]:{type:k.UnsignedInteger},[g.EBMLMaxSizeLength]:{type:k.UnsignedInteger},[g.DocType]:{type:k.String},[g.DocTypeVersion]:{type:k.UnsignedInteger},[g.DocTypeReadVersion]:{type:k.UnsignedInteger},[g.Void]:{type:k.Binary},[g.Segment]:{type:k.Master},[g.SeekHead]:{type:k.Master},[g.Seek]:{type:k.Master},[g.SeekID]:{type:k.Binary},[g.SeekPosition]:{type:k.UnsignedInteger},[g.Info]:{type:k.Master},[g.TimestampScale]:{type:k.UnsignedInteger},[g.Duration]:{type:k.Float},[g.Tracks]:{type:k.Master},[g.TrackEntry]:{type:k.Master},[g.Video]:{type:k.Master},[g.Projection]:{type:k.Master},[g.ProjectionType]:{type:k.UnsignedInteger},[g.ProjectionPrivate]:{type:k.Master},[g.Chapters]:{type:k.Master},[g.Cluster]:{type:k.Master},[g.Timestamp]:{type:k.UnsignedInteger},[g.SilentTracks]:{type:k.Master},[g.SilentTrackNumber]:{type:k.UnsignedInteger},[g.Position]:{type:k.UnsignedInteger},[g.PrevSize]:{type:k.UnsignedInteger},[g.SimpleBlock]:{type:k.Binary},[g.BlockGroup]:{type:k.Master},[g.EncryptedBlock]:{type:k.Binary},[g.Attachments]:{type:k.Master},[g.Tags]:{type:k.Master},[g.Cues]:{type:k.Master},[g.CuePoint]:{type:k.Master},[g.CueTime]:{type:k.UnsignedInteger},[g.CueTrackPositions]:{type:k.Master},[g.CueTrack]:{type:k.UnsignedInteger},[g.CueClusterPosition]:{type:k.UnsignedInteger},[g.CueRelativePosition]:{type:k.UnsignedInteger},[g.CueDuration]:{type:k.UnsignedInteger},[g.CueBlockNumber]:{type:k.UnsignedInteger},[g.CueCodecState]:{type:k.UnsignedInteger},[g.CueReference]:{type:k.Master},[g.CueRefTime]:{type:k.UnsignedInteger}},jn=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=Ci(s,t),a=i in gr,n=a?gr[i].type:k.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=Ci(d),h=u*2**((l-1)*8)+c,f=t+l;let m;return f+h>s.byteLength?m=new DataView(s.buffer,s.byteOffset+f):m=new DataView(s.buffer,s.byteOffset+f,h),{tag:a?i:"0x"+i.toString(16).toUpperCase(),type:n,tagHeaderSize:f,tagSize:f+h,value:m,valueSize:h}},Ci=(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},Ae=(s,e)=>{switch(e){case k.SignedInteger:return s.getInt8(0);case k.UnsignedInteger:return Ci(s);case k.Float:return s.byteLength===4?s.getFloat32(0):s.getFloat64(0);case k.String:return new TextDecoder("ascii").decode(s);case k.UTF8:return new TextDecoder("utf-8").decode(s);case k.Date:return new Date(Date.UTC(2001,0)+s.getInt8(0)).getTime();case k.Master:return s;case k.Binary:return s;default:r.assertNever(e)}},Et=(s,e)=>{let t=0;for(;t<s.byteLength;){const i=new DataView(s.buffer,s.byteOffset+t),a=jn(i);if(!e(a))return;a.type===k.Master&&Et(a.value,e),t=a.value.byteOffset-s.byteOffset+a.valueSize}},Tp=s=>{if(s.getUint32(0)!==g.EBML)return!1;let e,t,i;const a=jn(s);return Et(a.value,({tag:n,type:o,value:l})=>(n===g.EBMLReadVersion?e=Ae(l,o):n===g.DocType?t=Ae(l,o):n===g.DocTypeReadVersion&&(i=Ae(l,o)),!0)),(e===void 0||e<=1)&&t!==void 0&&t==="webm"&&(i===void 0||i<=2)},Gn=[g.Info,g.SeekHead,g.Tracks,g.TrackEntry,g.Video,g.Projection,g.ProjectionType,g.ProjectionPrivate,g.Chapters,g.Cluster,g.Cues,g.Attachments,g.Tags],Ep=[g.Timestamp,g.SilentTracks,g.SilentTrackNumber,g.Position,g.PrevSize,g.SimpleBlock,g.BlockGroup,g.EncryptedBlock],$p=s=>{let e,t,i,a,n=!1,o=!1,l=!1,d,u,c=!1;const h=0;return Et(s,({tag:f,type:m,value:b,valueSize:p})=>{if(f===g.SeekID){const v=Ae(b,m);u=Ci(v)}else f!==g.SeekPosition&&(u=void 0);return f===g.Segment?(e=b.byteOffset,t=b.byteOffset+p):f===g.Info?n=!0:f===g.SeekHead?o=!0:f===g.TimestampScale?i=Ae(b,m):f===g.Duration?a=Ae(b,m):f===g.SeekPosition&&u===g.Cues?d=Ae(b,m):f===g.Tracks?Et(b,({tag:v,type:S,value:y})=>v===g.ProjectionType?(c=Ae(y,S)===1,!1):!0):n&&o&&Gn.includes(f)&&(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:Ni.EQUIRECTANGULAR,projectionData:{pose:{yaw:0,pitch:0,roll:0},bounds:{top:0,bottom:0,left:0,right:0}}}},Ap=s=>{if(r.isNullable(s.cuesSeekPosition))return;const e=s.segmentStart+s.cuesSeekPosition,t=1024*1024;return{from:e,to:e+t}},kp=(s,e)=>{let t=!1,i=!1;const a=l=>r.isNonNullable(l.time)&&r.isNonNullable(l.position),n=[];let o;return Et(s,({tag:l,type:d,value:u})=>{switch(l){case g.Cues:t=!0;break;case g.CuePoint:o&&a(o)&&n.push(o),o={};break;case g.CueTime:o&&(o.time=Ae(u,d));break;case g.CueTrackPositions:break;case g.CueClusterPosition:o&&(o.position=Ae(u,d));break;default:t&&Gn.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:H.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}}})},Pp=s=>{let e=0,t=!1;try{Et(s,i=>i.tag===g.Cluster?i.tagSize<=s.byteLength?(e=i.tagSize,!1):(e+=i.tagHeaderSize,!0):Ep.includes(i.tag)?(e+i.tagSize<=s.byteLength&&(e+=i.tagSize,t||(t=[g.SimpleBlock,g.BlockGroup,g.EncryptedBlock].includes(i.tag))),!0):!1)}catch(i){}return e>0&&e<=s.byteLength&&t?new DataView(s.buffer,s.byteOffset,e):null},wp={validateData:Tp,parseInit:$p,getIndexRange:Ap,parseSegments:kp,parseFeedableSegmentChunk:Pp};class yr{constructor(e,t,i,a,{fetcher:n,tuning:o,getCurrentPosition:l,compatibilityMode:d=!1}){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.subscription=new r.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new tt,this.destroyAbortController=new tt,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=r.abortable(this.destroyAbortController.signal,async function*(u){const c=this.representations.get(u);r.assertNonNullable(c,`Cannot find representation ${u}`),this.playingRepresentationId=u,this.downloadingRepresentationId=u,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${c.mime}; codecs="${c.codecs}"`),this.sourceBufferTaskQueue=new Xf(this.sourceBuffer),this.subscription.add(r.fromEvent(this.sourceBuffer,"updateend").subscribe(()=>{this.checkEjectedSegments(),this.maintain()},p=>this.error$.next({id:"SegmentEjection",category:r.ErrorCategory.WTF,message:"Error when trying to clear segments ejected by browser",thrown:p}))),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(p=>{if(!this.sourceBuffer)return;const v=Math.min(this.bufferLimit,Sr(this.sourceBuffer.buffered)*.8);this.bufferLimit=v,this.pruneBuffer(this.getCurrentPosition(),p)})),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe(p=>this.error$.next(p))),yield this.loadInit(c,"high",!0);const h=this.initData.get(c.id),f=this.segments.get(c.id),m=this.parsedInitData.get(c.id);if(r.assertNonNullable(h,"No init buffer for starting representation"),r.assertNonNullable(f,"No segments for starting representation"),!(h instanceof ArrayBuffer))return;let b=0;for(const p of f)p.time.from-b>0&&this.gaps.push({representation:c.id,from:b,to:p.time.from}),b=p.time.to;r.isNonNullable(c.duration)&&c.duration-b>0&&this.gaps.push({representation:c.id,from:b,to:c.duration}),yield this.sourceBufferTaskQueue.append(h,this.destroyAbortController.signal),this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(m)}.bind(this)),this.switchTo=r.abortable(this.destroyAbortController.signal,async function*(u){if(u===this.downloadingRepresentationId||u===this.switchingToRepresentationId)return;this.switchingToRepresentationId=u;const c=this.representations.get(u);r.assertNonNullable(c,`No such representation ${u}`);let h=this.initData.get(u);if(r.isNullable(h)?yield this.loadInit(c,"high",!1):h instanceof Promise&&(yield h),h=this.initData.get(u),!h||!(h instanceof ArrayBuffer)||!this.sourceBuffer)return;this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=u,this.abort(),yield this.sourceBufferTaskQueue.append(h,this.downloadAbortController.signal);const f=this.getCurrentPosition();r.isNonNullable(f)&&this.maintain(f)}.bind(this)),this.fetcher=n,this.tuning=o,this.compatibilityMode=d,this.forwardBufferTarget=o.dash.forwardBufferTargetAuto,this.getCurrentPosition=l,this.container=i,i){case Tt.MP4:this.containerParser=yp;break;case Tt.WEBM:this.containerParser=wp;break;default:r.assertNever(i)}this.initData=new Map(a.map(u=>[u.id,null])),this.segments=new Map,this.parsedInitData=new Map,this.representations=new Map(a.map(u=>[u.id,u])),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 tt,this.abortBuffer()}maintain(e=this.getCurrentPosition()){if(r.isNullable(e)||r.isNullable(this.downloadingRepresentationId)||r.isNullable(this.playingRepresentationId)||r.isNullable(this.sourceBuffer))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=et(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)&&Sr(this.sourceBuffer.buffered)>=this.bufferLimit){const u=et(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=Ie(l,0);c&&c.time.from-a.time.to>=this.forwardBufferTarget/2&&(u="low")}this.loadSegments(l,t,u)}!this.preloadOnly&&!this.allInitsLoaded&&a&&a.status===H.FED&&!l.length&&et(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const d=Ie(i,-1);d&&d.status===H.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(a===d))}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;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(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(e,t,i){const a=e.findIndex(({status:h,time:{from:f,to:m}},b)=>{const p=f<=i&&m>=i,v=f>i||p||b===0&&i===0,S=Math.min(this.forwardBufferTarget,this.bufferLimit),y=this.preloadOnly&&f<=i+S||m<=i+S;return(h===H.NONE||h===H.PARTIALLY_EJECTED&&v&&y&&this.sourceBuffer&&!Gs(this.sourceBuffer.buffered,i))&&v&&y});if(a===-1)return[];if(t!==fe.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 f=n[h];if(o+=f.byte.to+1-f.byte.from,l+=f.time.to+1-f.time.from,f.status===H.NONE||f.status===H.PARTIALLY_EJECTED)d.push(f);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 fe.BYTE_RANGE:{a=t.segmentReference.url,n={from:Ie(e,0).byte.from,to:Ie(e,-1).byte.to};break}case fe.TEMPLATE:{const u=Ie(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=H.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=>{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=et((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 f;this.playingRepresentationId=t,this.playingRepresentation$.next(this.playingRepresentationId),this.playingRepresentationInit$.next(this.parsedInitData.get(this.playingRepresentationId)),h.segment.status=H.FED,"size"in h.segment&&(h.segment.size=h.fedBytes);for(const m of this.representations.values())if(m.id!==t)for(const b of(f=this.segments.get(m.id))!==null&&f!==void 0?f:[])b.status===H.FED&&b.time.from===h.segment.time.from&&b.time.to===h.segment.time.to&&(b.status=H.NONE);this.activeSegments.delete(h),this.detectGapsWhenIdle(t,[h.segment])},d=this.representations.get(t);if(!d)return;const u=d.segmentReference.type,c=e.byteLength;for(const h of this.activeSegments){const{segment:f}=h,m=u===fe.BYTE_RANGE,b=m?f.byte.to-f.byte.from+1:c;if(h.representationId!==t||!(!m||f.byte.from>=i&&f.byte.to<i+e.byteLength))continue;if(n.aborted){o();continue}const v=m?f.byte.from-i:0,S=m?f.byte.to-i:e.byteLength,y=v<a,P=S<=a;if(f.status===H.DOWNLOADING&&y&&P){f.status=H.DOWNLOADED,this.activeSegments.delete(h);const E=new DataView(e.buffer,e.byteOffset+v,b);this.sourceBufferTaskQueue.append(E,n).then(T=>T&&!n.aborted?l(h):o())}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&y&&(h.loadedBytes=Math.min(b,a-v),h.loadedBytes>h.feedingBytes)){const E=new DataView(e.buffer,e.byteOffset+v+h.feedingBytes,h.loadedBytes-h.feedingBytes),T=h.loadedBytes===b?E:this.containerParser.parseFeedableSegmentChunk(E);T!=null&&T.byteLength&&(f.status=H.PARTIALLY_FED,h.feedingBytes+=T.byteLength,this.sourceBufferTaskQueue.append(T,n).then(w=>{if(n.aborted)o();else if(w)h.fedBytes+=T.byteLength,h.fedBytes===b&&l(h);else{if(h.feedingBytes<b)return;o()}}))}}}abortSegment(e){e.status===H.PARTIALLY_FED||e.status===H.PARTIALLY_EJECTED?(this.sourceBufferTaskQueue.remove(e.time.from,e.time.to).then(()=>e.status=H.NONE),e.status=H.PARTIALLY_EJECTED):e.status=H.NONE;for(const t of this.activeSegments.values())if(t.segment===e){this.activeSegments.delete(t);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=vr(()=>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(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,c),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===H.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===H.FED&&d(c)}}if(l=isFinite(n)&&isFinite(o),!l)for(let u=0;u<this.sourceBuffer.buffered.length;u++){const c=this.sourceBuffer.buffered.start(u)*1e3,h=this.sourceBuffer.buffered.end(u)*1e3;for(const f of this.segments.values())for(const m of f)if(m.status===H.NONE&&Math.round(m.time.from)<=Math.round(c)&&Math.round(m.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===H.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)}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=vr(()=>{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!==H.FED&&n!==H.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=H.PARTIALLY_EJECTED:a.status=H.NONE)}}}var bt;(function(s){s[s.HEADER=0]="HEADER",s[s.PARAM=1]="PARAM"})(bt||(bt={}));class _p{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 tt,this.subscription=new r.Subscription,this.fetchManifest=r.abortable(this.abortAllController.signal,async function*(a){let n=a;this.requestQuic&&(n=yt(n));const o=yield gt(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?bt.HEADER:bt.PARAM,range:o,onProgress:l,priority:d="auto",signal:u,measureThroughput:c=!0}={}){var h,f,m,b;let p=a;const v=new Headers;if(o)switch(n){case bt.HEADER:{v.append("Range",`bytes=${o.from}-${o.to}`);break}case bt.PARAM:{const $=new URL(p,location.href);$.searchParams.append("bytes",`${o.from}-${o.to}`),p=$.toString();break}default:r.assertNever(n)}this.requestQuic&&(p=yt(p));let S=this.abortAllController.signal;if(u){const $=new tt;if(this.subscription.add(r.merge(r.fromEvent(this.abortAllController.signal,"abort"),r.fromEvent(u,"abort")).subscribe(()=>{try{$.abort()}catch(N){Vt(N)}})),this.abortAllController.signal.aborted||u.aborted)try{$.abort()}catch(N){Vt(N)}S=$.signal}const y=r.now(),P=yield gt(p,{priority:d,headers:v,signal:S}).catch(Vt),E=r.now();if((h=this.throughputEstimator)===null||h===void 0||h.addRawRtt(E-y),!P)return null;if(!P.ok||!P.body)return Promise.reject(new Error(`Fetch error ${P.status}: ${P.statusText}`));this.onHeadersReceived(P.headers);const T=parseInt((f=P.headers.get("Content-Length"))!==null&&f!==void 0?f:"",10)||o&&o.to-o.from+1||NaN;if(!T){const $=yield P.arrayBuffer();return(m=this.throughputEstimator)===null||m===void 0||m.addRawSpeed($.byteLength,r.now()-E),l==null||l(new DataView($),$.byteLength),$}if(!l&&!c)return P.arrayBuffer();const[w,V]=P.body.tee(),C=w.getReader();c&&((b=this.throughputEstimator)===null||b===void 0||b.trackStream(V));let R=0;const F=new ArrayBuffer(T),D=new Uint8Array(F),_=new DataView(F);let j=!1;const Q=$=>{j=!0,Vt($)},Z=r.abortable(S,async function*({done:$,value:N}){R===0&&this.lastRequestFirstBytes$.next(r.now()-y),!S.aborted&&($?l==null||l(_,R):N&&(D.set(N,R),R+=N.byteLength,l==null||l(_,R),yield C==null?void 0:C.read().then(Z,Q)))}.bind(this));return yield C==null?void 0:C.read().then(Z,Q),j?null:F}.bind(this)),this.fetchByteRangeRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n,o){var l;if(a.type!==fe.BYTE_RANGE)return null;const{from:d,to:u}=a.initRange;let c=d,h=u,f=!1,m,b;a.indexRange&&(m=a.indexRange.from,b=a.indexRange.to,f=u+1===m,f&&(c=Math.min(m,d),h=Math.max(b,u))),c=Math.min(c,0);const p=yield this.fetch(a.url,{range:{from:c,to:h},priority:o,measureThroughput:!1});if(!p)return null;const v=new DataView(p,d-c,u-c+1);if(!n.validateData(v))throw new Error("Invalid media file");const S=n.parseInit(v),y=(l=a.indexRange)!==null&&l!==void 0?l:n.getIndexRange(S);if(!y)throw new ReferenceError("No way to load representation index");let P;if(f)P=new DataView(p,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;P=new DataView(T)}const E=n.parseSegments(P,S,y);return{init:S,dataView:new DataView(p),segments:E}}.bind(this)),this.fetchTemplateRepresentation=r.abortable(this.abortAllController.signal,async function*(a,n){if(a.type!==fe.TEMPLATE)return null;const o=new URL(a.initUrl,a.baseUrl).toString(),l=yield this.fetch(o,{priority:n,measureThroughput:!1});if(!l)return null;const d=a.segments.map(u=>({...u,status:H.NONE,size:void 0}));return{init:{},segments:d,dataView:new DataView(l)}}.bind(this)),this.throughputEstimator=e,this.requestQuic=t,this.compatibilityMode=i}onHeadersReceived(e){const{type:t,reused:i}=Vn(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 fe.BYTE_RANGE:return(a=await this.fetchByteRangeRepresentation(e,t,i))!==null&&a!==void 0?a:null;case fe.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 Rp=st,Dp=Li,Ip=Se,Np=Ip("match"),Cp=function(s){var e;return Rp(s)&&((e=s[Np])!==void 0?!!e:Dp(s)=="RegExp")},xp=Ui,Lp=String,Op=function(s){if(xp(s)==="Symbol")throw TypeError("Cannot convert a Symbol value to a string");return Lp(s)},Bp=at,Mp=function(){var s=Bp(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},Vp=Be,Fp=Me,Up=Qs,Hp=Mp,Tr=RegExp.prototype,jp=function(s){var e=s.flags;return e===void 0&&!("flags"in Tr)&&!Fp(s,"flags")&&Up(Tr,s)?Vp(Hp,s):e},ua=Oe,Gp=Mi,Yp=Math.floor,Ss=ua("".charAt),qp=ua("".replace),gs=ua("".slice),zp=/\$([$&'`]|\d{1,2}|<[^>]*>)/g,Wp=/\$([$&'`]|\d{1,2})/g,Qp=function(s,e,t,i,a,n){var o=t+s.length,l=i.length,d=Wp;return a!==void 0&&(a=Gp(a),d=zp),qp(n,d,function(u,c){var h;switch(Ss(c,0)){case"$":return"$";case"&":return s;case"`":return gs(e,0,t);case"'":return gs(e,o);case"<":h=a[gs(c,1,-1)];break;default:var f=+c;if(f===0)return u;if(f>l){var m=Yp(f/10);return m===0?u:m<=l?i[m-1]===void 0?Ss(c,1):i[m-1]+Ss(c,1):u}h=i[f-1]}return h===void 0?"":h})},Jp=Fi,Kp=Be,da=Oe,Er=qs,Xp=me,Zp=Oi,em=Cp,ht=Op,tm=Bi,im=jp,sm=Qp,am=Se,rm=am("replace"),nm=TypeError,Yn=da("".indexOf),om=da("".replace),$r=da("".slice),lm=Math.max,Ar=function(s,e,t){return t>s.length?-1:e===""?t:Yn(s,e,t)};Jp({target:"String",proto:!0},{replaceAll:function(e,t){var i=Er(this),a,n,o,l,d,u,c,h,f,m=0,b=0,p="";if(!Zp(e)){if(a=em(e),a&&(n=ht(Er(im(e))),!~Yn(n,"g")))throw nm("`.replaceAll` does not allow non-global regexes");if(o=tm(e,rm),o)return Kp(o,e,i,t);if(a)return om(ht(i),e,t)}for(l=ht(i),d=ht(e),u=Xp(t),u||(t=ht(t)),c=d.length,h=lm(1,c),m=Ar(l,d,0);m!==-1;)f=u?ht(t(d,m,l)):sm(d,l,m,[],void 0,t),p+=$r(l,b,m)+f,b=m+c,m=Ar(l,d,m+h);return b<l.length&&(p+=$r(l,b)),p}});var um=Bn,dm=um("String","replaceAll"),cm=dm,hm=cm,fm=hm,pm=fm,kr=pm;const Pr=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},ys=(s,e)=>{let t=s;t=kr(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=kr(t,o,(l,d)=>r.isNullable(n)?l:r.isNullable(d)?n:n.padStart(parseInt(d,10),"0"))}return t},mm=(s,e)=>{var t,i,a,n,o,l,d,u,c,h,f,m,b,p,v,S,y,P,E,T,w,V,C,R,F,D,_,j,Q,Z,$,N,q,X,ee,oe,ge;const U=new DOMParser().parseFromString(s,"application/xml"),ie={video:[],audio:[],text:[]},re=U.children[0],ue=re.getElementsByTagName("Period")[0],We=ue.children;let ye;const He=re.getAttribute("mediaPresentationDuration"),Qe=ue.getAttribute("duration");if(He)ye=Pr(He);else if(Qe){const Te=Pr(Qe);r.isNonNullable(Te)&&(ye=Te)}let wt=0;const ot=(i=(t=re.getAttribute("profiles"))===null||t===void 0?void 0:t.split(","))!==null&&i!==void 0?i:[],Kn=ot.includes(Ii.WEBM_AS_IN_FFMPEG)||ot.includes(Ii.WEBM_AS_IN_SPEC)?Tt.WEBM:Tt.MP4;for(const Te of We){const Xt=Te.getAttribute("mimeType"),Xn=Te.getAttribute("codecs"),ca=(a=Te.getAttribute("contentType"))!==null&&a!==void 0?a:Xt==null?void 0:Xt.split("/")[0],Zn=(o=(n=Te.getAttribute("profiles"))===null||n===void 0?void 0:n.split(","))!==null&&o!==void 0?o:[],eo=Te.querySelectorAll("Representation"),to=Te.querySelector("SegmentTemplate");if(ca!=="text")for(const se of eo){const _t=(l=se.getAttribute("mimeType"))!==null&&l!==void 0?l:Xt,ha=(u=(d=se.getAttribute("codecs"))!==null&&d!==void 0?d:Xn)!==null&&u!==void 0?u:"",Zt=(h=(c=se.getAttribute("contentType"))!==null&&c!==void 0?c:_t==null?void 0:_t.split("/")[0])!==null&&h!==void 0?h:ca,io=(m=(f=Te.getAttribute("profiles"))===null||f===void 0?void 0:f.split(","))!==null&&m!==void 0?m:[],so=parseInt((b=se.getAttribute("width"))!==null&&b!==void 0?b:"",10),fa=parseInt((p=se.getAttribute("height"))!==null&&p!==void 0?p:"",10),pa=parseInt((v=se.getAttribute("bandwidth"))!==null&&v!==void 0?v:"",10)/1e3,ma=(S=se.getAttribute("frameRate"))!==null&&S!==void 0?S:"",ao=(y=se.getAttribute("quality"))!==null&&y!==void 0?y:void 0,ro=ma?oa(ma):void 0,no=(P=se.getAttribute("id"))!==null&&P!==void 0?P:(wt++).toString(10),oo=Zt==="video"?`${fa}p`:Zt==="audio"?`${pa}Kbps`:ha,lo=`${no}@${oo}`,uo=(w=(T=(E=se.querySelector("BaseURL"))===null||E===void 0?void 0:E.textContent)===null||T===void 0?void 0:T.trim())!==null&&w!==void 0?w:"",ba=new URL(uo,e).toString(),co=[...ot,...Zn,...io];let Yi;const ho=se.querySelector("SegmentBase"),Je=(V=se.querySelector("SegmentTemplate"))!==null&&V!==void 0?V:to;if(ho){const Rt=(R=(C=se.querySelector("SegmentBase Initialization"))===null||C===void 0?void 0:C.getAttribute("range"))!==null&&R!==void 0?R:"",[Dt,zi]=Rt.split("-").map(Ke=>parseInt(Ke,10)),It={from:Dt,to:zi},Nt=(F=se.querySelector("SegmentBase"))===null||F===void 0?void 0:F.getAttribute("indexRange"),[Wi,ei]=Nt?Nt.split("-").map(Ke=>parseInt(Ke,10)):[],Ct=Nt?{from:Wi,to:ei}:void 0;Yi={type:fe.BYTE_RANGE,url:ba,initRange:It,indexRange:Ct}}else if(Je){const Rt={representationId:(D=se.getAttribute("id"))!==null&&D!==void 0?D:void 0,bandwidth:(_=se.getAttribute("bandwidth"))!==null&&_!==void 0?_:void 0},Dt=parseInt((j=Je.getAttribute("timescale"))!==null&&j!==void 0?j:"",10),zi=(Q=Je.getAttribute("initialization"))!==null&&Q!==void 0?Q:"",It=Je.getAttribute("media"),Nt=($=parseInt((Z=Je.getAttribute("startNumber"))!==null&&Z!==void 0?Z:"",10))!==null&&$!==void 0?$:1,Wi=ys(zi,Rt);if(!It)throw new ReferenceError("No media attribute in SegmentTemplate");const ei=(N=Je.querySelectorAll("SegmentTimeline S"))!==null&&N!==void 0?N:[],Ct=[];if(ei.length){let Ke=Nt,Xe=0;for(const xt of ei){const lt=parseInt((q=xt.getAttribute("d"))!==null&&q!==void 0?q:"",10)*1e3,Lt=parseInt((X=xt.getAttribute("r"))!==null&&X!==void 0?X:"",10)||0,Ot=(oe=parseInt((ee=xt.getAttribute("t"))!==null&&ee!==void 0?ee:"",10))!==null&&oe!==void 0?oe:void 0;for(let va=0;va<Lt+1;va++){const fo=ys(It,{...Rt,segmentNumber:Ke.toString(10),segmentTime:Ot.toString(10)}),po=Ot?Ot/Dt:Xe;Xe+=lt/Dt;const mo=Xe;Ke++,Ct.push({time:{from:po,to:mo},url:fo})}}}else if(r.isNonNullable(ye)){const Xe=parseInt((ge=Je.getAttribute("duration"))!==null&&ge!==void 0?ge:"",10)/Dt*1e3,xt=Math.ceil(ye/Xe);let lt=0;for(let Lt=1;Lt<xt;Lt++){const Ot=ys(It,{...Rt,segmentNumber:Lt.toString(10),segmentTime:lt.toString(10)});Ct.push({time:{from:lt,to:lt+Xe},url:Ot}),lt+=Xe}}Yi={type:fe.TEMPLATE,baseUrl:ba,initUrl:Wi,segments:Ct}}else throw new ReferenceError("Unknown MPD segment referencing type");if(!Zt||!_t)continue;const qi={video:he.VIDEO,audio:he.AUDIO,text:he.TEXT}[Zt];qi&&ie[qi].push({id:lo,kind:qi,segmentReference:Yi,profiles:co,duration:ye,bitrate:pa,mime:_t,codecs:ha,width:so,height:fa,fps:ro,quality:ao})}}return{duration:ye,container:Kn,representations:ie}},bm=["timeupdate","progress","play","seeked","stalled","waiting"];var ce;(function(s){s.NONE="none",s.MANIFEST_READY="manifest_ready",s.REPRESENTATIOS_READY="representations_ready",s.RUNNING="running"})(ce||(ce={}));let vm=class{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new r.Subscription,this.state$=new W(ce.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.forceEnded$=new r.Subject,this.gapWatchdogStarted=!1,this.destroyController=new tt,this.initManifest=r.abortable(this.destroyController.signal,async function*(t,i){this.element=t,this.state$.startTransitionTo(ce.MANIFEST_READY);const a=yield this.fetcher.fetchManifest(i).catch(l=>this.error$.next({id:"LoadManifest",category:r.ErrorCategory.NETWORK,message:"Failed to load manifest",thrown:l}));if(!a)return;let n;try{n=mm(a!=null?a:"",i)}catch(l){this.error$.next({id:"ManifestParsing",category:r.ErrorCategory.PARSER,message:"Failed to parse MPD manifest",thrown:l})}if(!n)return;const o=({mime:l,codecs:d})=>{var u,c,h;return Boolean(((u=t.canPlayType)===null||u===void 0?void 0:u.call(t,l))&&((h=(c=window.MediaSource)===null||c===void 0?void 0:c.isTypeSupported)===null||h===void 0?void 0:h.call(c,`${l}; codecs="${d}"`)))};this.manifest={...n,representations:Wt(Object.entries(n.representations).map(([l,d])=>[l,d.filter(o)]))},this.manifest.representations.video.length?this.state$.setState(ce.MANIFEST_READY):this.error$.next({id:"NoRepresentations",category:r.ErrorCategory.PARSER,message:"No playable video representations"})}.bind(this)),this.initRepresentations=r.abortable(this.destroyController.signal,async function*(t,i){r.assertNonNullable(this.manifest),r.assertNonNullable(this.element),this.state$.startTransitionTo(ce.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};this.videoBufferManager=new yr(he.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,a),this.bufferManagers=[this.videoBufferManager],r.isNonNullable(i)&&(this.audioBufferManager=new yr(he.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,a),this.bufferManagers.push(this.audioBufferManager)),this.subscription.add(this.fetcher.lastConnectionType$.subscribe(this.lastConnectionType$)),this.subscription.add(this.fetcher.lastConnectionReused$.subscribe(this.lastConnectionReused$)),this.subscription.add(this.fetcher.lastRequestFirstBytes$.subscribe(this.lastRequestFirstBytes$));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.subscription.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.subscription.add(r.merge(...this.bufferManagers.map(l=>l.error$)).subscribe(this.error$)),this.subscription.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(ce.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.jumGap(),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 _p({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick,compatibilityMode:e.compatibilityMode})}initBuffer(){r.assertNonNullable(this.element),this.state$.setState(ce.RUNNING),this.subscription.add(r.merge(...bm.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&&Gs(this.element.buffered,this.element.currentTime*1e3)&&(this.element.currentTime=this.element.currentTime)})),this.tick()}async switchRepresentation(e,t){const i={[he.VIDEO]:this.videoBufferManager,[he.AUDIO]:this.audioBufferManager,[he.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),Gs(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(ce.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(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const e=this.element.currentTime*1e3,t=[];for(const i of this.bufferManagers)for(const a of i.gaps)i.playingRepresentation$.getValue()===a.representation&&a.from<=e&&a.to>e&&(this.element.duration*1e3-a.to<this.tuning.endGapTolerance?t.push(1/0):t.push(a.to));if(t.length){const i=Math.max(...t);i===1/0?(this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),this.gapWatchdogStarted=!1):this.element.currentTime=i/1e3}}};const Sm=135,gm=76;class ym{constructor(){this.fov={x:Sm,y:gm},this.rotation={x:0,y:0,z:0}}}const ft=10,wr=175;class Tm{constructor(e,t={}){this.rotating=!1,this.torqueLossTS=0,this.hold=!1,this.options=t,this.camera=e,this.torqueLossTS=performance.now(),this.rotationSpeed={x:0,y:0,z:0},this.rotationMoment={x:0,y:0,z:0}}turnCamera(e=0,t=0,i=0){this.pointCameraTo(this.camera.rotation.x+e,this.camera.rotation.y+t,this.camera.rotation.z+i)}pointCameraTo(e=0,t=0,i=0){this.camera.rotation.x=e,this.camera.rotation.y=this.limitCameraRotationY(t),this.camera.rotation.z=i}setRotationSpeed(e,t,i){e===void 0&&(e=this.rotationSpeed.x),t===void 0&&(t=this.rotationSpeed.y),i===void 0&&(i=this.rotationSpeed.z),this.rotationSpeed.x=e,this.rotationSpeed.y=t,this.rotationSpeed.z=i,this.torqueLossTS=performance.now()}startRotation(){this.rotating=!0}stopRotation(e=!1){e&&this.setRotationSpeed(0,0,0),this.rotating=!1,this.torqueLossTS=performance.now()}limitCameraRotationY(e){return Math.max(-wr,Math.min(e,wr))}temporalFn(e){const t=100-5e-4*(e-this.torqueLossTS);return Math.sign(t)*Math.sqrt(Math.abs(t))/10}tick(e){if(!this.lastTick){this.lastTick=e;return}const i=(e-this.lastTick)/1e3;if(this.rotating)this.turnCamera(this.rotationSpeed.x*i*ft,this.rotationSpeed.y*i*ft,this.rotationSpeed.z*i*ft);else{let a=0,n=0,o=0;const l=this.temporalFn(e);this.rotationSpeed.x&&(this.rotationSpeed.x=Math.sign(this.rotationSpeed.x)*Math.max(Math.abs(this.rotationSpeed.x)-l,0),a=this.rotationSpeed.x*i*ft),this.rotationSpeed.y&&(this.rotationSpeed.y=Math.sign(this.rotationSpeed.y)*Math.max(Math.abs(this.rotationSpeed.y)-l,0),n=this.rotationSpeed.y*i*ft),this.rotationSpeed.z&&(this.rotationSpeed.z=Math.sign(this.rotationSpeed.z)*Math.max(Math.abs(this.rotationSpeed.z)-l,0),o=this.rotationSpeed.z*i*ft),this.turnCamera(a,n,o)}this.rotationSpeed.x===0&&this.rotationSpeed.y===0&&this.rotationSpeed.z===0&&this.stopRotation(),this.lastTick=e}}const Em=`
|
|
8
|
+
attribute vec2 a_vertex;
|
|
9
|
+
attribute vec2 a_texel;
|
|
10
|
+
|
|
11
|
+
varying vec2 v_texel;
|
|
12
|
+
|
|
13
|
+
void main(void) {
|
|
14
|
+
// direct vertex drawing
|
|
15
|
+
gl_Position = vec4(a_vertex, 0.0, 1.0);
|
|
16
|
+
// save texel vector to pass to fragment shader
|
|
17
|
+
v_texel = a_texel;
|
|
18
|
+
}
|
|
19
|
+
`,$m=`
|
|
20
|
+
#ifdef GL_ES
|
|
21
|
+
precision highp float;
|
|
22
|
+
precision highp int;
|
|
23
|
+
#else
|
|
24
|
+
precision mediumhp float;
|
|
25
|
+
#endif
|
|
26
|
+
|
|
27
|
+
varying vec2 v_texel; // [0..1, 0..1]
|
|
28
|
+
|
|
29
|
+
uniform sampler2D u_texture;
|
|
30
|
+
uniform vec2 u_focus; // current central point [-180..180, -90..90] (degrees)
|
|
31
|
+
|
|
32
|
+
const float PI = 3.14159265358979323846264;
|
|
33
|
+
const float PI_2 = PI * 0.5;
|
|
34
|
+
const float PI2 = PI * 2.0;
|
|
35
|
+
|
|
36
|
+
void main(void) {
|
|
37
|
+
// center point of output projection
|
|
38
|
+
float lambda0 = u_focus.x / 360.0; // [-0.5, 0.5]
|
|
39
|
+
float phi0 = u_focus.y / 180.0; // [-0.5, 0.5]
|
|
40
|
+
|
|
41
|
+
float x = PI2 * (v_texel.x - 0.5 - lambda0); // [-pi..+pi] (rad)
|
|
42
|
+
float y = PI * (v_texel.y - 0.5 - phi0); // [-pi/2..+pi/2] (rad)
|
|
43
|
+
|
|
44
|
+
float p = sqrt(x * x + y * y); // rou
|
|
45
|
+
float c = atan(p);
|
|
46
|
+
float cos_c = cos(c);
|
|
47
|
+
float sin_c = sin(c);
|
|
48
|
+
|
|
49
|
+
// geo coordinates of projection
|
|
50
|
+
float lambda = lambda0 + atan(
|
|
51
|
+
x * sin_c,
|
|
52
|
+
p * cos(phi0) * cos_c - y * sin(phi0) * sin_c
|
|
53
|
+
);
|
|
54
|
+
float phi = asin(cos_c * sin(phi0) + (y * sin_c * cos(phi0)) / p);
|
|
55
|
+
|
|
56
|
+
// reprojected texture coordinates
|
|
57
|
+
vec2 tc = vec2(
|
|
58
|
+
mod(lambda / PI2 - 0.5, 1.0), // [0..1]
|
|
59
|
+
mod(phi / PI - 0.5, 1.0) // [0..1]
|
|
60
|
+
);
|
|
61
|
+
|
|
62
|
+
// sample using new coordinates
|
|
63
|
+
gl_FragColor = texture2D(u_texture, tc);
|
|
64
|
+
}
|
|
65
|
+
`;class Am{constructor(e,t,i={}){this.videoInitialized=!1,this.lastCameraRotationX=0,this.lastCameraRotationY=0,this.lastCameraRotationT=0,this.lastCameraRotationDX=0,this.lastCameraRotationDY=0,this.mouseDown=!1,this.active=!1,this.container=e,this.sourceVideoElement=t,this.options=i,this.canvas=document.createElement("canvas");const a=this.canvas.getContext("webgl");if(!a)throw new Error("Could not initialize WebGL context");this.gl=a,this.canvas.classList.add("player-scene3d"),this.container.appendChild(this.canvas),this.camera=new ym,this.cameraRotationManager=new Tm(this.camera),this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.textureMappingBuffer=this.createTextureMappingBuffer(),this.updateTextureMappingBuffer(),this.program=this.createProgram(),this.videoTexture=this.createTexture(),this.gl.useProgram(this.program),this.onMouseDownHandlerFn=this.mouseDownHandler.bind(this),this.onMouseMoveHandlerFn=this.mouseMoveHandler.bind(this),this.onMouseUpHandlerFn=this.mouseUpHandler.bind(this),this.mouseLeaveHandlerFn=this.mouseLeaveHandler.bind(this),this.initControls(),this.renderFn=this.render.bind(this)}play(){this.videoInitialized?this.doPlay():this.sourceVideoElement.readyState>=2?(this.videoInitialized=!0,this.doPlay()):this.sourceVideoElement.addEventListener("loadeddata",()=>{this.updateViewportSize(),this.vertexBuffer=this.createVertexBuffer(),this.videoInitialized=!0,this.doPlay()})}stop(){this.active=!1}startCameraRotation(e,t,i){this.cameraRotationManager.setRotationSpeed(e,t,i),this.cameraRotationManager.startRotation()}stopCameraRotation(e=!1){this.cameraRotationManager.stopRotation(e)}destroy(e){this.stop(),this.container.removeEventListener("mousedown",this.onMouseDownHandlerFn),this.container.removeEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.removeEventListener("mouseup",this.onMouseUpHandlerFn),this.canvas.remove(),e==null||e()}doPlay(){this.active=!0,requestAnimationFrame(this.renderFn)}render(e){this.cameraRotationManager.tick(e),this.updateViewportSize(),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.rotation.x,-this.camera.rotation.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(Em,this.gl.VERTEX_SHADER),i=this.createShader($m,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.rotation.x/360,t=.5-this.camera.rotation.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,f=t+a;return[n,o,l,d,u,c,h,f]}updateTextureMappingBuffer(){this.gl.bindBuffer(this.gl.ARRAY_BUFFER,this.textureMappingBuffer),this.gl.bufferData(this.gl.ARRAY_BUFFER,new Float32Array([...this.calculateTexturePosition()]),this.gl.STATIC_DRAW),this.gl.bindBuffer(this.gl.ARRAY_BUFFER,null)}updateViewportSize(){this.frameWidth=this.sourceVideoElement.videoWidth||this.sourceVideoElement.width,this.frameHeight=this.sourceVideoElement.videoHeight||this.sourceVideoElement.height,this.viewportWidth=this.sourceVideoElement.offsetWidth,this.viewportHeight=this.sourceVideoElement.offsetHeight,this.canvas.width=this.viewportWidth,this.canvas.height=this.viewportHeight,this.gl.viewport(0,0,this.canvas.width,this.canvas.height)}initControls(){this.container.addEventListener("mousedown",this.onMouseDownHandlerFn),this.container.addEventListener("mousemove",this.onMouseMoveHandlerFn),this.container.addEventListener("mouseup",this.onMouseUpHandlerFn),this.container.addEventListener("mouseleave",this.mouseLeaveHandlerFn)}mouseDownHandler(e){e.target===this.canvas&&(this.cameraRotationManager.stopRotation(!0),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationT=e.timeStamp,this.mouseDown=!0)}mouseMoveHandler(e){if(this.mouseDown){const t=e.offsetX-this.lastCameraRotationX,i=this.lastCameraRotationY-e.offsetY;this.cameraRotationManager.pointCameraTo(this.camera.rotation.x+t,this.camera.rotation.y+i),this.lastCameraRotationX=e.offsetX,this.lastCameraRotationY=e.offsetY,this.lastCameraRotationDX=t,this.lastCameraRotationDY=i,this.lastCameraRotationT=e.timeStamp}}mouseUpHandler(e){this.mouseDown=!1;const t=e.timeStamp-this.lastCameraRotationT;this.cameraRotationManager.setRotationSpeed(this.lastCameraRotationDX*40/t,this.lastCameraRotationDY*40/t)}mouseLeaveHandler(){this.mouseDown=!1,this.lastCameraRotationX=this.lastCameraRotationY=0}}var J;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(J||(J={}));const km=({id:s,width:e,height:t,bitrate:i,fps:a,quality:n})=>{var o;const l=(o=n?Jt(n):void 0)!==null&&o!==void 0?o:rt({width:e,height:t});return l&&{id:s,quality:l,bitrate:i,size:{width:e,height:t},fps:a}},Pm=({id:s,bitrate:e})=>({id:s,bitrate:e}),wm=(s,e,t)=>{var i;const a=e.indexOf(t);return(i=Ie(s,Math.round(s.length*a/e.length)))!==null&&i!==void 0?i:Ie(s,-1)};class _m{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(J.STOPPED),this.elementSize$=new r.ValueSubject(void 0),this.textTracksManager=new we,this.videoTracks=[],this.audioTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Pf,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(!this.videoState.getTransition()){if(n.state===I.Requested&&(a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&t!==J.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(n.position,n.forcePrecise),i===exports.PlaybackState.STOPPED){t!==J.STOPPED&&(this.videoState.startTransitionTo(J.STOPPED),this.player.stop(),this.video.setAttribute("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),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}switch(t){case J.STOPPED:this.videoState.startTransitionTo(J.READY),this.prepare();return;case J.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(J.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.READY&&A(this.params.desiredState.playbackState,exports.PlaybackState.READY);return;case J.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(J.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case J.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(J.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}}},this.init3DScene=t=>{this.scene3D||(this.scene3D=new Am(this.params.container,this.video,t),this.scene3D.play())},this.destroy3DScene=()=>{this.scene3D&&this.scene3D.destroy(()=>{this.scene3D=null})},this.params=e,this.video=Fe(this.params.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(ne(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new vm({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning,compatibilityMode:this.params.source.compatibilityMode}),this.subscribe()}subscribe(){const{output:e,desiredState:t}=this.params,i=Ue(this.video),a=u=>{e.error$.next({id:"DashVKProvider",category:r.ErrorCategory.WTF,message:"DashVKProvider internal logic error",thrown:u})},n=(u,c)=>this.subscription.add(u.subscribe(c,a));n(i.timeUpdate$,e.position$),n(i.durationChange$,e.duration$),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.isAudioAvailable$,e.isAudioAvailable$),n(this.player.error$,e.error$),n(this.player.lastConnectionType$,e.httpConnectionType$),n(this.player.lastConnectionReused$,e.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(r.filter(r.isNonNullable),r.once(),r.mapTo(void 0)),e.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(e.seekedEvent$,a)),this.subscription.add(nt(this.video,t.isLooped,a)),this.subscription.add(Ve(this.video,t.volume,i.volumeState$,a)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,a)),this.subscription.add(qe(this.video,t.playbackRate,i.playbackRateState$,a)),n(Ri(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe(()=>{this.videoState.setState(J.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},a)).add(i.pause$.subscribe(()=>{this.videoState.setState(J.PAUSED),A(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===ce.MANIFEST_READY){this.videoTracks=[],this.audioTracks=[];const h=this.player.getRepresentations();r.assertNonNullable(h,"Manifest not loaded or empty");const f=Array.from(h.audio).sort((p,v)=>v.bitrate-p.bitrate),m=Array.from(h.video).sort((p,v)=>v.bitrate-p.bitrate);if(!this.params.tuning.isAudioDisabled)for(const p of f){const v=Pm(p);v&&this.audioTracks.push({track:v,representation:p})}for(const p of m){const v=km(p);if(v){this.videoTracks.push({track:v,representation:p});const S=!this.params.tuning.isAudioDisabled&&wm(f,m,p);S&&this.audioRepresentations.set(p.id,S)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map(({track:p})=>p)),this.params.output.availableAudioTracks$.next(this.audioTracks.map(({track:p})=>p)),this.params.output.isAudioAvailable$.next(!!this.audioTracks.length);const b=this.selectVideoRepresentation();r.assertNonNullable(b),this.player.initRepresentations(b.id,(c=this.audioRepresentations.get(b.id))===null||c===void 0?void 0:c.id)}else u===ce.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.stateChangeEnded$,this.elementSize$,r.fromEvent(this.video,"progress")).subscribe(()=>{const u=this.player.state$.getState(),c=this.player.state$.getTransition();if(u!==ce.RUNNING||c||!this.videoTracks.length)return;t.autoVideoTrackSwitching.getTransition()&&t.autoVideoTrackSwitching.setState(t.autoVideoTrackSwitching.getState());const h=this.selectVideoRepresentation();if(h){this.player.switchRepresentation(he.VIDEO,h.id).catch(o);const f=this.audioRepresentations.get(h.id);f&&this.player.switchRepresentation(he.AUDIO,f.id).catch(o)}},a)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(r.filterChanged(),r.map(u=>{var c;return u&&((c=this.videoTracks.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=>{if(u)if(u.is3dVideo)try{this.init3DScene(u),e.is3DVideo$.next(!0)}catch(c){}else this.destroy3DScene(),e.is3DVideo$.next(!1)},a)),this.params.desiredState.cameraRotation.stateChangeEnded$.subscribe(()=>{if(this.scene3D){const u=this.params.desiredState.cameraRotation.getState();u?this.scene3D.startCameraRotation(u.x,u.y,u.z):this.scene3D.stopCameraRotation(!1)}}),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.find(({track:{id:S}})=>S===d))===null||e===void 0?void 0:e.track,c=this.params.output.currentVideoTrack$.getValue(),h=et(this.video.buffered,this.video.currentTime*1e3),f=l?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,m=Math.min(h/Math.min(f,(this.video.duration*1e3||1/0)-this.video.currentTime*1e3),1),b=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),p=Qt(this.videoTracks.map(({track:S})=>S),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),reserve:b,forwardBufferHealth:m,current:c,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),v=l?p!=null?p:u:u!=null?u:p;return v&&((o=this.videoTracks.find(({track:S})=>S===v))===null||o===void 0?void 0:o.representation)}async prepare(){this.player.initManifest(this.video,this.params.source.url)}seek(e,t){this.params.output.willSeekEvent$.next(),this.player.seek(e,t)}destroy(){this.subscription.unsubscribe(),this.destroy3DScene(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(J.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}}const Rm=5e3,Re={};var M;(function(s){s.INITIALIZING="initializing",s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(M||(M={}));const hi=(s,e)=>new r.Observable(t=>{const i=(a,n)=>t.next(n);return s.on(e,i),()=>s.off(e,i)});class Dm{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(M.INITIALIZING),this.textTracksManager=new we,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!==M.INITIALIZING)switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===I.Requested&&this.seek(n.position),i){case exports.PlaybackState.STOPPED:switch(t){case M.STOPPED:break;case M.READY:case M.PLAYING:case M.PAUSED:this.stop();break;default:r.assertNever(t)}break;case exports.PlaybackState.READY:switch(t){case M.STOPPED:this.prepare();break;case M.READY:case M.PLAYING:case M.PAUSED:break;default:r.assertNever(t)}break;case exports.PlaybackState.PLAYING:switch(t){case M.PLAYING:break;case M.STOPPED:this.prepare();break;case M.READY:case M.PAUSED:this.playIfAllowed();break;default:r.assertNever(t)}break;case exports.PlaybackState.PAUSED:switch(t){case M.PAUSED:break;case M.STOPPED:this.prepare();break;case M.READY:this.videoState.setState(M.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case M.PLAYING:this.pause();break;default:r.assertNever(t)}break;default:r.assertNever(i)}},this.video=Fe(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(ne(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.video.remove(),this.params.output.element$.next(void 0)}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"),Rm);import("hls.js/dist/hls.min.js").then(a=>{e||(Re.Hls=a.default,Re.Events=a.default.Events,this.init())},t).finally(()=>{window.clearTimeout(i),e=!0})}init(){r.assertNonNullable(Re.Hls,"hls.js not loaded"),this.hls=new Re.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(M.STOPPED)}subscribe(){r.assertNonNullable(Re.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=Ue(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.isAudioAvailable$,t.isAudioAvailable$),this.subscription.add(nt(this.video,e.isLooped,i)),this.subscription.add(Ve(this.video,e.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(qe(this.video,e.playbackRate,a.playbackRateState$,i)),this.subscription.add(hi(this.hls,Re.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(M.PLAYING),A(e.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(M.PAUSED),A(e.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var u;((u=this.videoState.getTransition())===null||u===void 0?void 0:u.to)===M.READY&&this.videoState.setState(M.READY),this.videoState.getState()===M.PLAYING&&this.playIfAllowed()},i)),n(hi(this.hls,Re.Events.MANIFEST_PARSED).pipe(r.map(({levels:u})=>u.reduce((c,h)=>{var f,m;const b=h.name||h.height.toString(10),{width:p,height:v}=h,S=(m=Jt((f=h.attrs.QUALITY)!==null&&f!==void 0?f:""))!==null&&m!==void 0?m:rt({width:p,height:v});if(!S)return c;const y=h.attrs["FRAME-RATE"]?parseFloat(h.attrs["FRAME-RATE"]):void 0,P={id:b.toString(),quality:S,bitrate:h.bitrate/1e3,size:{width:p,height:v},fps:y};return this.trackLevels.set(b,{track:P,level:h}),c.push(P),c},[]))),t.availableVideoTracks$),n(hi(this.hls,Re.Events.LEVEL_LOADING).pipe(r.map(({url:u})=>ne(u))),t.hostname$),this.subscription.add(ke(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=hi(this.hls,Re.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(ke(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 f=this.hls.levels.indexOf(h),m=this.hls.currentLevel,b=this.hls.levels[m];!b||h.bitrate>b.bitrate?this.hls.nextLevel=f:(this.hls.loadLevel=f,this.hls.loadLevel=f)},{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(M.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}async playIfAllowed(){this.videoState.startTransitionTo(M.PLAYING),await ze(this.video)||(this.videoState.setState(M.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}pause(){this.videoState.startTransitionTo(M.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.setAttribute("src",""),this.video.load(),this.videoState.setState(M.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const _r="X-Playback-Duration";var Rr=async s=>{const e=await gt(s,{method:"HEAD"});return e.headers.has(_r)?parseInt(e.headers.get(_r),10):void 0};const Im=s=>{let e=null;if(s.QUALITY&&(e=Jt(s.QUALITY)),!e&&s.RESOLUTION){const[t,i]=s.RESOLUTION.split("x").map(a=>parseInt(a,10));e=rt({width:t,height:i})}return e!=null?e:null},qn=async(s,e=s)=>{var t;const n=(await(await gt(s)).text()).split(`
|
|
66
|
+
`),o=[];for(let l=0;l<n.length;l++){const u=n[l].match(/^#EXT-X-STREAM-INF:(.+)/);if(!u)continue;const c=Wt(u[1].split(",").map(S=>S.split("="))),h=(t=c.QUALITY)!==null&&t!==void 0?t:`stream-${c.BANDWIDTH}`,f=Im(c);let m;c.BANDWIDTH&&(m=parseInt(c.BANDWIDTH,10)/1e3||void 0),!m&&c["AVERAGE-BANDWIDTH"]&&(m=parseInt(c["AVERAGE-BANDWIDTH"],10)/1e3||void 0);const b=c["FRAME-RATE"]?parseFloat(c["FRAME-RATE"]):void 0;let p;if(c.RESOLUTION){const[S,y]=c.RESOLUTION.split("x").map(P=>parseInt(P,10));S&&y&&(p={width:S,height:y})}const v=new URL(n[++l],e).toString();f&&o.push({id:h,quality:f,url:v,bandwidth:m,size:p,fps:b})}return o};var G;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(G||(G={}));class Nm{constructor(e){var t;this.subscription=new r.Subscription,this.videoState=new W(G.STOPPED),this.textTracksManager=new we,this.manifests$=new r.ValueSubject([]),this.liveOffset=new na,this.manifestStartTime$=new r.ValueSubject(void 0),this.syncPlayback=()=>{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!==G.STOPPED&&(this.videoState.startTransitionTo(G.STOPPED),this.video.setAttribute("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(G.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const c=this.params.desiredState.seekState.getState();if(a===G.STOPPED){this.videoState.startTransitionTo(G.READY),this.prepare();return}if(l||d){const h=this.videoState.getState();this.videoState.setState(G.CHANGING_MANIFEST),this.videoState.startTransitionTo(h),this.prepare(),c.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0});return}if((o==null?void 0:o.to)!==exports.PlaybackState.PAUSED&&c.state===I.Requested){this.videoState.startTransitionTo(G.READY),this.seek(c.position-this.liveOffset.getTotalPausedTime()),this.prepare();return}switch(a){case G.READY:n===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):n===exports.PlaybackState.PAUSED?(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):n===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(G.PLAYING),this.playIfAllowed());return;case G.PLAYING:n===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(G.PAUSED),this.liveOffset.pause(),this.video.pause()):(o==null?void 0:o.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case G.PAUSED:n===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(G.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())):(o==null?void 0:o.to)===exports.PlaybackState.PAUSED&&(A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause());return;case G.CHANGING_MANIFEST:break;default:return r.assertNever(a)}},this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video);const i={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),qn(St(this.params.source.url),this.params.source.url).then(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.availableVideoTracks$.next([]),this.params.output.availableAudioTracks$.next([]),this.params.output.isAudioAvailable$.next(!0),this.params.output.hostname$.next(ne(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)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=Ue(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(t.isLooped.stateChangeStarted$.subscribe(()=>t.isLooped.setState(!1),i)),this.subscription.add(Ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.textTracksManager.connect(this.video,t,e),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(G.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(G.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===G.READY&&this.videoState.setState(G.READY),this.videoState.getState()===G.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 f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===G.CHANGING_MANIFEST&&this.videoState.setState(d.to),l&&l.state===I.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:f})=>({id:d,quality:u,size:c,fps:f,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$,r.observableFrom(["init"])).pipe(r.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(r.isNullable(e))return;const t=St(e.url,this.liveOffset.getTotalOffset());this.video.setAttribute("src",t),this.video.load(),Rr(t).then(i=>{var a;if(!r.isNullable(i))this.maxSeekBackTime$.next(i);else{const n=(a=this.params.source.maxSeekBackTime)!==null&&a!==void 0?a:this.maxSeekBackTime$.getValue();if(r.isNullable(n)||!isFinite(n))try{gt(t).then(o=>o.text()).then(o=>{var l;const d=(l=/#EXT-X-STREAM-INF[^\n]+\n(.+)/m.exec(o))===null||l===void 0?void 0:l[1];if(d){const u=new URL(d,t).toString();Rr(u).then(c=>{r.isNullable(c)||this.maxSeekBackTime$.next(c)})}})}catch(o){}}})}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(G.PAUSED),this.liveOffset.pause(),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}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 z;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.CHANGING_MANIFEST="changing_manifest",s.PAUSED="paused"})(z||(z={}));class Cm{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(z.STOPPED),this.textTracksManager=new we,this.manifests$=new r.ValueSubject([]),this.syncPlayback=()=>{const i=this.videoState.getState(),a=this.params.desiredState.playbackState.getState(),n=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(a===exports.PlaybackState.STOPPED){i!==z.STOPPED&&(this.videoState.startTransitionTo(z.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(z.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const u=this.params.desiredState.seekState.getState();if(i===z.STOPPED){this.videoState.startTransitionTo(z.READY),this.prepare();return}if(o||l){const c=this.videoState.getState();this.videoState.setState(z.CHANGING_MANIFEST),this.videoState.startTransitionTo(c);const{currentTime:h}=this.video;this.prepare(),u.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:h*1e3,forcePrecise:!0});return}switch((n==null?void 0:n.to)!==exports.PlaybackState.PAUSED&&u.state===I.Requested&&this.seek(u.position),i){case z.READY:a===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):a===exports.PlaybackState.PAUSED?(this.videoState.setState(z.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):a===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed());return;case z.PLAYING:a===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(z.PAUSED),this.video.pause()):(n==null?void 0:n.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case z.PAUSED:a===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(z.PLAYING),this.playIfAllowed()):(n==null?void 0:n.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;case z.CHANGING_MANIFEST:break;default:return r.assertNever(i)}},this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video);const t={id:"master",quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([t]),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(ne(this.params.source.url)),qn(this.params.source.url).then(i=>{this.manifests$.next([t,...i])},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)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=Ue(this.video),n=(l,d)=>this.subscription.add(l.subscribe(d));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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(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),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(z.PAUSED),A(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).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 f=this.manifests$.getValue().find(m=>m.id===h);f&&(this.params.output.currentVideoTrack$.next(f),this.params.output.hostname$.next(ne(f.url)))}c&&this.params.desiredState.autoVideoTrackSwitching.setState(c.to),d&&d.from===z.CHANGING_MANIFEST&&this.videoState.setState(d.to),l.state===I.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:f})=>({id:d,quality:u,size:c,fps:f,bitrate:h})))).subscribe(this.params.output.availableVideoTracks$,i));const o=r.merge(t.playbackState.stateChangeStarted$,t.seekState.stateChangeEnded$,t.videoTrack.stateChangeStarted$,t.autoVideoTrackSwitching.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.video.remove(),this.params.output.element$.next(void 0)}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(z.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}var K;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(K||(K={}));class xm{constructor(e){this.subscription=new r.Subscription,this.videoState=new W(K.STOPPED),this.trackUrls={},this.textTracksManager=new we,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!==K.STOPPED&&(this.videoState.startTransitionTo(K.STOPPED),this.video.setAttribute("src",""),this.video.load(),this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.videoState.setState(K.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition(),l=this.params.desiredState.seekState.getState();if(t===K.STOPPED){this.videoState.startTransitionTo(K.READY),this.prepare();return}if(o){const{currentTime:d}=this.video;this.prepare(),l.state===I.None&&this.params.desiredState.seekState.setState({state:I.Requested,position:d*1e3,forcePrecise:!0});return}switch((a==null?void 0:a.to)!==exports.PlaybackState.PAUSED&&l.state===I.Requested&&this.seek(l.position),t){case K.READY:i===exports.PlaybackState.READY?A(this.params.desiredState.playbackState,exports.PlaybackState.READY):i===exports.PlaybackState.PAUSED?(this.videoState.setState(K.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed());return;case K.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(K.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case K.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(K.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);return;default:return r.assertNever(t)}},this.params=e,this.video=Fe(e.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).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.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=Ue(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.isAudioAvailable$,e.isAudioAvailable$),this.subscription.add(nt(this.video,t.isLooped,i)),this.subscription.add(Ve(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(qe(this.video,t.playbackRate,a.playbackRateState$,i)),this.subscription.add(a.playing$.subscribe(()=>{this.videoState.setState(K.PLAYING),A(t.playbackState,exports.PlaybackState.PLAYING)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(K.PAUSED),A(t.playbackState,exports.PlaybackState.PAUSED)},i)).add(a.canplay$.subscribe(()=>{var l;((l=this.videoState.getTransition())===null||l===void 0?void 0:l.to)===K.READY&&this.videoState.setState(K.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()===K.PLAYING&&this.playIfAllowed()},i)),this.textTracksManager.connect(this.video,t,e);const o=r.merge(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,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.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,t;const i=(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();r.assertNonNullable(i,"MpegProvider: track is not selected");let{url:a}=this.trackUrls[i];r.assertNonNullable(a,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(a=yt(a)),this.video.setAttribute("src",a),this.video.load(),this.params.output.hostname$.next(ne(a))}playIfAllowed(){ze(this.video).then(e=>{e||(this.videoState.setState(K.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}seek(e){this.params.output.willSeekEvent$.next(),this.video.currentTime=e/1e3}}const Dr=["stun:videostun.mycdn.me:80"],Lm=1e3,Om=3,Ts=()=>null;class Bm{constructor(e,t){this.ws=null,this.peerConnection=null,this.serverUrl="",this.streamKey="",this.stream=null,this.signalingType="JOIN",this.retryCount=0,this.externalStartCallback=Ts,this.externalStopCallback=Ts,this.externalErrorCallback=Ts,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:Dr}]};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),Lm)}normalizeOptions(e={}){const t={stunServerList:Dr,maxRetryNumber:Om,errorChanel:null};return e.stunServerList&&(t.stunServerList=e.stunServerList),e.maxRetryNumber&&e.maxRetryNumber>0&&(t.maxRetryNumber=e.maxRetryNumber),t}}var Y;(function(s){s.STOPPED="stopped",s.READY="ready",s.PLAYING="playing",s.PAUSED="paused"})(Y||(Y={}));class Mm{constructor(e){this.videoState=new W(Y.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!==Y.STOPPED&&(this.videoState.startTransitionTo(Y.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(Y.STOPPED),A(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0));return}if(this.videoState.getTransition())return;const o=this.params.desiredState.videoTrack.getTransition();if(t===Y.STOPPED){this.videoState.startTransitionTo(Y.READY),this.prepare();return}if(o){this.prepare();return}switch(t){case Y.READY:i===exports.PlaybackState.PAUSED?(this.videoState.setState(Y.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed());return;case Y.PLAYING:i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Y.PAUSED),this.video.pause()):(a==null?void 0:a.to)===exports.PlaybackState.PLAYING&&A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING);return;case Y.PAUSED:i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Y.PLAYING),this.playIfAllowed()):(a==null?void 0:a.to)===exports.PlaybackState.PAUSED&&A(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=Fe(e.container),this.liveStreamClient=new Bm(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.video.remove(),this.params.output.element$.next(void 0),this.liveStreamClient.disconnect()}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=Ue(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$),n(a.isAudioAvailable$,e.isAudioAvailable$),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)===Y.READY&&this.videoState.setState(Y.READY)},i)).add(a.pause$.subscribe(()=>{this.videoState.setState(Y.PAUSED)},i)).add(a.playing$.subscribe(()=>{this.videoState.setState(Y.PLAYING)},i)).add(a.error$.subscribe(e.error$)).add(this.maxSeekBackTime$.subscribe(this.params.output.duration$)).add(Ve(this.video,t.volume,a.volumeState$,i)).add(a.volumeState$.subscribe(e.volume$,i)).add(this.videoState.stateChangeEnded$.subscribe(o=>{switch(o.to){case Y.STOPPED:e.position$.next(0),e.duration$.next(0),t.playbackState.setState(exports.PlaybackState.STOPPED);break;case Y.READY:break;case Y.PAUSED:t.playbackState.setState(exports.PlaybackState.PAUSED);break;case Y.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.hostname$.next(ne(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:exports.VideoQuality.INVARIANT}),this.video.srcObject=e,A(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}onLiveStreamStop(){this.videoState.startTransitionTo(Y.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(Y.PAUSED),A(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))})}prepare(){this.liveStreamClient.connect()}}class Ir{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 Boolean(this.current.done)}}var Vm=()=>{var s,e;const t=window.navigator;return t.userAgentData?((e=(s=t.userAgentData)===null||s===void 0?void 0:s.platform)===null||e===void 0?void 0:e.toLowerCase())==="android":window.navigator.userAgent.toLowerCase().includes("android")},Es,$s,As,ks,Ps,ws,fi,_s,pi,Rs,mi,Ds,bi,Is,vi,Ns;const zn=Vm(),je=document.createElement("video"),De={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(($s=(Es=window.SourceBuffer)===null||Es===void 0?void 0:Es.prototype)===null||$s===void 0?void 0:$s.appendBuffer)),hls:Boolean(((As=je.canPlayType)===null||As===void 0?void 0:As.call(je,"application/x-mpegurl"))||((ks=je.canPlayType)===null||ks===void 0?void 0:ks.call(je,"vnd.apple.mpegURL"))),webrtc:Boolean(window.RTCPeerConnection)},de={mp4:Boolean((Ps=je.canPlayType)===null||Ps===void 0?void 0:Ps.call(je,"video/mp4")),webm:Boolean((ws=je.canPlayType)===null||ws===void 0?void 0:ws.call(je,"video/webm")),cmaf:!0},Ge={h264:Boolean((_s=(fi=window.MediaSource)===null||fi===void 0?void 0:fi.isTypeSupported)===null||_s===void 0?void 0:_s.call(fi,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean((Rs=(pi=window.MediaSource)===null||pi===void 0?void 0:pi.isTypeSupported)===null||Rs===void 0?void 0:Rs.call(pi,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean((Ds=(mi=window.MediaSource)===null||mi===void 0?void 0:mi.isTypeSupported)===null||Ds===void 0?void 0:Ds.call(mi,'video/webm; codecs="vp9"')),aac:Boolean((Is=(bi=window.MediaSource)===null||bi===void 0?void 0:bi.isTypeSupported)===null||Is===void 0?void 0:Is.call(bi,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean((Ns=(vi=window.MediaSource)===null||vi===void 0?void 0:vi.isTypeSupported)===null||Ns===void 0?void 0:Ns.call(vi,'audio/webm; codecs="opus"'))},pt=(Ge.h264||Ge.h265)&&Ge.aac,Gi=De.hls&&de.mp4,Fm=Boolean(window.WebSocket),Um=()=>Object.keys(Ge).filter(s=>Ge[s]),Hm=(s,e=!1)=>s.filter(t=>{switch(t){case exports.VideoFormat.DASH:return De.mse&&de.mp4&&pt;case exports.VideoFormat.DASH_SEP:return De.mse&&de.mp4&&pt;case exports.VideoFormat.DASH_WEBM:return De.mse&&de.webm&&Ge.vp9&&Ge.opus;case exports.VideoFormat.DASH_LIVE:return De.mse&&de.mp4&&pt;case exports.VideoFormat.DASH_LIVE_CMAF:return De.mse&&de.mp4&&pt&&de.cmaf;case exports.VideoFormat.DASH_ONDEMAND:return De.mse&&de.mp4&&pt;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_LIVE_CMAF:case exports.VideoFormat.HLS_ONDEMAND:return Gi||e&&De.mse&&de.mp4&&pt;case exports.VideoFormat.MPEG:return de.mp4;case exports.VideoFormat.DASH_LIVE_WEBM:return!1;case exports.VideoFormat.WEB_RTC_LIVE:return De.webrtc&&Fm&&Ge.h264&&(de.mp4||de.webm);default:return r.assertNever(t)}}),jm=()=>zn?[exports.VideoFormat.MPEG,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND]:Gi?[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG,exports.VideoFormat.DASH]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],Gm=()=>zn?[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:Gi?[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF]:[exports.VideoFormat.WEB_RTC_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_CMAF,exports.VideoFormat.HLS_LIVE,exports.VideoFormat.HLS_LIVE_CMAF],Nr=s=>s?[exports.VideoFormat.HLS_LIVE]:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG];var Ym=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$,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="provider change",l=0})),t.add(n.subscribe(()=>{l&&(window.clearTimeout(l),l=window.setTimeout(()=>o.next(d),s.maxTransitionInterval))})),t.add(o.subscribe(e)),()=>{window.clearTimeout(l),t.unsubscribe()}});const Cr={maxPlaybackTransitionInterval:2e4,providerErrorLimit:3},qm={cacheDuration:12e4},zm={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Wm={maxPausedTime:3e4},xr={maxPausedTime:3e4};class Qm{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),currentBuffer$:new r.ValueSubject(void 0),isBuffering$:new r.ValueSubject(!0),error$: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),liveTime$: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),element$: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=Hm([...Gm(),...jm()],this.params.tuning.useHlsJs).filter(o=>r.isNonNullable(e.sources[o])),{formatsToAvoid:i}=this.params.tuning,a=i.length?[...t.filter(o=>!i.includes(o)),...t.filter(o=>i.includes(o))]:t;this.screenFormatsIterator=new Ir(a);const n=[...Nr(!0),...Nr(!1)];this.chromecastFormatsIterator=new Ir(n.filter(o=>r.isNonNullable(e.sources[o])))}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.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider(),this.failoverIndex=void 0;const e=this.current$.getValue().destination;r.assertNonNullable(e,"No current provider"),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!==I.None;this.params.desiredState.seekState.setState({state:I.Requested,position:a?i.position:t,forcePrecise:a?i.forcePrecise:!1}),e.destroy();const n=this.providerOutput.isBuffering$;n.getValue()||n.next(!0)}createProvider(e,t){switch(this.log({message:`createProvider: ${e}:${t}`}),e){case le.SCREEN:return this.createScreenProvider(t);case le.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 Qf({...o,source:l,config:qm})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),this.params.tuning.useDashJs?new mr({...o,source:l,format:e,config:xr}):new _m({...o,source:l})}case exports.VideoFormat.DASH_LIVE_CMAF:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new mr({...o,source:l,format:e,config:xr})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),Gi||!this.params.tuning.useHlsJs?new Cm({...o,source:l}):new Dm({...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 Nm({...o,source:l,config:Wm})}case exports.VideoFormat.MPEG:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new xm({...o,source:l})}case exports.VideoFormat.DASH_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Gf({...o,source:l,config:zm})}case exports.VideoFormat.WEB_RTC_LIVE:{const l=this.applyFailoverHost(t[e]);return r.assertNonNullable(l),new Mm({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 Jh({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()?le.CHROMECAST:le.SCREEN}chooseFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case le.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return r.assertNever(e)}}skipFormat(e){switch(e){case le.SCREEN:return this.screenFormatsIterator.next();case le.CHROMECAST:return this.chromecastFormatsIterator.next();default:return r.assertNever(e)}}handleNoFormatsError(e){switch(e){case le.SCREEN:this.noAvailableProvidersError$.next(),this.current$.next({type:void 0});return;case le.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 Wt(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$,Ym({desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Cr.maxPlaybackTransitionInterval,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(r.filter(({type:a})=>a!==void 0))}).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=>{if(this.current$.getValue().destination===le.CHROMECAST)this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then(()=>this.switchToNextProvider(),()=>this.params.dependencies.chromecastInitializer.disconnect());else{const n=a.category===r.ErrorCategory.NETWORK,o=this.params.failoverHosts.length>0&&(this.failoverIndex===void 0||this.failoverIndex<this.params.failoverHosts.length-1),l=i<Cr.providerErrorLimit;o&&(n&&t||!l)?(this.failoverIndex=this.failoverIndex===void 0?0:this.failoverIndex+1,this.reinitProvider()):l?(i++,this.reinitProvider()):this.switchToNextProvider()}})),e}}var pe;(function(s){s[s.LOCAL_STORAGE=0]="LOCAL_STORAGE",s[s.SESSION_STORAGE=1]="SESSION_STORAGE",s[s.RUNTIME=2]="RUNTIME"})(pe||(pe={}));const Wn=new Map;let it=pe.RUNTIME;const Cs=`vk-videoplayer-dummy-key-${Math.random()}`,Jm=()=>{try{localStorage.setItem(Cs,"test"),localStorage.removeItem(Cs),it=pe.LOCAL_STORAGE}catch(s){if(s instanceof DOMException||s instanceof TypeError)try{sessionStorage.getItem(Cs),it=pe.SESSION_STORAGE}catch(e){if(e instanceof DOMException||e instanceof TypeError)it=pe.RUNTIME;else throw e}else throw s}};Jm();const Km=s=>{var e,t;switch(it){case pe.LOCAL_STORAGE:return(e=localStorage.getItem(s))!==null&&e!==void 0?e:void 0;case pe.SESSION_STORAGE:return(t=sessionStorage.getItem(s))!==null&&t!==void 0?t:void 0;case pe.RUNTIME:return Wn.get(s);default:r.assertNever(it)}},Lr=(s,e)=>{switch(it){case pe.LOCAL_STORAGE:try{localStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.SESSION_STORAGE:try{sessionStorage.setItem(s,e)}catch(t){if(t instanceof DOMException)console.error(t);else throw t}break;case pe.RUNTIME:return void Wn.set(s,e);default:r.assertNever(it)}},Ys=(s,e,t)=>t*e+(1-t)*s,Qn=(s,e)=>s.reduce((t,i)=>t+i,0)/e,Xm=(s,e,t,i)=>{let a=0,n=t;const o=Qn(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 Jn{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 $e(`raw_${i}`),this.smoothedSeries$=new $e(`smoothed_${i}`),this.reportedSeries$=new $e(`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 Zm extends Jn{constructor(e){super(e),this.slow=this.fast=e.initial}updateSmoothedValue(e){this.slow=Ys(this.slow,e,this.params.emaAlphaSlow),this.fast=Ys(this.fast,e,this.params.emaAlphaFast);const t=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=t(this.slow,this.fast)}}class eb extends Jn{constructor(e){super(e),this.emaSmoothed=e.initial}updateSmoothedValue(e){const t=Qn(this.pastMeasures,this.takenMeasures);this.emaSmoothed=Ys(this.emaSmoothed,e,this.params.emaAlpha);const i=Xm(this.pastMeasures,this.takenMeasures,this.measuresCursor-1,this.params.basisTrendChangeCount);this.smoothed=i?this.emaSmoothed:t}}class Or{static getSmoothedValue(e,t,i){return i.type==="TwoEma"?new Zm({initial:e,emaAlphaSlow:i.emaAlphaSlow,emaAlphaFast:i.emaAlphaFast,changeThreshold:i.changeThreshold,fastDirection:t,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"}):new eb({initial:e,emaAlpha:i.emaAlpha,basisTrendChangeCount:i.basisTrendChangeCount,changeThreshold:i.changeThreshold,deviationDepth:i.deviationDepth,deviationFactor:i.deviationFactor,label:"throughput"})}}const tb=5e3,Br="one_video_throughput",Mr="one_video_rtt",xe=window.navigator.connection,Vr=()=>{const s=xe==null?void 0:xe.downlink;if(r.isNonNullable(s)&&s!==10)return s*1e3},Fr=()=>{const s=xe==null?void 0:xe.rtt;if(r.isNonNullable(s)&&s!==3e3)return s},Ur=(s,e,t)=>{const i=t*8,a=i/s;return i/(a+e)};class jt{constructor(e){var t,i;this.subscription=new r.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const a=jt.load(Br)||(e.useBrowserEstimation?Vr():void 0)||tb,n=(i=(t=jt.load(Mr))!==null&&t!==void 0?t:e.useBrowserEstimation?Fr():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(Ur(a,n,e.rttPenaltyRequestSize)),this.throughput=Or.getSmoothedValue(a,-1,e),this.rtt=Or.getSmoothedValue(n,1,e),e.useBrowserEstimation){const o=()=>{const d=Vr();d&&this.throughput.next(d);const u=Fr();r.isNonNullable(u)&&this.rtt.next(u)};xe&&"onchange"in xe&&this.subscription.add(r.fromEvent(xe,"change").subscribe(o)),o()}this.subscription.add(this.throughput.smoothed$.subscribe(o=>{Lr(Br,o.toFixed(0))})),this.subscription.add(this.rtt.smoothed$.subscribe(o=>{Lr(Mr,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})=>Ur(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(jt.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=Km(e);if(r.isNonNullable(i))return(t=parseInt(i,10))!==null&&t!==void 0?t:void 0}}const Hr={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},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},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3*1e3,random:.1},enableWakeLock:!0,enableTelemetryAtStart:!1,formatsToAvoid:[],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,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,useHlsJs:!0,isAudioDisabled:!1,webrtc:{connectionRetryMaxNumber:3}},ib=s=>{const e={};for(const t of Object.keys(Hr)){const i=Hr[t],a=s[t];Array.isArray(i)&&Array.isArray(a)?e[t]=a:typeof i=="object"&&typeof a=="object"?e[t]={...i,...a}:e[t]=a!=null?a:i}return e};var sb=({seekState:s,position$:e})=>r.merge(s.stateChangeEnded$.pipe(r.map(({to:t})=>{var i;return t.state===I.None?void 0:((i=t.position)!==null&&i!==void 0?i:NaN)/1e3}),r.filter(r.isNonNullable)),e.pipe(r.filter(()=>s.getState().state===I.None))),ab=s=>{const e=typeof s.container=="string"?document.getElementById(s.container):s.container;return r.assertNonNullable(e,`Wrong container or containerId {${s.container}}`),e};const jr=({playbackState:s,seekState:e,playbackAbort$:t,looped$:i,position$:a})=>new r.Observable(n=>{let o;const l=s.transitionEnded$.pipe(r.filter(m=>(m.from===exports.PlaybackState.PAUSED||m.from===exports.PlaybackState.STOPPED)&&m.to===exports.PlaybackState.PLAYING)),d=s.stateChangeEnded$.pipe(r.filter(m=>m.from===exports.PlaybackState.PLAYING&&m.to===exports.PlaybackState.PAUSED)),u=e.stateChangeEnded$.pipe(r.filter(({to:m})=>{var b,p;return m.state===I.Requested&&((p=(b=s.getTransition())===null||b===void 0?void 0:b.from)!==null&&p!==void 0?p:s.getState())===exports.PlaybackState.PLAYING})),c=e.stateChangeEnded$.pipe(r.filter(({from:m,to:b})=>{var p,v;return m.state===I.Applying&&b.state===I.None&&((v=(p=s.getTransition())===null||p===void 0?void 0:p.from)!==null&&v!==void 0?v:s.getState())===exports.PlaybackState.PLAYING})),h=r.merge(l,c).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable)),f=r.merge(r.merge(d,u,t),i).pipe(r.map(()=>a.getValue()),r.filter(r.isNonNullable));return new r.Subscription().add(h.subscribe(m=>{o=m})).add(f.subscribe(m=>{if(r.isNullable(o)||o===m)return;const b={from:o,to:m};o=void 0,n.next(b)}))});class rb{constructor(e={}){if(this.subscription=new r.Subscription,this.logger=new r.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new W(exports.PlaybackState.STOPPED),seekState:new W({state:I.None}),volume:new W({volume:1,muted:!1}),videoTrack:new W(void 0),autoVideoTrackSwitching:new W(!1),autoVideoTrackLimits:new W({}),isLooped:new W(!1),playbackRate:new W(1),externalTextTracks:new W([]),currentTextTrack:new W(void 0),textTrackCuesSettings:new W({}),cameraRotation:new W(!1)},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),liveTime$: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),chromecastState$:new r.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new r.ValueSubject(void 0),intrinsicVideoSize$:new r.ValueSubject(void 0),is3DVideo$:new r.ValueSubject(!1)},this.events={inited$:new r.Subject,started$:new r.Subject,willPause$:new r.Subject,willResume$: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),enableDebugTelemetry$:new r.ValueSubject(!1),dumpTelemetry:$f},this.initLogs(),this.tuning=ib(e),this.chromecastInitializer=new Po({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new jt(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,(f,m)=>{const b=typeof m;return["number","string","boolean"].includes(b)?m:m===null?null:`<${b}>`})),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=ab(e),this.chromecastInitializer.contentId=(t=e.meta)===null||t===void 0?void 0:t.videoId,this.providerContainer=new Qm({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},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(),(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=this.desiredState.playbackState;return e.getState()!==exports.PlaybackState.PLAYING&&e.startTransitionTo(exports.PlaybackState.PLAYING),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){return this.events.willSeek$.next({from:this.getExactTime(),to:e}),this.desiredState.seekState.setState({state:I.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.setState(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;return(e===void 0||!((t=this.providerContainer)===null||t===void 0)&&t.providerOutput.availableTextTracks$.getValue().find(i=>i.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()}startCameraRotation(e,t){return this.desiredState.cameraRotation.setState({x:e,y:t,z:0}),this}stopCameraRotation(){return this.desiredState.cameraRotation.setState(!1),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===I.None?void 0:t.position;return r.isNonNullable(i)?i/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}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$.pipe(r.filter(()=>!this.isPlaybackStarted),r.filter(e=>e.to===exports.PlaybackState.PLAYING)).subscribe(()=>{this.isPlaybackStarted=!0,this.events.started$.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();break}}))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe(()=>{const d=this.desiredState.seekState.getState();d.state===I.Requested?this.desiredState.seekState.setState({...d,state:I.Applying}):this.events.managedError$.next({id:`WillSeekIn${d.state}`,category:r.ErrorCategory.WTF,message:"Received unexpeceted willSeek$"})})).add(e.providerOutput.seekedEvent$.subscribe(()=>{this.desiredState.seekState.getState().state===I.Applying&&(this.desiredState.seekState.setState({state:I.None}),this.events.seeked$.next())})).add(e.current$.pipe(r.map(d=>d.type)).subscribe(this.info.currentFormat$)).add(e.current$.pipe(r.map(d=>d.destination),r.filterChanged()).subscribe(()=>{this.isPlaybackStarted=!1})).add(e.providerOutput.availableVideoTracks$.pipe(r.map(d=>d.map(({quality:u})=>u).sort((u,c)=>wi(u)?1:wi(c)?-1:Ti(c,u)?1:-1))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe(d=>{const u={};for(const c of d)c.fps&&(u[c.quality]=c.fps);this.info.availableQualitiesFps$.next(u)})).add(e.providerOutput.availableAudioTracks$.subscribe(this.info.availableAudioTracks$)).add(e.providerOutput.isAudioAvailable$.subscribe(this.info.isAudioAvailable$)).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{this.info.currentQuality$.next(d==null?void 0:d.quality),this.info.videoBitrate$.next(d==null?void 0:d.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.currentBuffer$.pipe(r.map(d=>d?{start:d.from,end:d.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.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.muted),r.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(r.map(d=>d.volume),r.filterChanged()).subscribe(this.info.volume$)).add(sb({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(d=>({id:"NoProviders",category:r.ErrorCategory.VIDEO_PIPELINE,message:"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(()=>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$));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:d})=>d===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 d=e.providerOutput.isBuffering$.getValue(),u=t.getValue()||i.getValue();return d&&!u}),r.filterChanged());this.subscription.add(n.subscribe(d=>{d?a=window.setTimeout(()=>this.info.isStalled$.next(!0),this.tuning.stallIgnoreThreshold):(window.clearTimeout(a),this.info.isStalled$.next(!1))}));const o=new r.Subscription;this.subscription.add(o);const l=r.merge(r.fromEvent(window,"beforeunload"),this.events.willDestruct$,e.current$.pipe(r.filter(d=>Boolean(d==null?void 0:d.provider))));e.providerOutput.isLive$.pipe(r.filterChanged()).subscribe(d=>{switch(r.assertNonNullable(this.providerContainer),o.unsubscribe(),d){case!0:{const u=new r.ValueSubject(void 0);o.add(this.providerContainer.providerOutput.liveTime$.subscribe(c=>u.next(c&&Math.floor(c/1e3)))),o.add(jr({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:l,looped$:this.events.looped$,position$:u}).pipe(r.map(({from:c,to:h})=>({start:c,end:h}))).subscribe(this.events.watchCoverageLive$));break}case!1:o.add(jr({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:l,position$:this.providerContainer.providerOutput.position$}).pipe(r.map(({from:u,to:c})=>({start:u,end:c}))).subscribe(this.events.watchCoverageRecord$));break}}),this.subscription.add(r.merge(e.providerOutput.canplay$,e.providerOutput.firstFrameEvent$,e.providerOutput.firstBytesEvent$).subscribe(()=>{const d=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:d==null?void 0:d.videoWidth,height:d==null?void 0:d.videoHeight})})).add(e.providerOutput.currentVideoTrack$.subscribe(d=>{var u,c;const h=e.providerOutput.element$.getValue();this.setIntrinsicVideoSize({width:(u=d==null?void 0:d.size)===null||u===void 0?void 0:u.width,height:(c=d==null?void 0:d.size)===null||c===void 0?void 0:c.height},{width:h==null?void 0:h.videoWidth,height:h==null?void 0:h.videoHeight})})).add(e.providerOutput.is3DVideo$.subscribe(d=>{this.info.is3DVideo$.next(d)}))}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=Qt(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})),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),Ef(),this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe(i=>Tf(i)),this.providerContainer.current$.subscribe(({type:i})=>ui("provider",i)),t.duration$.subscribe(i=>ui("duration",i)),t.availableVideoTracks$.pipe(r.filter(i=>!!i.length),r.once()).subscribe(i=>ui("tracks",i)),this.events.fatalError$.subscribe(new $e("fatalError")),this.events.managedError$.subscribe(new $e("managedError")),t.position$.subscribe(new $e("position")),t.currentVideoTrack$.pipe(r.map(i=>i==null?void 0:i.quality)).subscribe(new $e("quality")),this.info.currentBuffer$.subscribe(new $e("buffer")),t.isBuffering$.subscribe(new $e("isBuffering"))].forEach(i=>this.subscription.add(i)),ui("codecs",Um())}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=>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.transitionEnded$).subscribe(()=>{const a=document.visibilityState==="visible",n=this.desiredState.playbackState.getState()===exports.PlaybackState.PLAYING,o=Boolean(e)&&!(e!=null&&e.released);a&&n?o||i():t()})).add(this.events.willDestruct$.subscribe(t))}}const nb=`${Ao}@${$o}`;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}});exports.Player=rb;exports.SDK_VERSION=nb;
|