@vkontakte/videoplayer-core 2.0.65 → 2.0.67

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.
Files changed (42) hide show
  1. package/es2015.cjs.js +4 -4
  2. package/es2015.esm.js +4 -4
  3. package/es2018.cjs.js +4 -4
  4. package/es2018.esm.js +4 -4
  5. package/esnext.cjs.js +4 -4
  6. package/esnext.esm.js +4 -4
  7. package/package.json +29 -4
  8. package/packages/{sdk → core}/src/providers/ChromecastProvider/ChromecastInitializer/types.d.ts +0 -0
  9. package/packages/{sdk → core}/src/providers/DashIFProvider/dashjsTypes.d.ts +0 -0
  10. package/packages/{sdk → core}/src/providers/DashLiveProvider/types.d.ts +0 -0
  11. package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/FilesFetcher.d.ts +0 -0
  12. package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -0
  13. package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/ThroughputEstimator.d.ts +0 -0
  14. package/packages/{sdk → core}/src/providers/DashLiveProvider/utils/liveDashPlayerUtil.d.ts +0 -0
  15. package/packages/{sdk → core}/src/providers/DashProvider/types.d.ts +0 -0
  16. package/packages/{sdk → core}/src/providers/DashProvider/utils/DashLite.d.ts +0 -0
  17. package/packages/{sdk → core}/src/providers/DashProvider/utils/stream.d.ts +0 -0
  18. package/packages/{sdk → core}/src/providers/DashProvider/utils/xhr2.d.ts +0 -0
  19. package/packages/{sdk → core}/src/providers/DashVKProvider/lib/buffer.d.ts +0 -0
  20. package/packages/{sdk → core}/src/providers/DashVKProvider/lib/ebml.d.ts +0 -0
  21. package/packages/{sdk → core}/src/providers/DashVKProvider/lib/fetcher.d.ts +0 -0
  22. package/packages/{sdk → core}/src/providers/DashVKProvider/lib/isobmff.d.ts +0 -0
  23. package/packages/{sdk → core}/src/providers/DashVKProvider/lib/mpd.d.ts +0 -0
  24. package/packages/{sdk → core}/src/providers/DashVKProvider/lib/sourceBufferTaskQueue.d.ts +1 -1
  25. package/packages/{sdk → core}/src/providers/DashVKProvider/lib/webm.d.ts +0 -0
  26. package/packages/{sdk → core}/src/providers/ProviderContainer/types.d.ts +0 -0
  27. package/packages/{sdk → core}/src/providers/types.d.ts +0 -0
  28. package/packages/{sdk → core}/src/providers/utils/LiveOffset/types.d.ts +0 -0
  29. package/packages/{sdk → core}/src/utils/StateMachine/types.d.ts +0 -0
  30. package/packages/{sdk → core}/src/utils/StatefulIterator/StatefulIterator.spec.d.ts +0 -0
  31. package/packages/{sdk → core}/src/utils/buffer/getTotalBufferDuration.d.ts +0 -0
  32. package/packages/{sdk → core}/src/utils/buffer/isPositionBuffered.d.ts +0 -0
  33. package/packages/{sdk → core}/src/utils/buffer/types.d.ts +0 -0
  34. package/packages/{sdk → core}/src/utils/link.d.ts +0 -0
  35. package/packages/{sdk → core}/src/utils/quality/quality.spec.d.ts +0 -0
  36. package/player/Player.d.ts +1 -1
  37. package/player/utils/optimisticPosition.d.ts +1 -1
  38. package/providers/utils/forcePlay.d.ts +1 -1
  39. package/providers/utils/syncDesiredState.d.ts +2 -2
  40. package/providers/DashLiveProvider/utils/LiveDashPlayer.d.ts +0 -135
  41. package/providers/DashProvider/utils/DashLite.d.ts +0 -60
  42. package/utils/buffer/isPositionBuffered.d.ts +0 -3
package/es2015.esm.js CHANGED
@@ -1,6 +1,6 @@
1
1
  /**
2
- * @vkontakte/videoplayer-core v2.0.65
3
- * Wed, 17 Aug 2022 17:42:01 GMT
4
- * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-65/doc/
2
+ * @vkontakte/videoplayer-core v2.0.67
3
+ * Tue, 30 Aug 2022 15:03:08 GMT
4
+ * https://st.mycdn.me/static/vkontakte-videoplayer/2-0-67/doc/
5
5
  */
6
- import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as r,fromEvent as a,assertNever as n,merge as o,tap as d,map as u,observableFrom as h,filterChanged as c,assertNonNullable as l,debounce as p,timeout as f,filter as m,mapTo as v,now as g,Observable as S,once as b,combine as y,abortable as T,getExponentialDelay as E,interval as w,throttle as $,Logger as k}from'@vkontakte/videoplayer-shared/es2015.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/es2015.esm.js';import A from'lodash/debounce';var P,D,_,R,I,L,x;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND_VK',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(D||(D={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(_||(_={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(R||(R={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(I||(I={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(L||(L={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(x||(x={}));class C{constructor(r){var a;this.connection$=new t(void 0),this.castState$=new t(R.NOT_AVAILABLE),this.errorEvent$=new e,this.realCastState$=new t(R.NOT_AVAILABLE),this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const n='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${n}`}),r.isDisabled||!n)return;var o;s(null===(a=window.chrome)||void 0===a?void 0:a.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(o='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();r(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();r(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(a(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{var e,s;switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(s=null===(e=i.getCurrentSession())||void 0===e?void 0:e.getMediaSession())||void 0===s?void 0:s.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 n(t.sessionState)}}))).add(o(a(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),h([i.getCastState()])).pipe(c(),u(O),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var n;const o=a===R.CONNECTED,d=s(this.connection$.getValue());if(o&&!d){const s=i.getCurrentSession();l(s);const a=s.getCastDevice(),o=null===(n=s.getMediaSession())||void 0===n?void 0:n.media.contentId;(r(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!o&&d&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===R.CONNECTED?s(this.connection$.getValue())?R.CONNECTED:R.AVAILABLE:a)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const O=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return R.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return R.AVAILABLE;case cast.framework.CastState.CONNECTING:return R.CONNECTING;case cast.framework.CastState.CONNECTED:return R.CONNECTED;default:return n(t)}};var N='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},B=function(t){return t&&t.Math==Math&&t},M=B('object'==typeof globalThis&&globalThis)||B('object'==typeof window&&window)||B('object'==typeof self&&self)||B('object'==typeof N&&N)||function(){return this}()||Function('return this')(),U=function(t){try{return!!t()}catch(t){return!0}},V=!U((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),q=V,F=Function.prototype,H=F.apply,G=F.call,Y='object'==typeof Reflect&&Reflect.apply||(q?G.bind(H):function(){return G.apply(H,arguments)}),j=V,z=Function.prototype,Q=z.bind,W=z.call,J=j&&Q.bind(W,W),K=j?function(t){return t&&J(t)}:function(t){return t&&function(){return W.apply(t,arguments)}},X=function(t){return'function'==typeof t},Z={},tt=!U((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),et=V,it=Function.prototype.call,st=et?it.bind(it):function(){return it.apply(it,arguments)},rt={},at={}.propertyIsEnumerable,nt=Object.getOwnPropertyDescriptor,ot=nt&&!at.call({1:2},1);rt.f=ot?function(t){var e=nt(this,t);return!!e&&e.enumerable}:at;var dt,ut,ht=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},ct=K,lt=ct({}.toString),pt=ct(''.slice),ft=function(t){return pt(lt(t),8,-1)},mt=K,vt=U,gt=ft,St=M.Object,bt=mt(''.split),yt=vt((function(){return!St('z').propertyIsEnumerable(0)}))?function(t){return'String'==gt(t)?bt(t,''):St(t)}:St,Tt=M.TypeError,Et=function(t){if(null==t)throw Tt('Can\'t call method on '+t);return t},wt=yt,$t=Et,kt=function(t){return wt($t(t))},At=X,Pt=function(t){return'object'==typeof t?null!==t:At(t)},Dt={},_t=Dt,Rt=M,It=X,Lt=function(t){return It(t)?t:void 0},xt=function(t,e){return arguments.length<2?Lt(_t[t])||Lt(Rt[t]):_t[t]&&_t[t][e]||Rt[t]&&Rt[t][e]},Ct=K({}.isPrototypeOf),Ot=xt('navigator','userAgent')||'',Nt=M,Bt=Ot,Mt=Nt.process,Ut=Nt.Deno,Vt=Mt&&Mt.versions||Ut&&Ut.version,qt=Vt&&Vt.v8;qt&&(ut=(dt=qt.split('.'))[0]>0&&dt[0]<4?1:+(dt[0]+dt[1])),!ut&&Bt&&(!(dt=Bt.match(/Edge\/(\d+)/))||dt[1]>=74)&&(dt=Bt.match(/Chrome\/(\d+)/))&&(ut=+dt[1]);var Ft=ut,Ht=Ft,Gt=U,Yt=!!Object.getOwnPropertySymbols&&!Gt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Ht&&Ht<41})),jt=Yt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,zt=xt,Qt=X,Wt=Ct,Jt=jt,Kt=M.Object,Xt=Jt?function(t){return'symbol'==typeof t}:function(t){var e=zt('Symbol');return Qt(e)&&Wt(e.prototype,Kt(t))},Zt=M.String,te=function(t){try{return Zt(t)}catch(t){return'Object'}},ee=X,ie=te,se=M.TypeError,re=function(t){if(ee(t))return t;throw se(ie(t)+' is not a function')},ae=re,ne=function(t,e){var i=t[e];return null==i?void 0:ae(i)},oe=st,de=X,ue=Pt,he=M.TypeError,ce={exports:{}},le=M,pe=Object.defineProperty,fe=function(t,e){try{pe(le,t,{value:e,configurable:!0,writable:!0})}catch(i){le[t]=e}return e},me=M['__core-js_shared__']||fe('__core-js_shared__',{}),ve=me;(ce.exports=function(t,e){return ve[t]||(ve[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.21.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.21.1/LICENSE',source:'https://github.com/zloirock/core-js'});var ge=Et,Se=M.Object,be=function(t){return Se(ge(t))},ye=be,Te=K({}.hasOwnProperty),Ee=Object.hasOwn||function(t,e){return Te(ye(t),e)},we=K,$e=0,ke=Math.random(),Ae=we(1..toString),Pe=function(t){return'Symbol('+(void 0===t?'':t)+')_'+Ae(++$e+ke,36)},De=M,_e=ce.exports,Re=Ee,Ie=Pe,Le=Yt,xe=jt,Ce=_e('wks'),Oe=De.Symbol,Ne=Oe&&Oe.for,Be=xe?Oe:Oe&&Oe.withoutSetter||Ie,Me=function(t){if(!Re(Ce,t)||!Le&&'string'!=typeof Ce[t]){var e='Symbol.'+t;Le&&Re(Oe,t)?Ce[t]=Oe[t]:Ce[t]=xe&&Ne?Ne(e):Be(e)}return Ce[t]},Ue=st,Ve=Pt,qe=Xt,Fe=ne,He=function(t,e){var i,s;if('string'===e&&de(i=t.toString)&&!ue(s=oe(i,t)))return s;if(de(i=t.valueOf)&&!ue(s=oe(i,t)))return s;if('string'!==e&&de(i=t.toString)&&!ue(s=oe(i,t)))return s;throw he('Can\'t convert object to primitive value')},Ge=Me,Ye=M.TypeError,je=Ge('toPrimitive'),ze=function(t,e){if(!Ve(t)||qe(t))return t;var i,s=Fe(t,je);if(s){if(void 0===e&&(e='default'),i=Ue(s,t,e),!Ve(i)||qe(i))return i;throw Ye('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),He(t,e)},Qe=Xt,We=function(t){var e=ze(t,'string');return Qe(e)?e:e+''},Je=Pt,Ke=M.document,Xe=Je(Ke)&&Je(Ke.createElement),Ze=function(t){return Xe?Ke.createElement(t):{}},ti=Ze,ei=!tt&&!U((function(){return 7!=Object.defineProperty(ti('div'),'a',{get:function(){return 7}}).a})),ii=tt,si=st,ri=rt,ai=ht,ni=kt,oi=We,di=Ee,ui=ei,hi=Object.getOwnPropertyDescriptor;Z.f=ii?hi:function(t,e){if(t=ni(t),e=oi(e),ui)try{return hi(t,e)}catch(t){}if(di(t,e))return ai(!si(ri.f,t,e),t[e])};var ci=U,li=X,pi=/#|\.prototype\./,fi=function(t,e){var i=vi[mi(t)];return i==Si||i!=gi&&(li(e)?ci(e):!!e)},mi=fi.normalize=function(t){return String(t).replace(pi,'.').toLowerCase()},vi=fi.data={},gi=fi.NATIVE='N',Si=fi.POLYFILL='P',bi=fi,yi=re,Ti=V,Ei=K(K.bind),wi=function(t,e){return yi(t),void 0===e?t:Ti?Ei(t,e):function(){return t.apply(e,arguments)}},$i={},ki=tt&&U((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),Ai=M,Pi=Pt,Di=Ai.String,_i=Ai.TypeError,Ri=function(t){if(Pi(t))return t;throw _i(Di(t)+' is not an object')},Ii=tt,Li=ei,xi=ki,Ci=Ri,Oi=We,Ni=M.TypeError,Bi=Object.defineProperty,Mi=Object.getOwnPropertyDescriptor;$i.f=Ii?xi?function(t,e,i){if(Ci(t),e=Oi(e),Ci(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Mi(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Bi(t,e,i)}:Bi:function(t,e,i){if(Ci(t),e=Oi(e),Ci(i),Li)try{return Bi(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Ni('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Ui=$i,Vi=ht,qi=tt?function(t,e,i){return Ui.f(t,e,Vi(1,i))}:function(t,e,i){return t[e]=i,t},Fi=M,Hi=Y,Gi=K,Yi=X,ji=Z.f,zi=bi,Qi=Dt,Wi=wi,Ji=qi,Ki=Ee,Xi=function(t){var e=function(i,s,r){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,r)}return Hi(t,this,arguments)};return e.prototype=t.prototype,e},Zi=function(t,e){var i,s,r,a,n,o,d,u,h=t.target,c=t.global,l=t.stat,p=t.proto,f=c?Fi:l?Fi[h]:(Fi[h]||{}).prototype,m=c?Qi:Qi[h]||Ji(Qi,h,{})[h],v=m.prototype;for(r in e)i=!zi(c?r:h+(l?'.':'#')+r,t.forced)&&f&&Ki(f,r),n=m[r],i&&(o=t.noTargetGet?(u=ji(f,r))&&u.value:f[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(d=t.bind&&i?Wi(a,Fi):t.wrap&&i?Xi(a):p&&Yi(a)?Gi(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Ji(d,'sham',!0),Ji(m,r,d),p&&(Ki(Qi,s=h+'Prototype')||Ji(Qi,s,{}),Ji(Qi[s],r,a),t.real&&v&&!v[r]&&Ji(v,r,a)))},ts=M.Promise,es=qi,is=function(t,e,i,s){s&&s.enumerable?t[e]=i:es(t,e,i)},ss=is,rs=M,as=(rs.String,rs.TypeError,K);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=as(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var ns={};ns[Me('toStringTag')]='z';var os='[object z]'===String(ns),ds=M,us=os,hs=X,cs=ft,ls=Me('toStringTag'),ps=ds.Object,fs='Arguments'==cs(function(){return arguments}()),ms=us?cs:function(t){var e,i,s;return void 0===t?'Undefined':null===t?'Null':'string'==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=ps(t),ls))?i:fs?cs(e):'Object'==(s=cs(e))&&hs(e.callee)?'Arguments':s},vs=ms,gs=os?{}.toString:function(){return'[object '+vs(this)+']'},Ss=os,bs=$i.f,ys=qi,Ts=Ee,Es=gs,ws=Me('toStringTag'),$s=function(t,e,i,s){if(t){var r=i?t:t.prototype;Ts(r,ws)||bs(r,ws,{configurable:!0,value:e}),s&&!Ss&&ys(r,'toString',Es)}},ks=xt,As=$i,Ps=tt,Ds=Me('species'),_s=Ct,Rs=M.TypeError,Is=X,Ls=me,xs=K(Function.toString);Is(Ls.inspectSource)||(Ls.inspectSource=function(t){return xs(t)});var Cs=Ls.inspectSource,Os={},Ns=Os,Bs=Me('iterator'),Ms=Array.prototype,Us=Math.ceil,Vs=Math.floor,qs=function(t){var e=+t;return e!=e||0===e?0:(e>0?Vs:Us)(e)},Fs=qs,Hs=Math.min,Gs=function(t){return t>0?Hs(Fs(t),9007199254740991):0},Ys=function(t){return Gs(t.length)},js=ms,zs=ne,Qs=Os,Ws=Me('iterator'),Js=function(t){if(null!=t)return zs(t,Ws)||zs(t,'@@iterator')||Qs[js(t)]},Ks=st,Xs=re,Zs=Ri,tr=te,er=Js,ir=M.TypeError,sr=st,rr=Ri,ar=ne,nr=wi,or=st,dr=Ri,ur=te,hr=function(t){return void 0!==t&&(Ns.Array===t||Ms[Bs]===t)},cr=Ys,lr=Ct,pr=function(t,e){var i=arguments.length<2?er(t):e;if(Xs(i))return Zs(Ks(i,t));throw ir(tr(t)+' is not iterable')},fr=Js,mr=function(t,e,i){var s,r;rr(t);try{if(!(s=ar(t,'return'))){if('throw'===e)throw i;return i}s=sr(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return rr(s),i},vr=M.TypeError,gr=function(t,e){this.stopped=t,this.result=e},Sr=gr.prototype,br=function(t,e,i){var s,r,a,n,o,d,u,h=i&&i.that,c=!(!i||!i.AS_ENTRIES),l=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),f=nr(e,h),m=function(t){return s&&mr(s,'normal',t),new gr(!0,t)},v=function(t){return c?(dr(t),p?f(t[0],t[1],m):f(t[0],t[1])):p?f(t,m):f(t)};if(l)s=t;else{if(!(r=fr(t)))throw vr(ur(t)+' is not iterable');if(hr(r)){for(a=0,n=cr(t);n>a;a++)if((o=v(t[a]))&&lr(Sr,o))return o;return new gr(!1)}s=pr(t,r)}for(d=s.next;!(u=or(d,s)).done;){try{o=v(u.value)}catch(t){mr(s,'throw',t)}if('object'==typeof o&&o&&lr(Sr,o))return o}return new gr(!1)},yr=Me('iterator'),Tr=!1;try{var Er=0,wr={next:function(){return{done:!!Er++}},return:function(){Tr=!0}};wr[yr]=function(){return this},Array.from(wr,(function(){throw 2}))}catch(t){}var $r=K,kr=U,Ar=X,Pr=ms,Dr=Cs,_r=function(){},Rr=[],Ir=xt('Reflect','construct'),Lr=/^\s*(?:class|function)\b/,xr=$r(Lr.exec),Cr=!Lr.exec(_r),Or=function(t){if(!Ar(t))return!1;try{return Ir(_r,Rr,t),!0}catch(t){return!1}},Nr=function(t){if(!Ar(t))return!1;switch(Pr(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return Cr||!!xr(Lr,Dr(t))}catch(t){return!0}};Nr.sham=!0;var Br,Mr,Ur,Vr,qr=!Ir||kr((function(){var t;return Or(Or.call)||!Or(Object)||!Or((function(){t=!0}))||t}))?Nr:Or,Fr=te,Hr=M.TypeError,Gr=Ri,Yr=function(t){if(qr(t))return t;throw Hr(Fr(t)+' is not a constructor')},jr=Me('species'),zr=function(t,e){var i,s=Gr(t).constructor;return void 0===s||null==(i=Gr(s)[jr])?e:Yr(i)},Qr=xt('document','documentElement'),Wr=K([].slice),Jr=M.TypeError,Kr=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ot),Xr='process'==ft(M.process),Zr=M,ta=Y,ea=wi,ia=X,sa=Ee,ra=U,aa=Qr,na=Wr,oa=Ze,da=function(t,e){if(t<e)throw Jr('Not enough arguments');return t},ua=Kr,ha=Xr,ca=Zr.setImmediate,la=Zr.clearImmediate,pa=Zr.process,fa=Zr.Dispatch,ma=Zr.Function,va=Zr.MessageChannel,ga=Zr.String,Sa=0,ba={};try{Br=Zr.location}catch(t){}var ya=function(t){if(sa(ba,t)){var e=ba[t];delete ba[t],e()}},Ta=function(t){return function(){ya(t)}},Ea=function(t){ya(t.data)},wa=function(t){Zr.postMessage(ga(t),Br.protocol+'//'+Br.host)};ca&&la||(ca=function(t){da(arguments.length,1);var e=ia(t)?t:ma(t),i=na(arguments,1);return ba[++Sa]=function(){ta(e,void 0,i)},Mr(Sa),Sa},la=function(t){delete ba[t]},ha?Mr=function(t){pa.nextTick(Ta(t))}:fa&&fa.now?Mr=function(t){fa.now(Ta(t))}:va&&!ua?(Vr=(Ur=new va).port2,Ur.port1.onmessage=Ea,Mr=ea(Vr.postMessage,Vr)):Zr.addEventListener&&ia(Zr.postMessage)&&!Zr.importScripts&&Br&&'file:'!==Br.protocol&&!ra(wa)?(Mr=wa,Zr.addEventListener('message',Ea,!1)):Mr='onreadystatechange'in oa('script')?function(t){aa.appendChild(oa('script')).onreadystatechange=function(){aa.removeChild(this),ya(t)}}:function(t){setTimeout(Ta(t),0)});var $a,ka,Aa,Pa,Da,_a,Ra,Ia,La={set:ca,clear:la},xa=M,Ca=/ipad|iphone|ipod/i.test(Ot)&&void 0!==xa.Pebble,Oa=/web0s(?!.*chrome)/i.test(Ot),Na=M,Ba=wi,Ma=Z.f,Ua=La.set,Va=Kr,qa=Ca,Fa=Oa,Ha=Xr,Ga=Na.MutationObserver||Na.WebKitMutationObserver,Ya=Na.document,ja=Na.process,za=Na.Promise,Qa=Ma(Na,'queueMicrotask'),Wa=Qa&&Qa.value;Wa||($a=function(){var t,e;for(Ha&&(t=ja.domain)&&t.exit();ka;){e=ka.fn,ka=ka.next;try{e()}catch(t){throw ka?Pa():Aa=void 0,t}}Aa=void 0,t&&t.enter()},Va||Ha||Fa||!Ga||!Ya?!qa&&za&&za.resolve?((Ra=za.resolve(void 0)).constructor=za,Ia=Ba(Ra.then,Ra),Pa=function(){Ia($a)}):Ha?Pa=function(){ja.nextTick($a)}:(Ua=Ba(Ua,Na),Pa=function(){Ua($a)}):(Da=!0,_a=Ya.createTextNode(''),new Ga($a).observe(_a,{characterData:!0}),Pa=function(){_a.data=Da=!Da}));var Ja=Wa||function(t){var e={fn:t,next:void 0};Aa&&(Aa.next=e),ka||(ka=e,Pa()),Aa=e},Ka={},Xa=re,Za=function(t){var e,i;this.promise=new t((function(t,s){if(void 0!==e||void 0!==i)throw TypeError('Bad Promise constructor');e=t,i=s})),this.resolve=Xa(e),this.reject=Xa(i)};Ka.f=function(t){return new Za(t)};var tn=Ri,en=Pt,sn=Ka,rn=function(t,e){if(tn(t),en(e)&&e.constructor===t)return e;var i=sn.f(t);return(0,i.resolve)(e),i.promise},an=M,nn=function(){this.head=null,this.tail=null};nn.prototype={add:function(t){var e={item:t,next:null};this.head?this.tail.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}};var on,dn,un,hn=nn,cn=X,ln=Cs,pn=M.WeakMap,fn=cn(pn)&&/native code/.test(ln(pn)),mn=ce.exports,vn=Pe,gn=mn('keys'),Sn=function(t){return gn[t]||(gn[t]=vn(t))},bn={},yn=fn,Tn=M,En=K,wn=Pt,$n=qi,kn=Ee,An=me,Pn=Sn,Dn=bn,_n=Tn.TypeError,Rn=Tn.WeakMap;if(yn||An.state){var In=An.state||(An.state=new Rn),Ln=En(In.get),xn=En(In.has),Cn=En(In.set);on=function(t,e){if(xn(In,t))throw new _n('Object already initialized');return e.facade=t,Cn(In,t,e),e},dn=function(t){return Ln(In,t)||{}},un=function(t){return xn(In,t)}}else{var On=Pn('state');Dn[On]=!0,on=function(t,e){if(kn(t,On))throw new _n('Object already initialized');return e.facade=t,$n(t,On,e),e},dn=function(t){return kn(t,On)?t[On]:{}},un=function(t){return kn(t,On)}}var Nn,Bn,Mn,Un={set:on,get:dn,has:un,enforce:function(t){return un(t)?dn(t):on(t,{})},getterFor:function(t){return function(e){var i;if(!wn(e)||(i=dn(e)).type!==t)throw _n('Incompatible receiver, '+t+' required');return i}}},Vn='object'==typeof window,qn=Zi,Fn=M,Hn=xt,Gn=st,Yn=ts,jn=function(t,e,i){for(var s in e)i&&i.unsafe&&t[s]?t[s]=e[s]:ss(t,s,e[s],i);return t},zn=$s,Qn=function(t){var e=ks(t),i=As.f;Ps&&e&&!e[Ds]&&i(e,Ds,{configurable:!0,get:function(){return this}})},Wn=re,Jn=X,Kn=Pt,Xn=function(t,e){if(_s(e,t))return t;throw Rs('Incorrect invocation')},Zn=Cs,to=br,eo=function(t,e){if(!e&&!Tr)return!1;var i=!1;try{var s={};s[yr]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i},io=zr,so=La.set,ro=Ja,ao=rn,no=function(t,e){var i=an.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},oo=Ka,uo=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},ho=hn,co=Un,lo=bi,po=Vn,fo=Xr,mo=Ft,vo=Me('species'),go='Promise',So=co.getterFor(go),bo=co.set,yo=co.getterFor(go),To=Yn&&Yn.prototype,Eo=Yn,wo=To,$o=Fn.TypeError,ko=Fn.document,Ao=Fn.process,Po=oo.f,Do=Po,_o=!!(ko&&ko.createEvent&&Fn.dispatchEvent),Ro=Jn(Fn.PromiseRejectionEvent),Io=lo(go,(function(){var t=Zn(Eo),e=t!==String(Eo);if(!e&&66===mo)return!0;if(!wo.finally)return!0;if(mo>=51&&/native code/.test(t))return!1;var i=new Eo((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};return(i.constructor={})[vo]=s,!(i.then((function(){}))instanceof s)||!e&&po&&!Ro})),Lo=Io||!eo((function(t){Eo.all(t).catch((function(){}))})),xo=function(t){var e;return!(!Kn(t)||!Jn(e=t.then))&&e},Co=function(t,e){var i,s,r,a=e.value,n=1==e.state,o=n?t.ok:t.fail,d=t.resolve,u=t.reject,h=t.domain;try{o?(n||(2===e.rejection&&Uo(e),e.rejection=1),!0===o?i=a:(h&&h.enter(),i=o(a),h&&(h.exit(),r=!0)),i===t.promise?u($o('Promise-chain cycle')):(s=xo(i))?Gn(s,i,d,u):d(i)):u(a)}catch(t){h&&!r&&h.exit(),u(t)}},Oo=function(t,e){t.notified||(t.notified=!0,ro((function(){for(var i,s=t.reactions;i=s.get();)Co(i,t);t.notified=!1,e&&!t.rejection&&Bo(t)})))},No=function(t,e,i){var s,r;_o?((s=ko.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),Fn.dispatchEvent(s)):s={promise:e,reason:i},!Ro&&(r=Fn['on'+t])?r(s):'unhandledrejection'===t&&no('Unhandled promise rejection',i)},Bo=function(t){Gn(so,Fn,(function(){var e,i=t.facade,s=t.value;if(Mo(t)&&(e=uo((function(){fo?Ao.emit('unhandledRejection',s,i):No('unhandledrejection',i,s)})),t.rejection=fo||Mo(t)?2:1,e.error))throw e.value}))},Mo=function(t){return 1!==t.rejection&&!t.parent},Uo=function(t){Gn(so,Fn,(function(){var e=t.facade;fo?Ao.emit('rejectionHandled',e):No('rejectionhandled',e,t.value)}))},Vo=function(t,e,i){return function(s){t(e,s,i)}},qo=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,Oo(t,!0))},Fo=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw $o('Promise can\'t be resolved itself');var s=xo(e);s?ro((function(){var i={done:!1};try{Gn(s,e,Vo(Fo,i,t),Vo(qo,i,t))}catch(e){qo(i,e,t)}})):(t.value=e,t.state=1,Oo(t,!1))}catch(e){qo({done:!1},e,t)}}};Io&&(wo=(Eo=function(t){Xn(this,wo),Wn(t),Gn(Nn,this);var e=So(this);try{t(Vo(Fo,e),Vo(qo,e))}catch(t){qo(e,t)}}).prototype,(Nn=function(t){bo(this,{type:go,done:!1,notified:!1,parent:!1,reactions:new ho,rejection:!1,state:0,value:void 0})}).prototype=jn(wo,{then:function(t,e){var i=yo(this),s=Po(io(this,Eo));return i.parent=!0,s.ok=!Jn(t)||t,s.fail=Jn(e)&&e,s.domain=fo?Ao.domain:void 0,0==i.state?i.reactions.add(s):ro((function(){Co(s,i)})),s.promise},catch:function(t){return this.then(void 0,t)}}),Bn=function(){var t=new Nn,e=So(t);this.promise=t,this.resolve=Vo(Fo,e),this.reject=Vo(qo,e)},oo.f=Po=function(t){return t===Eo||t===Mn?new Bn(t):Do(t)}),qn({global:!0,wrap:!0,forced:Io},{Promise:Eo}),zn(Eo,go,!1,!0),Qn(go),Mn=Hn(go),qn({target:go,stat:!0,forced:Io},{reject:function(t){var e=Po(this);return Gn(e.reject,void 0,t),e.promise}}),qn({target:go,stat:!0,forced:true},{resolve:function(t){return ao(this===Mn?Eo:this,t)}}),qn({target:go,stat:!0,forced:Lo},{all:function(t){var e=this,i=Po(e),s=i.resolve,r=i.reject,a=uo((function(){var i=Wn(e.resolve),a=[],n=0,o=1;to(t,(function(t){var d=n++,u=!1;o++,Gn(i,e,t).then((function(t){u||(u=!0,a[d]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise},race:function(t){var e=this,i=Po(e),s=i.reject,r=uo((function(){var r=Wn(e.resolve);to(t,(function(t){Gn(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var Ho=ts,Go=xt,Yo=X,jo=zr,zo=rn;Zi({target:'Promise',proto:!0,real:!0,forced:!!Ho&&U((function(){Ho.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=jo(this,Go('Promise')),i=Yo(t);return this.then(i?function(i){return zo(e,t()).then((function(){return i}))}:t,i?function(i){return zo(e,t()).then((function(){throw i}))}:t)}});var Qo,Wo=xt,Jo=Wo('Promise','finally');!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Qo||(Qo={}));var Ko,Xo=(t,e=0,i=Qo.OFFSET_P)=>{switch(i){case Qo.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case Qo.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:n(i)}return t},Zo=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(Ko||(Ko={}));const td={[Ko.Q_144P]:{width:256,height:144},[Ko.Q_240P]:{width:428,height:240},[Ko.Q_360P]:{width:640,height:360},[Ko.Q_480P]:{width:856,height:480},[Ko.Q_720P]:{width:1280,height:720},[Ko.Q_1080P]:{width:1920,height:1080},[Ko.Q_1440P]:{width:2560,height:1440},[Ko.Q_2160P]:{width:3840,height:2160},[Ko.Q_4320P]:{width:7680,height:4320}},ed=(t,e)=>td[t].height>td[e].height,id=(t,e)=>td[t].height<td[e].height,sd=Object.keys(td).sort(((t,e)=>id(t,e)?-1:1)),rd=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return sd.find((t=>{const e=td[t];return e.width>=s&&e.height>=i}))},ad=t=>t===Ko.INVARIANT;class nd{constructor(t){this.transitionStarted$=new e,this.transitionEnded$=new e,this.transitionUpdated$=new e,this.forceChanged$=new e,this.stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$),this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var od;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(od||(od={}));class dd{constructor(t){this.subscription=new i,this.loadMediaTimeoutSubscription=new i,this.videoState=new nd(od.STOPPED),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)if((null==s?void 0:s.to)===P.PAUSED||r.state!==x.Requested||t===od.STOPPED)switch(i){case P.PLAYING:switch(t){case od.PLAYING:break;case od.PAUSED:case od.READY:this.videoState.startTransitionTo(od.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case od.STOPPED:this.videoState.startTransitionTo(od.READY),this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case od.PLAYING:this.videoState.startTransitionTo(od.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case od.PAUSED:break;case od.READY:this.videoState.startTransitionTo(od.PAUSED),this.videoState.setState(od.PAUSED);break;case od.STOPPED:this.videoState.startTransitionTo(od.READY),this.prepare();break;default:n(t)}break;default:n(i)}else this.seek(r.position)}else t!==od.STOPPED&&(this.videoState.startTransitionTo(od.STOPPED),this.stop())},this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case D.MPEG:case D.DASH:case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.HLS:case D.HLS_JS:case D.HLS_ONDEMAND:return!1;case D.HLS_LIVE:case D.DASH_LIVE:case D.DASH_LIVE_WEBM:return!0;default:return n(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(o(this.videoState.stateChangeStarted$.pipe(u((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(u((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const s=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new e;t.add(i.pipe(p(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===x.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),Zo(this.params.desiredState.playbackState,P.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:n(i)}})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));s(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(od.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(od.PLAYING),Zo(this.params.desiredState.playbackState,P.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekState.setState({state:x.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==od.PAUSED&&t!==od.PLAYING||(this.videoState.setState(od.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==od.PLAYING&&t!==od.PAUSED||(this.videoState.setState(od.PLAYING),Zo(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===od.READY&&this.videoState.setState(od.READY)}handleRemoteStop(){this.videoState.getState()!==od.STOPPED&&this.videoState.setState(od.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){var e;const i=this.params.source;let r,a,o;switch(t){case D.MPEG:{const e=i[t];l(e);const s=Object.keys(e).sort(((t,e)=>t===e?0:t===Ko.INVARIANT?1:e===Ko.INVARIANT?-1:id(t,e)?1:-1))[0];l(s);const n=e[s];l(n),r=n,a='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS:case D.HLS_ONDEMAND:{const e=i[t];l(e),r=e.url,a='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM_VK:case D.DASH_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS_LIVE:{const e=i[t];l(e),r=Xo(e.url),a='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case D.DASH_LIVE_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case D.HLS_JS:case D.DASH:case D.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return n(t)}const d=new chrome.cast.media.MediaInfo(null!==(e=this.params.meta.videoId)&&void 0!==e?e:r,a);d.contentUrl=r,d.streamType=o,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:h}=this.params.meta;return s(u)&&(d.metadata.title=u),s(h)&&(d.metadata.subtitle=h),d}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===x.Applying||i.state===x.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(f(7e3).subscribe((()=>e('timeout(7000)'))))}));Jo(Promise.race([e,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===x.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:e,thrown:t})})),(()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}function ud(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{d(s.next(t))}catch(t){a(t)}}function o(t){try{d(s.throw(t))}catch(t){a(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}d((s=s.apply(t,e||[])).next())}))}function hd(t){return this instanceof hd?(this.v=t,this):new hd(t)}function cd(t,e,i){if(!Symbol.asyncIterator)throw new TypeError('Symbol.asyncIterator is not defined.');var s,r=i.apply(t,e||[]),a=[];return s={},n('next'),n('throw'),n('return'),s[Symbol.asyncIterator]=function(){return this},s;function n(t){r[t]&&(s[t]=function(e){return new Promise((function(i,s){a.push([t,e,i,s])>1||o(t,e)}))})}function o(t,e){try{(i=r[t](e)).value instanceof hd?Promise.resolve(i.value.v).then(d,u):h(a[0][2],i)}catch(t){h(a[0][3],t)}var i}function d(t){o('next',t)}function u(t){o('throw',t)}function h(t,e){t(e),a.shift(),a.length&&o(a[0][0],a[0][1])}}class ld{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}removeEventListener(t,e){if(!(t in this.listeners))return;const i=this.listeners[t];for(let t=0,s=i.length;t<s;t++)if(i[t].callback===e)return void i.splice(t,1)}dispatchEvent(t){if(!(t.type in this.listeners))return;const e=this.listeners[t.type].slice();for(let i=0,s=e.length;i<s;i++){const s=e[i];try{s.callback.call(this,t)}catch(t){Promise.resolve().then((()=>{throw t}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}class pd extends ld{constructor(){super(),this.listeners||ld.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class fd{constructor(){Object.defineProperty(this,'signal',{value:new pd,writable:!0,configurable:!0})}abort(){let t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event'),t.initEvent('abort',!1,!1)):(t=document.createEventObject(),t.type='abort'):t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}toString(){return'[object AbortController]'}}function md(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(fd.prototype[Symbol.toStringTag]='AbortController',pd.prototype[Symbol.toStringTag]='AbortSignal');const vd=md({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),gd=vd?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=t;if(!md({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty('signal')||r)&&(a=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const r=new i(t,e);return s&&Object.defineProperty(r,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),r},a.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=a&&a.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const r=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,n(t,e)])}return n(t,e)},Request:a}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Sd=vd?gd.fetch:window.fetch;vd?gd.Request:window.Request;const bd=vd?fd:window.AbortController,yd=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Td{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}executeNextRequests(){return ud(this,void 0,void 0,(function*(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[r,a]=yd(s.request);if(r>=i.from&&a<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}))}abort(t){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),r=this.activeRequests.get(i.url);s&&r&&r.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(yd),s=i[0][0];let r=i[0][1];for(let t=1;t<i.length&&r<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===s?Math.max(r,s+this.params.minInitSize):Math.max(r,s+this.params.minDataSize);const a=new URL(t,location.href);a.searchParams.append('bytes',`${s}-${r}`);const n=a.toString(),o=new bd,d=o.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return Sd(n,{signal:d}).then((t=>{var e,i,a;if(u.response=t,!t.ok||!t.body)return void this.onBigRequestError(u);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const d=n.getReader(),c=parseInt(null!==(a=t.headers.get('Content-Length'))&&void 0!==a?a:'',10)||r-s+1;u.data=new ArrayBuffer(c);const l=new Uint8Array(u.data),p=({done:t,value:e})=>ud(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(u):e&&(l.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),yield null==d?void 0:d.read().then(p,Td.suppressStreamErrors).catch(h))}));null==d||d.read().then(p,Td.suppressStreamErrors).catch(h)}),Td.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r,response:a}){var n,o,d,u,h,c,l,p;if(!this.activeRequests.has(t)||!r)return;const f=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const n of f){const{request:f}=n,[m,v]=yd(f),g=m>=e&&v<=e+s,S=e>=m&&e+s<v,b=r.slice(m-e,Math.min(v-e+1,s));if((g||S)&&(f.requestStartDate=null!==(o=f.requestStartDate)&&void 0!==o?o:new Date,f.firstByteDate=null!==(d=f.firstByteDate)&&void 0!==d?d:new Date,f.bytesLoaded=b.byteLength,f.bytesTotal=i-e),g){f.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==n))),null===(h=n.success)||void 0===h||h.call(n,b,'',t);const e=a?Array.from(a.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(c=this.dashMetrics)||void 0===c||c.addHttpRequest(f,t,null!==(l=null==a?void 0:a.status)&&void 0!==l?l:200,e,[])}else S&&(null===(p=n.progress)||void 0===p||p.call(n,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var r,a,n,o;if(null===(a=(r=this.params).onError)||void 0===a||a.call(r,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const d=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of d){const[r,a]=yd(t.request);(r>=e&&r<i||a>e&&a<=i)&&(null===(o=null==t?void 0:t.error)||void 0===o||o.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=yd(t.request);(s>=e&&s<i||a>e&&a<=i)&&(null===(r=null==t?void 0:t.abort)||void 0===r||r.call(t,t.request))}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class Ed{constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(Ed.shouldDelegateToBase(e))return this.baseLoader.load(t);this.bigRequest.queueDashJSRequest(t),this.bigRequest.executeNextRequests()}abort(t){if(!t)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:e}=t;Ed.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const wd=(t,e)=>{const i=new Td(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const r=t(i).create(s);return new Ed(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var $d=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,r=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>r(t),i&&s&&(null==e||e())}}}),!0)},kd=tt,Ad=Ee,Pd=Function.prototype,Dd=kd&&Object.getOwnPropertyDescriptor,_d=Ad(Pd,'name'),Rd={EXISTS:_d,PROPER:_d&&'something'===function(){}.name,CONFIGURABLE:_d&&(!kd||kd&&Dd(Pd,'name').configurable)},Id={},Ld=qs,xd=Math.max,Cd=Math.min,Od=kt,Nd=function(t,e){var i=Ld(t);return i<0?xd(i+e,0):Cd(i,e)},Bd=Ys,Md=function(t){return function(e,i,s){var r,a=Od(e),n=Bd(a),o=Nd(s,n);if(t&&i!=i){for(;n>o;)if((r=a[o++])!=r)return!0}else for(;n>o;o++)if((t||o in a)&&a[o]===i)return t||o||0;return!t&&-1}},Ud={includes:Md(!0),indexOf:Md(!1)},Vd=Ee,qd=kt,Fd=Ud.indexOf,Hd=bn,Gd=K([].push),Yd=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],jd=function(t,e){var i,s=qd(t),r=0,a=[];for(i in s)!Vd(Hd,i)&&Vd(s,i)&&Gd(a,i);for(;e.length>r;)Vd(s,i=e[r++])&&(~Fd(a,i)||Gd(a,i));return a},zd=Yd,Qd=Object.keys||function(t){return jd(t,zd)},Wd=tt,Jd=ki,Kd=$i,Xd=Ri,Zd=kt,tu=Qd;Id.f=Wd&&!Jd?Object.defineProperties:function(t,e){Xd(t);for(var i,s=Zd(e),r=tu(e),a=r.length,n=0;a>n;)Kd.f(t,i=r[n++],s[i]);return t};var eu,iu=Ri,su=Id,ru=Yd,au=bn,nu=Qr,ou=Ze,du=Sn('IE_PROTO'),uu=function(){},hu=function(t){return'<script>'+t+'<\/script>'},cu=function(t){t.write(hu('')),t.close();var e=t.parentWindow.Object;return t=null,e},lu=function(){try{eu=new ActiveXObject('htmlfile')}catch(t){}var t,e;lu='undefined'!=typeof document?document.domain&&eu?cu(eu):((e=ou('iframe')).style.display='none',nu.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(hu('document.F=Object')),t.close(),t.F):cu(eu);for(var i=ru.length;i--;)delete lu.prototype[ru[i]];return lu()};au[du]=!0;var pu,fu,mu,vu=Object.create||function(t,e){var i;return null!==t?(uu.prototype=iu(t),i=new uu,uu.prototype=null,i[du]=t):i=lu(),void 0===e?i:su.f(i,e)},gu=!U((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),Su=M,bu=Ee,yu=X,Tu=be,Eu=gu,wu=Sn('IE_PROTO'),$u=Su.Object,ku=$u.prototype,Au=Eu?$u.getPrototypeOf:function(t){var e=Tu(t);if(bu(e,wu))return e[wu];var i=e.constructor;return yu(i)&&e instanceof i?i.prototype:e instanceof $u?ku:null},Pu=U,Du=X,_u=vu,Ru=Au,Iu=is,Lu=Me('iterator'),xu=!1;[].keys&&('next'in(mu=[].keys())?(fu=Ru(Ru(mu)))!==Object.prototype&&(pu=fu):xu=!0);var Cu=null==pu||Pu((function(){var t={};return pu[Lu].call(t)!==t}));Du((pu=Cu?{}:_u(pu))[Lu])||Iu(pu,Lu,(function(){return this}));var Ou={IteratorPrototype:pu,BUGGY_SAFARI_ITERATORS:xu},Nu=Ou.IteratorPrototype,Bu=vu,Mu=ht,Uu=$s,Vu=Os,qu=function(){return this},Fu=Zi,Hu=st,Gu=function(t,e,i,s){var r=e+' Iterator';return t.prototype=Bu(Nu,{next:Mu(+!s,i)}),Uu(t,r,!1,!0),Vu[r]=qu,t},Yu=Au,ju=$s,zu=is,Qu=Os,Wu=Rd.PROPER,Ju=Ou.BUGGY_SAFARI_ITERATORS,Ku=Me('iterator'),Xu=function(){return this},Zu=kt,th=Os,eh=Un;$i.f;var ih=function(t,e,i,s,r,a,n){Gu(i,e,s);var o,d,u,h=function(t){if(t===r&&m)return m;if(!Ju&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},c=e+' Iterator',l=!1,p=t.prototype,f=p[Ku]||p['@@iterator']||r&&p[r],m=!Ju&&f||h(r),v='Array'==e&&p.entries||f;if(v&&(o=Yu(v.call(new t)))!==Object.prototype&&o.next&&(ju(o,c,!0,!0),Qu[c]=Xu),Wu&&'values'==r&&f&&'values'!==f.name&&(l=!0,m=function(){return Hu(f,this)}),r)if(d={values:h('values'),keys:a?m:h('keys'),entries:h('entries')},n)for(u in d)(Ju||l||!(u in p))&&zu(p,u,d[u]);else Fu({target:e,proto:!0,forced:Ju||l},d);return n&&p[Ku]!==m&&zu(p,Ku,m,{name:r}),Qu[e]=m,d},sh=eh.set,rh=eh.getterFor('Array Iterator');ih(Array,'Array',(function(t,e){sh(this,{type:'Array Iterator',target:Zu(t),index:0,kind:e})}),(function(){var t=rh(this),e=t.target,i=t.kind,s=t.index++;return!e||s>=e.length?(t.target=void 0,{value:void 0,done:!0}):'keys'==i?{value:s,done:!1}:'values'==i?{value:e[s],done:!1}:{value:[s,e[s]],done:!1}}),'values'),th.Arguments=th.Array;var ah=We,nh=$i,oh=ht,dh=br,uh=function(t,e,i){var s=ah(e);s in t?nh.f(t,s,oh(0,i)):t[s]=i};Zi({target:'Object',stat:!0},{fromEntries:function(t){var e={};return dh(t,(function(t,i){uh(e,t,i)}),{AS_ENTRIES:!0}),e}});var hh=Dt.Object.fromEntries,ch={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},lh=M,ph=ms,fh=qi,mh=Os,vh=Me('toStringTag');for(var gh in ch){var Sh=lh[gh],bh=Sh&&Sh.prototype;bh&&ph(bh)!==vh&&fh(bh,vh,gh),mh[gh]=mh.Array}var yh=hh,Th=i=>{const r=new t(1/0),a=new e,n=new t(void 0),o=new t(void 0);let d=NaN,u=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{var e,i,a,d,u;const h=yh(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in h||'x-playback-duration-millis'in h){const n=parseInt(null!==(e=t.getResponseHeader('X-Playback-Duration'))&&void 0!==e?e:'',10),o=parseInt(null!==(i=t.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==i?i:'',10),d=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;s(d)&&!isNaN(d)&&r.next(d)}const c=null!==(d=h['x-delivery-type'])&&void 0!==d?d:L.HTTP1,l=null!==(u={1:!0,0:!1}[h['x-reused']])&&void 0!==u?u:void 0;n.next(c),o.next(l)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!u&&(u=!0,a.next(Date.now()-d)),i(...t)},d=Date.now(),u=!1}return e(t)}}}),!0),{playbackDuration$:r,ping$:a,connectionReused$:o,connectionType$:n}},Eh=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},wh=t=>{t.extend('HTTPLoader',(function(){const{parent:t}=this,e=t.load;return{load:t=>{if(t.request&&t.request.range){const[e,i]=t.request.range.split('-').map((t=>parseInt(t,10))),s=new URL(t.request.url,location.href);s.searchParams.append('bytes',`${e}-${i}`),t.request.url=s.toString(),t.request.range=void 0}e(t)}}}),!0)};const $h=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),u=e(),h=r(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(u,d)||(s(d),h&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),h&&t.setState(e.to)}),o)),c},kh=(t,e,i)=>$h(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),Ah=(t,e,i,r)=>$h(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:i,onError:r}),Ph=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class Dh{constructor(){this.available$=new e,this.current$=new t(void 0),this.error$=new e,this.subscription=new i,this.externalTracks=new Map}connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};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($h(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(u((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add($h(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:r})),this.subscription.add($h(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(a(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(a(t,'addtrack'),a(t,'removetrack'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(o(a(t,'change'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(a(t,'addtrack').subscribe((t=>{var i,s;null===(i=t.track)||void 0===i||i.addEventListener('cuechange',e);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(a(t,'removetrack').subscribe((t=>{var i;null===(i=t.track)||void 0===i||i.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(Dh.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&Ph(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){l(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var _h=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class Rh{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(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}class Ih{constructor(t){this._buffer=[],this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:r})=>{const a=s>=t&&s<e,n=r>=t&&r<e;a&&n||(a?i(e,r):n?i(s,t):s<t&&r>e?(i(e,r),i(s,t)):i(s,r))}))}destroy(){this._buffer=[]}}var Lh=(t,e,i=3)=>{let s=0,r=0;for(let a=0;a<t.length;a++){const n=t.start(a),o=t.end(a);if(n<=e&&e<=o){if(s=n,r=o,!i)return{from:s,to:r};for(let e=a-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=a+1;e<t.length;e++)t.start(e)-i<=r&&(r=t.end(e))}}return{from:s,to:r}};const xh=t=>{const i=e=>a(t,e).pipe(v(void 0)),r=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>a(t,e)))).pipe(u((()=>t.readyState<3)),c()),n=o(a(t,'progress'),a(t,'timeupdate')).pipe(u((()=>Lh(t.buffered,t.currentTime)))),d=a(t,'volumechange').pipe(p(0),u((()=>({muted:t.muted,volume:t.volume})))),h=a(t,'error').pipe(u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),l=a(t,'timeupdate').pipe(u((()=>t.currentTime))),f=new e;let g;return l.subscribe((e=>{t.loop&&s(g)&&s(e)&&g>=t.duration-.3&&e<=.3&&f.next(g),g=e})),{playing$:i('playing'),pause$:i('pause').pipe(m((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:f,error$:h,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:a(t,'durationchange').pipe(u((()=>t.duration))),isBuffering$:r,currentBuffer$:n,volumeState$:d}},Ch=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var Oh=be,Nh=Ys,Bh=qs;Zi({target:'Array',proto:!0},{at:function(t){var e=Oh(this),i=Nh(e),s=Bh(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var Mh=Wo('Array','at');let Uh=!1,Vh={};const qh=t=>{t(Vh)},Fh=(t,e)=>{var i;Uh&&(Vh.meta=null!==(i=Vh.meta)&&void 0!==i?i:{},Vh.meta[t]=e)};class Hh{constructor(t){this.name=t}next(t){var e,i;if(!Uh)return;Vh.series=null!==(e=Vh.series)&&void 0!==e?e:{};const s=null!==(i=Vh.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Vh.series[this.name]=s}}const Gh=new Hh('best_bitrate');class Yh{constructor(){this.history={}}recordSelection(t){this.history[t.id]=g()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const jh=(t,{container:e,throughput:i,tuning:a,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:u,current:h,history:c})=>{var l,p,f,m;const v=a.usePixelRatio&&null!==(l=window.devicePixelRatio)&&void 0!==l?l:1,S=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*a.containerSizeFactor,height:e.height*v*a.containerSizeFactor},b=S&&rd(S),y=a.considerPlaybackRate&&s(u)?u:1,T=t.filter((t=>!ad(t.quality))).sort(((t,e)=>ed(t.quality,e.quality)?-1:1)),E=null===(p=Mh(T,-1))||void 0===p?void 0:p.quality,w=null===(f=Mh(T,0))||void 0===f?void 0:f.quality,$=r(n)||s(n.min)&&s(n.max)&&id(n.max,n.min)||s(n.min)&&w&&ed(n.min,w)||s(n.max)&&E&&id(n.max,E),k=y*(A=null!=d?d:.5,P=a.bitrateFactorAtEmptyBuffer,D=a.bitrateFactorAtFullBuffer,(P-D)*Math.pow(2,-10*A)+D);var A,P,D;const _=T.filter((t=>{const e=!b||id(t.quality,b),u=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*k,c=a.lazyQualitySwitch&&s(a.minBufferToSwitchUp)&&h&&!ad(h.quality)&&(null!=d?d:0)<a.minBufferToSwitchUp&&ed(t.quality,h.quality),l=$||(r(n.max)||(p=t.quality,f=n.max,td[p].height<=td[f].height))&&(r(n.min)||((t,e)=>td[t].height>=td[e].height)(t.quality,n.min));var p,f;return e&&u&&!c&&l}))[0];_&&_.bitrate&&Gh.next(_.bitrate);const R=null!==(m=null!=_?_:T[Math.ceil((T.length-1)/2)])&&void 0!==m?m:t[0],I=R&&c&&c.history[R.id]&&g()-c.history[R.id]<=a.trackCooldown&&(!c.last||R.id!==c.last.id);if((null==R?void 0:R.id)&&c&&!I&&c.recordSelection(R),I&&(null==c?void 0:c.last)){const t=c.last;return null==c||c.recordSwitch(t),t}return null==c||c.recordSwitch(R),R};var zh=t=>new URL(t).hostname;const Qh=(t,e=300)=>new S((i=>{const{width:r,height:a}=t.getBoundingClientRect();if(i.next({width:r,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let r,a;e.contentBoxSize&&e.contentBoxSize[0]?(a=e.contentBoxSize[0].blockSize,r=e.contentBoxSize[0].inlineSize):e.contentRect&&(r=e.contentRect.width,a=e.contentRect.height),s(r)&&s(a)&&i.next({width:r,height:a})}),e));return n.observe(t),()=>n.disconnect()})),Wh={};var Jh;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Jh||(Jh={}));const Kh=(t,e)=>new S((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Xh{constructor(e){this.subscription=new i,this.videoState=new nd(Jh.DOWNLOADING_LIB),this.textTracksManager=new Dh,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t(void 0),this.maxSeekBackTime$=new t(1/0),this.availableFrom$=new t(void 0),this.elementSize$=new t(void 0),this.liveOffset=new Rh,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==Jh.DOWNLOADING_LIB&&t!==Jh.STREAM_INITIALIZED)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===x.Requested&&t!==Jh.STOPPED&&e!==P.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case Jh.STOPPED:break;case Jh.PLAYING:case Jh.PAUSED:case Jh.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Jh.PLAYING:break;case Jh.PAUSED:r&&(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 Jh.READY:this.play();break;case Jh.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Jh.PLAYING:this.pause(),this.liveOffset.pause();break;case Jh.PAUSED:break;case Jh.READY:this.videoState.setState(Jh.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED);break;case Jh.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}},this.video=_h(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(zh(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Jo(import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Wh.MediaPlayer=e.MediaPlayer,Wh.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(Wh.MediaPlayer,'dashjs not loaded'),l(Wh.Debug,'dashjs not loaded'),this.player=Wh.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?Ch(t.frameRate+''):void 0),!0)));(this.params.format===D.DASH_WEBM||this.params.format===D.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=wd(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&&wh(this.player),$d(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:Eh})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Jh.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(Qh(this.video),this.elementSize$),a(Kh(this.player,'error').pipe(u((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),a(Kh(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Kh(this.player,'qualityChangeRendered').pipe(m((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));n.pipe(m(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(m((({to:t})=>t===Jh.STREAM_INITIALIZED)),b()).subscribe((()=>{this.subscription.add($h(e.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.videoTracks.find((({track:e})=>e.id===t)))||void 0===e?void 0:e.bitrateInfo;i&&this.player.setQualityFor('video',i.qualityIndex)}),{changed$:n.pipe(u((t=>null==t?void 0:t.id))),onError:i}))}),i)),this.subscription.add($h(e.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),a(Kh(this.player,'bufferStateChanged').pipe(m((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),a(Kh(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{var s,r;const a=this.player.getDashMetrics(),n=a.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),o=null!==(s=a.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type'))&&void 0!==s?s:L.HTTP1,d=null!==(r={1:!0,0:!1}[n])&&void 0!==r?r:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(d),t.hostname$.next(zh(i))})),a(Kh(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=rd(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===r&&(a=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&t.currentVideoTrack$.next(a),this.videoState.setState(Jh.STREAM_INITIALIZED),this.videoState.startTransitionTo(Jh.READY)})),a(Kh(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),a(o(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=jh(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(y({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(m(s))}).pipe(m((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const d=Kh(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>null!=t?t:0)));a(y({availableFrom:this.availableFrom$.pipe(m(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(d.pipe(m((()=>!1===this.isLive$.getValue()))),t.position$),a(Kh(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(Kh(this.player,'playbackEnded'),t.endedEvent$),a(Kh(this.player,'playbackProgress').pipe(u((()=>Lh(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(Kh(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Jh.PLAYING),Zo(e.playbackState,P.PLAYING)})),a(Kh(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Jh.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Kh(this.player,'playbackPaused'),(()=>{this.videoState.setState(Jh.PAUSED),Zo(e.playbackState,P.PAUSED)})),a(Kh(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Jh.READY&&this.videoState.setState(Jh.READY)})),a(this.isLive$,t.isLive$),a(Qh(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l,connectionType$:f,connectionReused$:g}=Th(this.player);a(f,this.params.output.httpConnectionType$),a(g,this.params.output.httpConnectionReused$),a(c,this.maxSeekBackTime$),a(l.pipe(b()),t.firstBytesEvent$),a(Kh(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(y({isLive:this.isLive$,isShort:t.duration$.pipe(u((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(d.pipe(m((t=>t>this.params.tuning.insufficientBufferRuleMargin)),b()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Kh(this.player,'manifestLoaded').pipe(b()).subscribe((()=>{this.subscription.add(Kh(this.player,'playbackPlaying').pipe(b(),v(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(kh(this.video,e.isLooped,i));const{volumeState$:S,looped$:T}=xh(this.video);this.subscription.add(Ah(this.video,e.volume,S,i)),this.subscription.add(S.subscribe(t.volume$,i)),this.subscription.add(T.subscribe(t.loopedEvent$))}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(Jh.STOPPED),Zo(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Jh.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=Xo(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Qo.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Jh.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Jh.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var Zh=t=>{switch(t){case'mobile':return Ko.Q_144P;case'lowest':return Ko.Q_240P;case'low':return Ko.Q_360P;case'sd':case'medium':return Ko.Q_480P;case'hd':case'high':return Ko.Q_720P;case'fullhd':case'full':return Ko.Q_1080P;case'quadhd':case'quad':return Ko.Q_1440P;case'ultrahd':case'ultra':return Ko.Q_2160P}},tc=t=>ud(void 0,void 0,void 0,(function*(){const e=t.muted;try{yield t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{yield t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0}));function ec(){return g()}function ic(t){return ec()-t}function sc(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,r=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let a=t.indexOf('?')>-1?'&':'?';return r&&(t+=a+'lowLat=1',a='&'),e&&(t+=a+'_rnd='+Math.floor(999999999*Math.random())),t}}}function rc(t,e,i,r){const a=window.XMLHttpRequest;let n,o,d,u,h,c=!1,p=0,f=!1,m='arraybuffer',v=7e3,g=2e3,S=()=>{if(c)return;l(u);const t=ic(u);let e;if(t<g)return e=g-t,void setTimeout(S,e);g*=2,g>v&&(g=v),o&&o.abort(),o=new a,y()};const b=()=>{if(!c){if(--p>=0)return S(),void(r&&r());c=!0,h&&h(),i&&i()}},y=()=>{u=ec(),o=new a,o.open('get',t);let i,s=0,r=0;const p=()=>(l(u),Math.max(u,Math.max(i||0,r||0)));if(n&&o.addEventListener('progress',(t=>{const e=ec();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(c)return;l(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(p(),t)}h&&h(),o&&e(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),f){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(r=ec(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=m,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(f=t,T),withJSONResponse:()=>(m='json',T),withRetryCount:t=>(p=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(v=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(h=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return T}class ac{constructor(t){this.intervals=[],this.currentRate=0,this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const r=e-t.start,a=t.end-t.start;i+=r;const n=t.bytes*r/a;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const r=8*s/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(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 nc{constructor(t,e,i,s,r){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=ec(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=rc(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=ec()-i,delete this.activeRequests[e],this._sendPending(),t._cb?t._cb(s,t._downloadTime):(this.limitCompleteCount(),this.completeRequests[e]=t)}),(()=>s('error')),(()=>{t._retry=1,t._retryCB&&t._retryCB()})),t._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{t._finallyCB&&t._finallyCB()})),this.activeRequests[e]=t,t._request.send(),this.lastPrefetchStart=ec()}_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 t=this._getParallelRequestCount(),e=ec();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const r={};return r.send=()=>{const a=this.activeRequests[t]||this.completeRequests[t];if(a)a._cb=e,a._errorCB=i,a._retryCB=s,a._finallyCB=r._finallyCB,a._error||a._complete?(this._removeFromActive(t),setTimeout((()=>{a._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(a._errorMsg)),r._finallyCB&&r._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(r,t)}},r._cb=e,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=t=>(r._finallyCB=t,r),r}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class oc{constructor(t){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=t,this.chunkRateEstimator=new ac(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=sc(t),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(t){this.autoQuality=t}setMaxAutoQuality(t){this.maxAutoQuality=t}switchByName(t){let e;for(let i=0;i<this.manifest.length;++i)if(e=this.manifest[i],e.name===t)return void this._switchToQuality(e)}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(t){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(t):this._notifyBuffering(!0)):this.catchUp()}startPlay(t,e){this.autoQuality=e,this._initPlayerWith(t)}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(t){this.manifestUrl=t,this.urlResolver=sc(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const a=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:'playing'})):a()}))};a()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new nc(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,d=null,u=null,h=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},f=(t,e,i)=>{u&&u.abort(),u=rc(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},m=(t,e,i)=>{l(this.filesFetcher),null==d||d.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},v=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void v(1);const i=ec()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const r=this.bufferStates[e];t=Math.min(t,r.buf),r.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,v(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else v(1)},b=t=>{let i;const r=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,u=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=i.dur.length-1;for(;a>=0&&(r-=i.dur[a],!(r<=0));--a);t=Math.min(a,i.dur.length-1-s),t=Math.max(t,0)}return u(t,!0)},f=(t,e,i)=>{h&&h.abort(),h=rc(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{h=null})).withJSONResponse().send()};return{seek:(e,o)=>{f(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let h=0;for(let t=0;t<i.dur.length;++t)h+=i.dur[t];h>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(h/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=r();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return u(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=r(),a=t?t.chunkIdx+1:0,n=a-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return u(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),u&&u.abort(),h&&h.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,u,c,v,g,T,E=b(t.jidxUrl),w=0;const $=()=>{v&&(clearTimeout(v),v=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=ec(),s=Math.min(1e4,e-i);w=i;const r=()=>{h||p()&&E.seek((()=>{p()&&(w=ec(),k(),$())}))};s>0?v=window.setTimeout((()=>{this.paused?$():r()}),s):r()},k=()=>{let e;for(;e=E.nextChunk(c);)c=e,R(e);const i=E.nextChunk(u);if(i){if(u&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));_(i)}else $()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let r,a,n;const o=i=>{window.setTimeout((()=>{p()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=ec(),u=i.currentTime;!this.paused&&i.buffered.length>1&&g===u&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,T=d);const h=this._getBufferSizeSec();if(h>30)s(`Buffered ${h} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(r=this.sourceBuffer.buffered.start(0),a=u,a-r>4&&this.sourceBuffer.remove(r,a-3)),o(1e3)}}},P=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(u)]),A(d,(function(){d=null,k()})))},D=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),_=t=>{p()&&m(D(t),((e,i)=>{if(p()){if(i/=1e3,d=e,u=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}P()}}),(()=>this._handleNetworkError()))},R=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{a=!0,P()})))};n=!0,E.seek((t=>{p()&&(w=ec(),t?(c=t,!r(e)||t.startTS>e?_(t):(u=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):f(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let r;t.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=ec();if(this.chunkRateEstimator.addInterval(t,s,i)){const r=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:r}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let r,a=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&r&&this.autoQuality){if(n&&t>r&&ic(a)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=ec();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=rc(this.urlResolver.resolve(t,!0),e,i,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;tc(e).then((e=>{e||null==t||t()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return(null==t?void 0:t.length)?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var dc;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(dc||(dc={}));const uc=[dc.PAUSED,dc.PLAYING,dc.READY],hc=[dc.PAUSED,dc.PLAYING,dc.READY];class cc{constructor(e){this.subscription=new i,this.videoState=new nd(dc.STOPPED),this.representations$=new t([]),this.textTracksManager=new Dh,this.maxSeekBackTime$=new t(1/0),this.zeroTime$=new t(void 0),this.liveOffset=new Rh,this._dashCb=t=>{var e,i,r,a;switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const s=t.manifest,a=[];for(const t of s){const s=null!==(e=t.name)&&void 0!==e?e:t.index.toString(10),r=null!==(i=Zh(t.name))&&void 0!==i?i:rd(t.video),n=t.bitrate/1e3,o=Object.assign({},t.video);if(!r)continue;const d={id:s,quality:r,bitrate:n,size:o};a.push({track:d,representation:t})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===dc.MANIFEST_READY&&this.videoState.setState(dc.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=null===(a=this.representations$.getValue().find((({representation:t})=>t===e)))||void 0===a?void 0:a.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}},this.syncPlayback=()=>{var t;const e=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r!==P.STOPPED){if(!i){if(hc.includes(e)){const e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to;s(e)&&this.setVideoTrack(e);const i=this.params.desiredState.autoVideoTrackSwitching.getTransition();i&&this.setAutoQuality(i.to)}if((null==a?void 0:a.to)!==P.PAUSED&&o.state===x.Requested&&uc.includes(e))this.seek(o.position-this.liveOffset.getTotalPausedTime());else switch(e){case dc.STOPPED:return this.videoState.startTransitionTo(dc.MANIFEST_READY),void this.dash.attachSource(Xo(this.params.source.url));case dc.MANIFEST_READY:this.videoState.startTransitionTo(dc.READY),this.prepare();break;case dc.READY:return void(r===P.PAUSED?this.videoState.setState(dc.PAUSED):r===P.PLAYING&&(this.videoState.startTransitionTo(dc.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(dc.PAUSED)}))));case dc.PLAYING:return void(r===P.PAUSED&&(this.videoState.startTransitionTo(dc.PAUSED),this.liveOffset.pause(),this.dash.pause()));case dc.PAUSED:return void(r===P.PLAYING&&(this.videoState.startTransitionTo(dc.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(dc.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return n(e)}}}else e!==dc.STOPPED&&(this.videoState.startTransitionTo(dc.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(dc.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const r=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=_h(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(zh(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const a=xh(this.video);this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===dc.READY&&this.videoState.setState(dc.READY)}),r)).add(a.pause$.subscribe((()=>{this.videoState.setState(dc.PAUSED)}),r)).add(a.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===x.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(dc.PLAYING)}),r)).add(a.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),u((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(y({zeroTime:this.zeroTime$.pipe(m(s)),position:a.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),r)).add(kh(this.video,this.params.desiredState.isLooped,r)).add(Ah(this.video,this.params.desiredState.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(this.params.output.volume$,r)).add(a.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(a.playing$.subscribe(this.params.output.firstFrameEvent$)).add(a.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&td[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case dc.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case dc.MANIFEST_READY:case dc.READY:break;case dc.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case dc.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return n(t.to)}}),r)).add(o(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new oc({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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var t,e,i,r,a,n;const o=this.representations$.getValue(),d=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState(),u=null!==(r=null===(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===i?void 0:i.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&s(d)?d:null===(a=jh(o.map((({track:t})=>t)),{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()}))||void 0===a?void 0:a.id,c=null===(n=o.find((({track:t})=>t.id===h)))||void 0===n?void 0:n.representation;l(c,'Representations missing'),this.dash.startPlay(c,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(h),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(t){var e;const i=null===(e=this.representations$.getValue().find((({track:e})=>e.id===t)))||void 0===e?void 0:e.representation;l(i,`No such representation ${t}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(Xo(this.params.source.url,i))}}var lc=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?L.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===r?void 0:null!==(i={1:!0,0:!1}[r])&&void 0!==i?i:void 0}},pc=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const r=1e3*t.start(s),a=1e3*t.end(s);r<=e&&e<=a&&(i=a)}return Math.max(i-e,0)};class fc{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{var e,i,s,r,a,n,o,d;if(l(this._xhr),(null===(e=this._xhr)||void 0===e?void 0:e.status)>=400)return null===(i=this._errorCb)||void 0===i||i.call(this,`Http${null===(s=this._xhr)||void 0===s?void 0:s.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=yh(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(a=this._headersCb)||void 0===a||a.call(this,new Headers(e))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(o=this._progressCb)||void 0===o||o.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!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 mc{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,r,a,n){this.abort((()=>{let o=0;const d=Date.now();let u=0,h=0,c=0;const l=t=>{s(mc._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=Eh(p)),this._lastXhr=new fc(p,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-o>n&&l(t),0===h)return void(h=Date.now());c=t.length-u;const e=Date.now()-h;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,u=t.length,h=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.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((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=mc._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class vc{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},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(t),s='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=Eh(i)),new fc(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$;const k=t.getElementsByTagName('SegmentBase')[0],A=k&&r(k,'indexRange').split('-'),P=k&&k.getElementsByTagName('Initialization')[0],D=P&&r(P,'range').split('-');if(!D||!A){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(h=null===(u=null===(d=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===d?void 0:d.childNodes)||void 0===u?void 0:u[0])||void 0===h?void 0:h.data),l=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:l})}return}const _=Number(null===(l=t.attributes.getNamedItem('bandwidth'))||void 0===l?void 0:l.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let I;const L=null!==(f=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==f?f:void 0;I=L?Ch(L):void 0,a.push({width:Number(null===(m=t.attributes.getNamedItem('width'))||void 0===m?void 0:m.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:_,baseURL:R,failoverHosts:e,indexFrom:Number(A[0]),indexTo:Number(A[1]),initFrom:Number(D[0]),initTo:Number(D[1]),codecs:null!==(S=null===(g=t.attributes.getNamedItem('codecs'))||void 0===g?void 0:g.value)&&void 0!==S?S:void 0,mimeType:null!==(y=null===(b=t.attributes.getNamedItem('mimeType'))||void 0===b?void 0:b.value)&&void 0!==y?y:void 0,fps:I,bufferSize:.1*_/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==($=null===(w=t.attributes.getNamedItem('id'))||void 0===w?void 0:w.value)&&void 0!==$?$:void 0})})),a.length?(this._representations=a,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const u=t.refs[t.refs.length-1];u.toTime-u.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,r;const a=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let a;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');a=e.to-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.to&&(r=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*a)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{a()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new mc({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const r=this._findRef(e);if(r){if(i){this._isLastRef(r)&&e>=r.toTime&&(e=r.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),a=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?e:r.fromTime}this._appendVector[String(r.fromTime)]=t,this._stream.load(t,r.fromOffset,r.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=r.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const r=.1;if(s.toTime<i.to+r){const e=this._findRef(s.toTime);e&&e.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!r(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var gc;!function(t){t.STOPPED='stopped',t.MANIFEST_LOADED='manifest-loaded',t.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',t.METADATA_LOADED='metadata-loaded',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(gc||(gc={}));const Sc=[gc.PAUSED,gc.PLAYING];class bc{constructor(s){this.videoState=new nd(gc.STOPPED),this.subscription=new i,this.representations$=new t([]),this.currentRepresentation$=new t(void 0),this.textTracksManager=new Dh,this.elementSize$=new t(void 0),this.dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&Zh(a.name))&&void 0!==s?s:rd(a),o=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!n)continue;const h={id:t,quality:n,bitrate:o,size:d,fps:u};r.push({track:h,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(gc.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t},this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)switch((null==s?void 0:s.to)!==P.PAUSED&&r.state===x.Requested&&Sc.includes(t)&&this.seek(r.position,r.forcePrecise),t){case gc.STOPPED:return this.videoState.startTransitionTo(gc.MANIFEST_LOADED),void this.prepare();case gc.MANIFEST_LOADED:return void this.videoState.startTransitionTo(gc.INITIAL_REPRESENTATION_SELECTED);case gc.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(gc.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case gc.METADATA_LOADED:return this.videoState.startTransitionTo(gc.READY),void this.dash.updateRefsForCurrentTime();case gc.READY:return void(i===P.PAUSED?(this.videoState.setState(gc.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(gc.PLAYING),this.playIfAllowed()));case gc.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(gc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===P.PLAYING&&Zo(this.params.desiredState.playbackState,P.PLAYING));case gc.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(gc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===P.PAUSED&&Zo(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==gc.STOPPED&&(this.videoState.startTransitionTo(gc.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(gc.STOPPED),Zo(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=s,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=_h(s.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(zh(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Ih(this.video),this.dash=new vc({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,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i})},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:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=xh(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,i));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.looped$,t.loopedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.playing$,t.firstFrameEvent$),l(d.canplay$,t.canplay$),this.subscription.add(d.seeking$.subscribe((()=>{r(this.params.desiredState.seekState.getState().state!==x.Applying)&&(this.videoState.getState()===gc.PLAYING||this.videoState.getState()===gc.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(kh(this.video,e.isLooped,i)),this.subscription.add(Ah(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(Qh(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===gc.READY&&this.videoState.setState(gc.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(gc.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(gc.PLAYING),Zo(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(gc.METADATA_LOADED)}),i)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(u((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(o(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$,a(this.video,'progress')).pipe(u((()=>{var t,e,i;const r=this.currentRepresentation$.getValue(),a=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),h=this.elementSize$.getValue(),c=n();let l;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!c&&s(d))l=d;else{const i=pc(this.video.buffered,1e3*this.video.currentTime),s=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,n=Math.min(i/s,1);l=null===(e=jh(a.map((({track:t})=>t)),{container:h,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:n,playbackRate:this.video.playbackRate,current:null===(t=a.find((({representation:t})=>t===r)))||void 0===t?void 0:t.track}))||void 0===e?void 0:e.id}return s(l)?null===(i=a.find((({track:t})=>t.id===l)))||void 0===i?void 0:i.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(y({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(m((t=>t.to===gc.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(m(s))}).pipe(b()).subscribe((()=>this.videoState.setState(gc.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(m(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=pc(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(zh(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=lc(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(b(),v(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(m(s)).subscribe(this.handleRepresentationPlay,i)).add(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(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 t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return n(t)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){tc(this.video).then((t=>{t||(this.videoState.setState(gc.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var yc,Tc,Ec,wc,$c;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(yc||(yc={})),function(t){t.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',t.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(Tc||(Tc={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(Ec||(Ec={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(wc||(wc={})),function(t){t.MP4='mp4',t.WEBM='webm'}($c||($c={}));var kc=(t,e)=>{for(let i=0;i<t.length;i++){if(1e3*t.start(i)<=e&&1e3*t.end(i)>e)return!0}return!1};const Ac='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;var Pc,Dc,_c=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};let Rc=!1;try{Rc=_c()&&parseInt(null!==(Dc=null===(Pc=navigator.userAgent.match(/Version\/(\d+)/))||void 0===Pc?void 0:Pc[1])&&void 0!==Dc?Dc:'',10)<16}catch(t){console.error(t)}class Ic{constructor(t){this.bufferFull$=new e,this.error$=new e,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const e=null===(t=this.currentTask.signal)||void 0===t?void 0:t.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown:t})}},this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}append(t,e){return ud(this,void 0,void 0,(function*(){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}))}remove(t,e,i){return ud(this,void 0,void 0,(function*(){return(!i||!i.aborted)&&new Promise((s=>{const r={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(r),this.pull()}))}))}abort(){return ud(this,void 0,void 0,(function*(){return new Promise((t=>{const e={operation:'abort',callback:t};for(const{callback:t}of this.queue)t(!1);this.queue=[e],this.pull()}))}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var t;if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(null===(t=e.signal)||void 0===t?void 0:t.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===i&&this.bufferFull$.next(this.currentTask.data.byteLength),t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===i||this.error$.next({id:`BufferTaskQueue:${i}`,message:'Buffer operation failed',thrown:t}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(t){const{operation:e}=t;switch(e){case'append':this.buffer.appendBuffer(t.data);break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;case'abort':Rc||this.buffer.abort();break;default:n(e)}}}var Lc;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(Lc||(Lc={}));class xc{constructor({throughputEstimator:e,requestQuic:s}){this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.abortAllController=new bd,this.subscription=new i,this.fetchManifest=T(this.abortAllController.signal,function(t){return cd(this,arguments,(function*(){let e=t;this.requestQuic&&(e=Eh(e));const i=yield yield hd(Sd(e,{signal:this.abortAllController.signal}).catch(Cc));return i?(this.onHeadersReceived(i.headers),yield hd(i.text())):yield hd(null)}))}.bind(this)),this.fetch=T(this.abortAllController.signal,function(t,{rangeMethod:e=Lc.HEADER,range:i,onProgress:s,priority:r='auto',signal:d,measureThroughput:u=!0}={}){var h,c,l,p;return cd(this,arguments,(function*(){let f=t;const m=new Headers;if(i)switch(e){case Lc.HEADER:m.append('Range',`${i.from}-${i.to}`);break;case Lc.PARAM:{const t=new URL(f,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),f=t.toString();break}default:n(e)}this.requestQuic&&(f=Eh(f));let v=this.abortAllController.signal;if(d){const t=new bd;if(this.subscription.add(o(a(this.abortAllController.signal,'abort'),a(d,'abort')).subscribe((()=>{try{t.abort()}catch(t){Cc(t)}}))),this.abortAllController.signal.aborted||d.aborted)try{t.abort()}catch(t){Cc(t)}v=t.signal}const S=g(),b=yield yield hd(Sd(f,{priority:r,headers:m,signal:v}).catch(Cc)),y=g();if(null===(h=this.throughputEstimator)||void 0===h||h.addRawRtt(y-S),!b)return yield hd(null);if(!b.ok||!b.body)return yield hd(Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`)));this.onHeadersReceived(b.headers);const E=parseInt(null!==(c=b.headers.get('Content-Length'))&&void 0!==c?c:'',10)||i&&i.to-i.from+1||NaN;if(!E){const t=yield yield hd(b.arrayBuffer());return null===(l=this.throughputEstimator)||void 0===l||l.addRawSpeed(t.byteLength,g()-y),null==s||s(new DataView(t),t.byteLength),yield hd(t)}if(!s&&!u)return yield hd(b.arrayBuffer());const[w,$]=b.body.tee(),k=w.getReader();u&&(null===(p=this.throughputEstimator)||void 0===p||p.trackStream($));let A=0;const P=new ArrayBuffer(E),D=new Uint8Array(P),_=new DataView(P);let R=!1;const I=t=>{R=!0,Cc(t)},L=T(v,function({done:t,value:e}){return cd(this,arguments,(function*(){if(0===A&&this.lastRequestFirstBytes$.next(g()-S),v.aborted)return yield hd(void 0);t?null==s||s(_,A):e&&(D.set(e,A),A+=e.byteLength,null==s||s(_,A),yield yield hd(null==k?void 0:k.read().then(L,I)))}))}.bind(this));return yield yield hd(null==k?void 0:k.read().then(L,I)),yield hd(R?null:P)}))}.bind(this)),this.fetchByteRangeRepresentation=T(this.abortAllController.signal,function(t,e,i){return cd(this,arguments,(function*(){if(t.type!==Ec.BYTE_RANGE)return yield hd(null);const{from:s,to:r}=t.initRange;let a,n,o=s,d=r,u=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,u=r+1===a,u&&(o=Math.min(a,s),d=Math.max(n,r))),o=Math.min(o,0);const h=yield yield hd(this.fetch(t.url,{rangeMethod:Lc.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1}));if(!h)return yield hd(null);const c=new DataView(h,s-o,r-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(u&&void 0!==a&&void 0!==n)p=new DataView(h,a-o,n-a+1);else{const s=e.getIndexRange(l);if(s){const e=yield yield hd(this.fetch(t.url,{rangeMethod:Lc.PARAM,range:s,priority:i,measureThroughput:!1}));if(!e)return yield hd(null);p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const f=e.parseSegments(p,l);return yield hd({dataView:new DataView(h),segments:f})}))}.bind(this)),this.fetchTemplateRepresentation=T(this.abortAllController.signal,function(t,e){return cd(this,arguments,(function*(){if(t.type!==Ec.TEMPLATE)return yield hd(null);const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield yield hd(this.fetch(i,{priority:e,measureThroughput:!1}));if(!s)return yield hd(null);const r=t.segments.map((t=>Object.assign(Object.assign({},t),{status:wc.NONE,size:void 0})));return yield hd({segments:r,dataView:new DataView(s)})}))}.bind(this)),this.throughputEstimator=e,this.requestQuic=s}onHeadersReceived(t){const{type:e,reused:i}=lc(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchRepresentation(t,e,i='auto'){var s,r;return ud(this,void 0,void 0,(function*(){const{type:a}=t;switch(a){case Ec.BYTE_RANGE:return null!==(s=yield this.fetchByteRangeRepresentation(t,e,i))&&void 0!==s?s:null;case Ec.TEMPLATE:return null!==(r=yield this.fetchTemplateRepresentation(t,i))&&void 0!==r?r:null;default:n(a)}}))}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Cc=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},Oc=new TextDecoder('ascii'),Nc=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=Oc.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}},Bc={validateData:t=>'ftyp'===Oc.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=Nc(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),d=4294967295&r();let u=n/a*1e3,h=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:wc.NONE,time:{from:u,to:u+o},byte:{from:h,to:h+s-1}}),u+=o,h+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const r=new DataView(t.buffer,t.byteOffset+e);try{const i=Nc(r);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var Mc,Uc;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(Mc||(Mc={})),function(t){t.SignedInteger='int',t.UnsignedInteger='uint',t.Float='float',t.String='string',t.UTF8='utf8',t.Date='date',t.Master='master',t.Binary='binary'}(Uc||(Uc={}));const Vc={[Mc.EBML]:{type:Uc.Master},[Mc.EBMLVersion]:{type:Uc.UnsignedInteger},[Mc.EBMLReadVersion]:{type:Uc.UnsignedInteger},[Mc.EBMLMaxIDLength]:{type:Uc.UnsignedInteger},[Mc.EBMLMaxSizeLength]:{type:Uc.UnsignedInteger},[Mc.DocType]:{type:Uc.String},[Mc.DocTypeVersion]:{type:Uc.UnsignedInteger},[Mc.DocTypeReadVersion]:{type:Uc.UnsignedInteger},[Mc.Void]:{type:Uc.Binary},[Mc.Segment]:{type:Uc.Master},[Mc.SeekHead]:{type:Uc.Master},[Mc.Seek]:{type:Uc.Master},[Mc.SeekID]:{type:Uc.Binary},[Mc.SeekPosition]:{type:Uc.UnsignedInteger},[Mc.Info]:{type:Uc.Master},[Mc.TimestampScale]:{type:Uc.UnsignedInteger},[Mc.Duration]:{type:Uc.Float},[Mc.Tracks]:{type:Uc.Master},[Mc.Chapters]:{type:Uc.Master},[Mc.Cluster]:{type:Uc.Master},[Mc.Timestamp]:{type:Uc.UnsignedInteger},[Mc.SilentTracks]:{type:Uc.Master},[Mc.SilentTrackNumber]:{type:Uc.UnsignedInteger},[Mc.Position]:{type:Uc.UnsignedInteger},[Mc.PrevSize]:{type:Uc.UnsignedInteger},[Mc.SimpleBlock]:{type:Uc.Binary},[Mc.BlockGroup]:{type:Uc.Master},[Mc.EncryptedBlock]:{type:Uc.Binary},[Mc.Attachments]:{type:Uc.Master},[Mc.Tags]:{type:Uc.Master},[Mc.Cues]:{type:Uc.Master},[Mc.CuePoint]:{type:Uc.Master},[Mc.CueTime]:{type:Uc.UnsignedInteger},[Mc.CueTrackPositions]:{type:Uc.Master},[Mc.CueTrack]:{type:Uc.UnsignedInteger},[Mc.CueClusterPosition]:{type:Uc.UnsignedInteger},[Mc.CueRelativePosition]:{type:Uc.UnsignedInteger},[Mc.CueDuration]:{type:Uc.UnsignedInteger},[Mc.CueBlockNumber]:{type:Uc.UnsignedInteger},[Mc.CueCodecState]:{type:Uc.UnsignedInteger},[Mc.CueReference]:{type:Uc.Master},[Mc.CueRefTime]:{type:Uc.UnsignedInteger}},qc=t=>{const e=t.getUint8(0);let i=0;128&e?i=1:64&e?i=2:32&e?i=3:16&e&&(i=4);const s=Fc(t,i),r=s in Vc,a=r?Vc[s].type:Uc.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),u=((n&255>>o)<<8*(o-1))+Fc(d),h=i+o;let c;return c=h+u>t.byteLength?new DataView(t.buffer,t.byteOffset+h):new DataView(t.buffer,t.byteOffset+h,u),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+u,value:c,valueSize:u}},Fc=(t,e=t.byteLength)=>{switch(e){case 1:return t.getUint8(0);case 2:return t.getUint16(0);case 3:return t.getUint16(0)<<8|t.getUint8(2);case 4:return t.getUint32(0);case 5:return t.getUint32(0)<<8|t.getUint8(4);case 6:return t.getUint32(0)<<16|t.getUint16(4);case 7:return t.getUint32(0)<<32|t.getUint16(4)<<8|t.getUint8(6);case 8:return t.getUint32(0)<<32|t.getUint32(4)}return 0},Hc=(t,e)=>{switch(e){case Uc.SignedInteger:return t.getInt8(0);case Uc.UnsignedInteger:return Fc(t);case Uc.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Uc.String:return new TextDecoder('ascii').decode(t);case Uc.UTF8:return new TextDecoder('utf-8').decode(t);case Uc.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Uc.Master:case Uc.Binary:return t;default:n(e)}},Gc=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=qc(s);if(!e(r))return;r.type===Uc.Master&&Gc(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},Yc=[Mc.Info,Mc.SeekHead,Mc.Tracks,Mc.Chapters,Mc.Cluster,Mc.Cues,Mc.Attachments,Mc.Tags],jc=[Mc.Timestamp,Mc.SilentTracks,Mc.SilentTrackNumber,Mc.Position,Mc.PrevSize,Mc.SimpleBlock,Mc.BlockGroup,Mc.EncryptedBlock],zc={validateData:t=>{if(t.getUint32(0)!==Mc.EBML)return!1;let e,i,s;const r=qc(t);return Gc(r.value,(({tag:t,type:r,value:a})=>(t===Mc.EBMLReadVersion?e=Hc(a,r):t===Mc.DocType?i=Hc(a,r):t===Mc.DocTypeReadVersion&&(s=Hc(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,r,a,n,o=!1,d=!1,u=!1;return Gc(t,(({tag:t,type:h,value:c,valueSize:l})=>{if(t===Mc.SeekID){const t=Hc(c,h);n=Fc(t)}else t!==Mc.SeekPosition&&(n=void 0);return t===Mc.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===Mc.Info?o=!0:t===Mc.SeekHead?d=!0:t===Mc.TimestampScale?s=Hc(c,h):t===Mc.Duration?r=Hc(c,h):t===Mc.SeekPosition&&n===Mc.Cues?a=Hc(c,h):o&&d&&Yc.includes(t)&&(u=!0),!u})),l(e,'Failed to parse webm Segment start'),l(i,'Failed to parse webm Segment end'),l(r,'Failed to parse webm Segment duration'),s=null!=s?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:a}},getIndexRange:t=>{if(r(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,r=!1;const a=t=>s(t.time)&&s(t.position),n=[];let o;return Gc(t,(({tag:t,type:e,value:s})=>{switch(t){case Mc.Cues:i=!0;break;case Mc.CuePoint:o&&a(o)&&n.push(o),o={};break;case Mc.CueTime:o&&(o.time=Hc(s,e));break;case Mc.CueTrackPositions:break;case Mc.CueClusterPosition:o&&(o.position=Hc(s,e));break;default:i&&Yc.includes(t)&&(r=!0)}return!(i&&r)})),o&&a(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:r}=t,a=n[i+1];return{status:wc.NONE,time:{from:s,to:a?a.time:e.segmentDuration},byte:{from:e.segmentStart+r,to:a?e.segmentStart+a.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Gc(t,(s=>s.tag===Mc.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!jc.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[Mc.SimpleBlock,Mc.BlockGroup,Mc.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class Qc{constructor(o,d,u,h,{fetcher:c,tuning:p,getCurrentPosition:f}){switch(this.onLastSegment$=new t(!1),this.fullyBuffered$=new t(!1),this.playingRepresentation$=new t(void 0),this.error$=new e,this.gaps=[],this.subscription=new i,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new bd,this.destroyAbortController=new bd,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=T(this.destroyAbortController.signal,function(t){return cd(this,arguments,(function*(){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new Ic(this.sourceBuffer),this.subscription.add(a(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(a(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>this.pruneBuffer(t)))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield yield hd(this.loadInit(e,'high',!0));const i=this.initData.get(e.id),r=this.segments.get(e.id);if(l(i,'No init buffer for starting representation'),l(r,'No segments for starting representation'),!(i instanceof ArrayBuffer))return yield hd(void 0);let n=0;for(const t of r)t.time.from-n>=300&&this.gaps.push({representation:e.id,from:n,to:t.time.from}),n=t.time.to;s(e.duration)&&e.duration-n>=300&&this.gaps.push({representation:e.id,from:n,to:e.duration}),yield yield hd(this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)}))}.bind(this)),this.switchTo=T(this.destroyAbortController.signal,function(t){return cd(this,arguments,(function*(){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return yield hd(void 0);this.switchingToRepresentationId=t;const e=this.representations.get(t);l(e,`No such representation ${t}`);let i=this.initData.get(t);if(r(i)?yield yield hd(this.loadInit(e,'high',!1)):i instanceof Promise&&(yield yield hd(i)),i=this.initData.get(t),!(i&&i instanceof ArrayBuffer&&this.sourceBuffer))return yield hd(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield yield hd(this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal));const a=this.getCurrentPosition();s(a)&&this.maintain(a)}))}.bind(this)),this.fetcher=c,this.tuning=p,this.forwardBufferTarget=p.dash.forwardBufferTargetAuto,this.getCurrentPosition=f,this.container=u,u){case $c.MP4:this.containerParser=Bc;break;case $c.WEBM:this.containerParser=zc;break;default:n(u)}this.initData=new Map(h.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(h.map((t=>[t.id,t]))),this.kind=o,this.mediaSource=d,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new bd,this.abortBuffer()}maintain(t){if(r(this.downloadingRepresentationId)||r(this.playingRepresentationId)||r(this.sourceBuffer))return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(l(e,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find((e=>t>=e.time.from&&t<e.time.to));let a=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,i=pc(this.sourceBuffer.buffered,t),r=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(a=r)}let n=[];if(isFinite(this.bufferLimit)&&(t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e})(this.sourceBuffer.buffered)>=.8*this.bufferLimit)this.pruneBuffer(1/0);else if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,e.segmentReference.type,a),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&s)if(n.includes(s))t='high';else{const e=Mh(n,0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===wc.FED&&!n.length&&pc(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=Mh(i,-1);o&&o.status===wc.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){var e,i,s;const r=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!r)return;const a=this.segments.get(r);if(!a)return;const n=a.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===wc.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==Ec.BYTE_RANGE)return t.slice(s,s+1);const r=t;let a=0;const n=[];for(let t=s;t<r.length&&a<=this.tuning.dash.segmentRequestSize;t++){const e=r[t];if(a+=e.byte.to+1-e.byte.from,e.status!==wc.NONE)break;n.push(e)}return n}loadSegments(t,e,i='auto'){return ud(this,void 0,void 0,(function*(){if(!t.length)return;let s,r,a=t;const{type:o}=e.segmentReference;switch(o){case Ec.BYTE_RANGE:s=e.segmentReference.url,r={from:Mh(t,0).byte.from,to:Mh(t,-1).byte.to};break;case Ec.TEMPLATE:{const i=Mh(t,0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),a=[i];break}default:n(o)}for(const t of a)t.status=wc.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,fedBytes:0,representationId:e.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield T(d,function(){return cd(this,arguments,(function*(){const t=E(this.failedDownloads,this.tuning.downloadBackoff);yield yield hd(new Promise((e=>setTimeout(e,t))))}))}.bind(this))(),d.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(s,{rangeMethod:Lc.PARAM,range:r,onProgress:(t,i)=>{if(!d.aborted)try{this.onSomeDataLoaded(t,e.id,r?r.from:0,i,d)}catch(t){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:t})}},signal:d,priority:i}).then((()=>this.failedDownloads=0),(e=>{for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.onSegmentDownloadError(e)}))}))}onSegmentDownloadError(t){var e;let i=!1;const r=this.getCurrentPosition();if(this.sourceBuffer&&s(r)){i=pc(null===(e=this.sourceBuffer)||void 0===e?void 0:e.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,i||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,r){if(!this.activeSegments.size)return;const a=t=>{this.abortSegment(t.segment)},n=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=wc.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===wc.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=wc.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,u=t.byteLength;for(const o of this.activeSegments){const{segment:h}=o,c=d===Ec.BYTE_RANGE,l=c?h.byte.to-h.byte.from+1:u;if(o.representationId!==e)continue;if(!(!c||h.byte.from>=i&&h.byte.to<i+t.byteLength))continue;if(r.aborted){a(o);continue}const p=c?h.byte.from-i:0,f=p<s,m=(c?h.byte.to-i:t.byteLength)<=s;if(h.status===wc.DOWNLOADING&&f&&m){h.status=wc.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,l);this.sourceBufferTaskQueue.append(e,r).then((t=>t&&!r.aborted?n(o):a(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&f&&(o.loadedBytes=Math.min(l,s-p),o.loadedBytes>o.fedBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.fedBytes,o.loadedBytes-o.fedBytes),i=o.loadedBytes===l?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(h.status=wc.PARTIALLY_FED,o.fedBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,r).then((t=>{!t||r.aborted?a(o):o.fedBytes===l&&n(o)})))}}}abortSegment(t){t.status===wc.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=wc.NONE)),t.status=wc.NONE):t.status=wc.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const r=s instanceof Promise;e||(e=r),null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=Ac((()=>Jo(this.loadInit(i,'low',!1),(()=>this.initLoadIdleCallback=null)))))}loadInit(t,e='auto',i=!1){return ud(this,void 0,void 0,(function*(){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',r=(!i&&this.failedDownloads>0?T(this.destroyAbortController.signal,function(){return cd(this,arguments,(function*(){const t=E(this.failedDownloads,this.tuning.downloadBackoff);yield yield hd(new Promise((e=>setTimeout(e,t))))}))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s))).then((e=>{if(!e)return;const{dataView:i,segments:s}=e,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,r),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,r),r}))}pruneBuffer(t){return ud(this,void 0,void 0,(function*(){const e=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||r(e))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let s=0,a=1/0,n=-1/0,o=!1;const d=t=>{var e;a=Math.min(a,t.time.from),n=Math.max(n,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;s+=i};for(const r of i){if(r.time.to>=e||s>=t)break;r.status===wc.FED&&d(r)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const r of i){if(r.time.from<e+this.forwardBufferTarget||s>t)break;r.status===wc.FED&&d(r)}}return o=isFinite(a)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(a/1e3,n/1e3)}))}abortBuffer(){this.sourceBuffer&&'open'===this.mediaSource.readyState&&this.sourceBufferTaskQueue.abort()}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),r=1e3*this.sourceBuffer.buffered.end(t);if(!(r<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&r>=i.time.to){e=void 0;break}r>i.time.from&&r<i.time.to&&(e.from=r),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=Ac((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(r(this.sourceBuffer)||r(this.playingRepresentationId))return;const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const i=1e3*this.sourceBuffer.buffered.start(e),s=1e3*this.sourceBuffer.buffered.end(e);t.push({from:i,to:s})}const e=this.tuning.dash.segmentTimelineTolerance;for(const i of this.segments.values())for(const s of i){const i=t.some((t=>t.from-e<=s.time.from&&t.to+e>=s.time.to));s.status!==wc.FED||i||(s.status=wc.NONE)}}}const Wc=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},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(t),s='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},Jc=(t,e)=>{let i=t;i=i.replaceAll('$$','$');const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[t,e]of Object.entries(s)){const s=new RegExp(`\\$${t}(?:%0(\\d+)d)?\\$`,'g');i=i.replaceAll(s,((t,i)=>r(e)?t:r(i)?e:e.padStart(parseInt(i,10),'0')))}return i},Kc=(t,e)=>{var i,r,a,n,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$,k,A,P,D,_,R,I,L,x,C,O,N,B;const M={video:[],audio:[],text:[]},U=(new DOMParser).parseFromString(t,'application/xml').children[0],V=U.getElementsByTagName('Period')[0],q=V.children;let F;const H=U.getAttribute('mediaPresentationDuration'),G=V.getAttribute('duration');if(H)F=Wc(H);else if(G){const t=Wc(G);s(t)&&(F=t)}let Y=0;const j=null!==(r=null===(i=U.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==r?r:[],z=j.includes(Tc.WEBM_AS_IN_FFMPEG)||j.includes(Tc.WEBM_AS_IN_SPEC)?$c.WEBM:$c.MP4;for(const t of q){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==i?void 0:i.split('/')[0],U=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],V=t.querySelectorAll('Representation');if('text'!==r)for(const a of V){const n=null!==(d=a.getAttribute('mimeType'))&&void 0!==d?d:i,o=null!==(h=null!==(u=a.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==h?h:'',V=null!==(l=null!==(c=a.getAttribute('contentType'))&&void 0!==c?c:null==n?void 0:n.split('/')[0])&&void 0!==l?l:r,q=null!==(f=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==f?f:[],H=parseInt(null!==(m=a.getAttribute('width'))&&void 0!==m?m:'',10),G=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),z=parseInt(null!==(g=a.getAttribute('bandwidth'))&&void 0!==g?g:'',10)/1e3,Q=null!==(S=a.getAttribute('frameRate'))&&void 0!==S?S:'',W=null!==(b=a.getAttribute('quality'))&&void 0!==b?b:void 0,J=Q?Ch(Q):void 0,K=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(Y++).toString(10)}@${'video'===V?`${G}p`:'audio'===V?`${z}Kbps`:o}`,X=null!==(w=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==w?w:'',Z=new URL(X,e).toString(),tt=[...j,...U,...q];let et;const it=a.querySelector('SegmentBase'),st=a.querySelector('SegmentTemplate');if(it){const t=null!==(k=null===($=a.querySelector('SegmentBase Initialization'))||void 0===$?void 0:$.getAttribute('range'))&&void 0!==k?k:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},r=null===(A=a.querySelector('SegmentBase'))||void 0===A?void 0:A.getAttribute('indexRange'),[n,o]=r?r.split('-').map((t=>parseInt(t,10))):[],d=r?{from:n,to:o}:void 0;et={type:Ec.BYTE_RANGE,url:Z,initRange:s,indexRange:d}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(P=a.getAttribute('id'))&&void 0!==P?P:void 0,bandwidth:null!==(D=a.getAttribute('bandwidth'))&&void 0!==D?D:void 0},e=parseInt(null!==(_=st.getAttribute('timescale'))&&void 0!==_?_:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),r=null!==(L=parseInt(null!==(I=st.getAttribute('startNumber'))&&void 0!==I?I:'',10))&&void 0!==L?L:1,n=Jc(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const o=null!==(x=st.querySelectorAll('SegmentTimeline S'))&&void 0!==x?x:[],d=[];let u=r,h=0;for(const i of o){const r=1e3*parseInt(null!==(C=i.getAttribute('d'))&&void 0!==C?C:'',10),a=parseInt(null!==(O=i.getAttribute('r'))&&void 0!==O?O:'',10)||1,n=null!==(B=parseInt(null!==(N=i.getAttribute('t'))&&void 0!==N?N:'',10))&&void 0!==B?B:void 0;for(let i=0;i<a;i++){const i=Jc(s,Object.assign(Object.assign({},t),{segmentNumber:u.toString(10),segmentTime:n.toString(10)})),a=n?n/e:h;h+=r/e;const o=h;u++,d.push({time:{from:a,to:o},url:i})}}et={type:Ec.TEMPLATE,baseUrl:Z,initUrl:n,segments:d}}}if(!V||!n)continue;const rt={video:yc.VIDEO,audio:yc.AUDIO,text:yc.TEXT}[V];rt&&M[rt].push({id:K,kind:rt,segmentReference:et,profiles:tt,duration:F,bitrate:z,mime:n,codecs:o,width:H,height:G,fps:J,quality:W})}}return{duration:F,container:z,representations:M}},Xc=['timeupdate','progress','play','seeked','stalled'];var Zc,tl;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Zc||(Zc={}));class el{constructor(r){this.element=null,this.source=null,this.manifest=null,this.subscription=new i,this.state$=new nd(Zc.NONE),this.currentVideoRepresentation$=new t(void 0),this.error$=new e,this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.forceEnded$=new e,this.gapWatchdogStarted=!1,this.destroyController=new bd,this.initManifest=T(this.destroyController.signal,function(t,e){return cd(this,arguments,(function*(){this.element=t,this.state$.startTransitionTo(Zc.MANIFEST_LOADED);const i=yield yield hd(this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:t}))));if(!i)return yield hd(null);let s;try{s=Kc(null!=i?i:'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!s)return yield hd(null);const r=({mime:e,codecs:i})=>{var s,r,a;return Boolean((null===(s=t.canPlayType)||void 0===s?void 0:s.call(t,e))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${e}; codecs="${i}"`)))};return this.manifest=Object.assign(Object.assign({},s),{representations:yh(Object.entries(s.representations).map((([t,e])=>[t,e.filter(r)])))}),this.manifest.representations.video.length?this.state$.setState(Zc.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),yield hd(this.manifest)}))}.bind(this)),this.initRepresentations=T(this.destroyController.signal,function(t,e){return cd(this,arguments,(function*(){l(this.manifest),l(this.element),this.state$.startTransitionTo(Zc.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new Qc(yc.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new Qc(yc.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),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 r=o(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(u((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),n=o(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(u((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(o(this.forceEnded$,y({allBuffersFull:r,someBufferEnded:n}).pipe(m((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var t;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield yield hd(new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)})))),s(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s(e)?yield yield hd(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)])):yield yield hd(this.videoBufferManager.startWith(t)),this.state$.setState(Zc.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...Xc.map((t=>a(this.element,t))),a(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(a(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(a(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&kc(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}))}.bind(this)),this.tick=()=>{var t,e;if(!this.element||!this.videoBufferManager)return;const i=1e3*this.element.currentTime;this.videoBufferManager.maintain(i),null===(t=this.audioBufferManager)||void 0===t||t.maintain(i),!this.videoBufferManager.gaps.length&&!(null===(e=this.audioBufferManager)||void 0===e?void 0:e.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=w(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=r.throughputEstimator,this.tuning=r.tuning,this.fetcher=new xc({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}switchRepresentation(t,e){return ud(this,void 0,void 0,(function*(){const i={[yc.VIDEO]:this.videoBufferManager,[yc.AUDIO]:this.audioBufferManager,[yc.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}))}seek(t,e){var i,s,r,a,n;let o;l(this.element),l(this.videoBufferManager),o=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(null!==(i=this.videoBufferManager.findSegmentStartTime(t))&&void 0!==i?i:t,null!==(r=null===(s=this.audioBufferManager)||void 0===s?void 0:s.findSegmentStartTime(t))&&void 0!==r?r:t),kc(this.element.buffered,o)||(this.videoBufferManager.abort(),null===(a=this.audioBufferManager)||void 0===a||a.abort()),this.videoBufferManager.maintain(o),null===(n=this.audioBufferManager)||void 0===n||n.maintain(o),this.element.currentTime=o/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(Zc.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of this.bufferManagers)for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(tl||(tl={}));const il=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?Zh(a):void 0)&&void 0!==n?n:rd({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},sl=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=Mh(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:Mh(t,-1)};class rl{constructor(e){this.subscription=new i,this.videoState=new nd(tl.STOPPED),this.elementSize$=new t(void 0),this.textTracksManager=new Dh,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new Yh,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(s.state===x.Requested&&(null==i?void 0:i.to)!==P.PAUSED&&t!==tl.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===tl.STOPPED)return this.videoState.startTransitionTo(tl.READY),void this.prepare();switch(t){case tl.READY:return void(e===P.PAUSED?(this.videoState.setState(tl.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(tl.PLAYING),this.playIfAllowed()));case tl.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(tl.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Zo(this.params.desiredState.playbackState,P.PLAYING));case tl.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(tl.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Zo(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==tl.STOPPED&&(this.videoState.startTransitionTo(tl.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(tl.STOPPED),Zo(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=e,this.video=_h(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(zh(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new el({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=xh(this.video),r=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,r));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.playing$,t.firstFrameEvent$),n(i.canplay$,t.canplay$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(m(s),b(),v(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(kh(this.video,e.isLooped,r)),this.subscription.add(Ah(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),n(Qh(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(tl.PLAYING),Zo(e.playbackState,P.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(tl.PAUSED),Zo(e.playbackState,P.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===tl.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(m((({to:t})=>t===Zc.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(tl.READY)})));const d=e=>t.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:e});this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a(this.video,'progress')).subscribe((()=>{var i,s,r,a,n,o,u,h;const c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c===Zc.NONE||!this.videoTracks.length)return;const f=c===Zc.MANIFEST_LOADED&&!p,m=c===Zc.REPRESENTATION_SELECTED&&!p,v=e.autoVideoTrackSwitching.getState(),g=e.videoTrack.getState(),S=null===(i=this.videoTracks.find((({track:{id:t}})=>t===g)))||void 0===i?void 0:i.track,b=t.currentVideoTrack$.getValue(),y=pc(this.video.buffered,1e3*this.video.currentTime),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),w=Math.max(S&&!v&&null!==(r=null===(s=this.audioRepresentations.get(S.id))||void 0===s?void 0:s.bitrate)&&void 0!==r?r:0,b&&null!==(n=null===(a=this.audioRepresentations.get(b.id))||void 0===a?void 0:a.bitrate)&&void 0!==n?n:0),$=jh(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),reserve:w,forwardBufferHealth:E,current:b,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),k=v?null!=$?$:S:null!=S?S:$;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),f){const t=k&&(null===(o=this.videoTracks.find((({track:t})=>t===k)))||void 0===o?void 0:o.representation);l(t),this.player.initRepresentations(t.id,null===(u=this.audioRepresentations.get(t.id))||void 0===u?void 0:u.id)}else if(m){const t=k&&(null===(h=this.videoTracks.find((({track:t})=>t===k)))||void 0===h?void 0:h.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(yc.VIDEO,t.id).catch(d),e&&this.player.switchRepresentation(yc.AUDIO,e.id).catch(d)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),u((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const f=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(f.subscribe(this.syncPlayback,r))}prepare(){return ud(this,void 0,void 0,(function*(){const t=yield this.player.initManifest(this.video,this.params.source.url);if(!t)return;this.videoTracks=[];const e=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),i=Array.from(t.representations.video).sort(((t,e)=>e.bitrate-t.bitrate));for(const t of i){const s=il(t);if(s){this.videoTracks.push({track:s,representation:t});const r=sl(e,i,t);r&&this.audioRepresentations.set(t.id,r)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){tc(this.video).then((t=>{t||(this.videoState.setState(tl.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const al={};var nl;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(nl||(nl={}));const ol=(t,e)=>new S((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class dl{constructor(t){this.subscription=new i,this.videoState=new nd(nl.INITIALIZING),this.textTracksManager=new Dh,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(t!==nl.INITIALIZING)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===x.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case nl.STOPPED:break;case nl.READY:case nl.PLAYING:case nl.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case nl.PLAYING:break;case nl.STOPPED:this.prepare();break;case nl.READY:case nl.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case nl.PAUSED:break;case nl.STOPPED:this.prepare();break;case nl.READY:this.videoState.setState(nl.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED);break;case nl.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}},this.video=_h(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(zh(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Jo(import('hls.js').then((e=>{t||(al.Hls=e.default,al.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(al.Hls,'hls.js not loaded'),this.hls=new al.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(nl.STOPPED)}subscribe(){l(al.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=xh(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,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.loadStart$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),this.subscription.add(kh(this.video,t.isLooped,i)),this.subscription.add(Ah(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ol(this.hls,al.Events.ERROR).subscribe((t=>{var i;t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(i=t.err)||void 0===i?void 0:i.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(nl.PLAYING),Zo(t.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(nl.PAUSED),Zo(t.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===nl.READY&&this.videoState.setState(nl.READY),this.videoState.getState()===nl.PLAYING&&this.playIfAllowed()}),i)),n(ol(this.hls,al.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=Zh(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:rd({width:a,height:n});if(!o)return t;const d=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:d};return this.trackLevels.set(r,{track:u,level:e}),t.push(u),t}),[])))),e.availableVideoTracks$),n(ol(this.hls,al.Events.LEVEL_LOADING).pipe(u((({url:t})=>zh(t)))),e.hostname$),this.subscription.add($h(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const d=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},c=ol(this.hls,al.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>d(this.hls.levels[t]))));c.pipe(m(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add($h(t.videoTrack,(()=>{var t;return null===(t=d(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.trackLevels.get(t))||void 0===e?void 0:e.level;if(!i)return;const s=this.hls.levels.indexOf(i),a=this.hls.currentLevel,n=this.hls.levels[a];!n||i.bitrate>n.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:c.pipe(u((t=>null==t?void 0:t.id))),onError:i})),n(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const f=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(f.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(nl.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return ud(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(nl.PLAYING);(yield tc(this.video))||(this.videoState.setState(nl.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(nl.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/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(nl.STOPPED),Zo(this.params.desiredState.playbackState,P.STOPPED,!0)}}const ul=t=>{let e=null;if(t.QUALITY&&(e=Zh(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=rd({width:i,height:s})}return null!=e?e:null},hl=(t,e=t)=>ud(void 0,void 0,void 0,(function*(){var i;const s=yield Sd(t),r=(yield s.text()).split('\n'),a=[];for(let t=0;t<r.length;t++){const s=r[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=yh(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,d=ul(n);let u;n.BANDWIDTH&&(u=parseInt(n.BANDWIDTH,10)/1e3||void 0),!u&&n['AVERAGE-BANDWIDTH']&&(u=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let c;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(c={width:t,height:e})}const l=new URL(r[++t],e).toString();d&&a.push({id:o,quality:d,url:l,bandwidth:u,size:c,fps:h})}return a}));var cl,ll,pl,fl,ml,vl,gl,Sl,bl,yl,Tl,El,wl,$l,kl,Al,Pl,Dl,_l,Rl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(cl||(cl={}));class Il{constructor(e){var s;this.subscription=new i,this.videoState=new nd(cl.STOPPED),this.textTracksManager=new Dh,this.manifests$=new t([]),this.liveOffset=new Rh,this.manifestStartTime$=new t(void 0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==cl.STOPPED&&(this.videoState.startTransitionTo(cl.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(cl.STOPPED),Zo(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===cl.STOPPED)return this.videoState.startTransitionTo(cl.READY),void this.prepare();if(s||r){const t=this.videoState.getState();return this.videoState.setState(cl.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(a.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==i?void 0:i.to)!==P.PAUSED&&a.state===x.Requested)return this.videoState.startTransitionTo(cl.READY),this.seek(a.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case cl.READY:return void(e===P.PAUSED?(this.videoState.setState(cl.PAUSED),this.liveOffset.pause(),Zo(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(cl.PLAYING),this.playIfAllowed()));case cl.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(cl.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Zo(this.params.desiredState.playbackState,P.PLAYING));case cl.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(cl.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())):(null==i?void 0:i.to)===P.PAUSED&&(Zo(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case cl.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=_h(e.container),this.params.output.element$.next(this.video);const r={id:'master',quality:Ko.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),hl(Xo(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([r,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(zh(this.params.source.url)),this.maxSeekBackTime$=new t(null!==(s=e.source.maxSeekBackTime)&&void 0!==s?s:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},r=xh(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.ended$,t.endedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(Ah(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(cl.PLAYING),Zo(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(cl.PAUSED),Zo(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===cl.READY&&this.videoState.setState(cl.READY),this.videoState.getState()===cl.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),u((t=>-t/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(zh(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===cl.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===x.Requested&&this.seek(t.position)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),i)),this.subscription.add(y({startTime:this.manifestStartTime$.pipe(m(s)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,h(['init'])).pipe(p(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(r(t))return;const e=Xo(t.url,this.liveOffset.getTotalOffset());var i;this.video.setAttribute('src',e),this.video.load(),(i=e,ud(void 0,void 0,void 0,(function*(){const t=yield Sd(i,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){tc(this.video).then((t=>{t||(this.videoState.setState(cl.PAUSED),this.liveOffset.pause(),Zo(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(ll||(ll={}));class Ll{constructor(e){this.subscription=new i,this.videoState=new nd(ll.STOPPED),this.textTracksManager=new Dh,this.manifests$=new t([]),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==ll.STOPPED&&(this.videoState.startTransitionTo(ll.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(ll.STOPPED),Zo(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===ll.STOPPED)return this.videoState.startTransitionTo(ll.READY),void this.prepare();if(s||r){const t=this.videoState.getState();this.videoState.setState(ll.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(a.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&a.state===x.Requested&&this.seek(a.position),t){case ll.READY:return void(e===P.PAUSED?(this.videoState.setState(ll.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(ll.PLAYING),this.playIfAllowed()));case ll.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(ll.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Zo(this.params.desiredState.playbackState,P.PLAYING));case ll.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(ll.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Zo(this.params.desiredState.playbackState,P.PAUSED));case ll.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=_h(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:Ko.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(zh(this.params.source.url)),hl(this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},r=xh(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(kh(this.video,e.isLooped,i)),this.subscription.add(Ah(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(ll.PLAYING),Zo(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(ll.PAUSED),Zo(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===ll.READY&&this.videoState.setState(ll.READY),this.videoState.getState()===ll.PLAYING&&this.playIfAllowed()}),i).add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(zh(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===ll.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===x.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();r(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){tc(this.video).then((t=>{t||(this.videoState.setState(ll.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(pl||(pl={}));class xl{constructor(t){this.subscription=new i,this.videoState=new nd(pl.STOPPED),this.trackUrls={},this.textTracksManager=new Dh,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==pl.STOPPED&&(this.videoState.startTransitionTo(pl.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(pl.STOPPED),Zo(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(t===pl.STOPPED)return this.videoState.startTransitionTo(pl.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(r.state===x.None&&this.params.desiredState.seekState.setState({state:x.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&r.state===x.Requested&&this.seek(r.position),t){case pl.READY:return void(e===P.PAUSED?(this.videoState.setState(pl.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(pl.PLAYING),this.playIfAllowed()));case pl.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(pl.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Zo(this.params.desiredState.playbackState,P.PLAYING));case pl.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(pl.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Zo(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}},this.params=t,this.video=_h(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},r=xh(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(kh(this.video,e.isLooped,i)),this.subscription.add(Ah(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(pl.PLAYING),Zo(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(pl.PAUSED),Zo(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===pl.READY&&this.videoState.setState(pl.READY);const e=this.params.desiredState.videoTrack.getTransition();e&&s(e.to)&&(this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to].track)),this.videoState.getState()===pl.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.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 t,e;const i=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState();l(i,'MpegProvider: track is not selected');let{url:s}=this.trackUrls[i];l(s,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(s=Eh(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(zh(s))}playIfAllowed(){tc(this.video).then((t=>{t||(this.videoState.setState(pl.PAUSED),Zo(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}class Cl{constructor(t){this.iterator=t[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)}}const Ol=_c(),Nl=(null===(fl=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===fl?void 0:fl.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Bl=document.createElement('video'),Ml={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(vl=null===(ml=window.SourceBuffer)||void 0===ml?void 0:ml.prototype)||void 0===vl?void 0:vl.appendBuffer)),hls:Boolean((null===(gl=Bl.canPlayType)||void 0===gl?void 0:gl.call(Bl,'application/x-mpegurl'))||(null===(Sl=Bl.canPlayType)||void 0===Sl?void 0:Sl.call(Bl,'vnd.apple.mpegURL')))},Ul={mp4:Boolean(null===(bl=Bl.canPlayType)||void 0===bl?void 0:bl.call(Bl,'video/mp4')),webm:Boolean(null===(yl=Bl.canPlayType)||void 0===yl?void 0:yl.call(Bl,'video/webm'))},Vl={h264:Boolean(null===(El=null===(Tl=window.MediaSource)||void 0===Tl?void 0:Tl.isTypeSupported)||void 0===El?void 0:El.call(Tl,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===($l=null===(wl=window.MediaSource)||void 0===wl?void 0:wl.isTypeSupported)||void 0===$l?void 0:$l.call(wl,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(Al=null===(kl=window.MediaSource)||void 0===kl?void 0:kl.isTypeSupported)||void 0===Al?void 0:Al.call(kl,'video/webm; codecs="vp9"')),aac:Boolean(null===(Dl=null===(Pl=window.MediaSource)||void 0===Pl?void 0:Pl.isTypeSupported)||void 0===Dl?void 0:Dl.call(Pl,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Rl=null===(_l=window.MediaSource)||void 0===_l?void 0:_l.isTypeSupported)||void 0===Rl?void 0:Rl.call(_l,'audio/webm; codecs="opus"'))},ql=(Vl.h264||Vl.h265)&&Vl.aac,Fl=!Ol,Hl=Nl||Ol,Gl=!Ml.hls||!Hl;const Yl=3e4,jl=18e4,zl=3,Ql=100,Wl={cacheDuration:12e4},Jl={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Kl={maxPausedTime:3e4},Xl={maxPausedTime:3e4};class Zl{constructor(r){this.current$=new t({type:void 0}),this.providerError$=new e,this.noAvailableProvidersError$=new e,this.providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,canplay$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)},this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:a}=this.params.tuning,o=a.length?[...r.screenFormatsPriority.filter((t=>!a.includes(t))),...r.screenFormatsPriority.filter((t=>a.includes(t)))]:r.screenFormatsPriority;this.screenFormatsIterator=new Cl(o.filter((t=>s(r.sources[t]))).filter((t=>{switch(t){case D.DASH:return Ml.mse&&Ul.mp4&&ql&&Fl;case D.DASH_SEP:case D.DASH_SEP_VK:return Ml.mse&&Ul.mp4&&ql;case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.DASH_LIVE_WEBM:return Ml.mse&&Ul.webm&&Vl.vp9&&Vl.opus;case D.DASH_LIVE:return Ml.mse&&Ul.mp4&&ql;case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:return Ml.mse&&Ul.mp4&&ql;case D.HLS:case D.HLS_LIVE:case D.HLS_ONDEMAND:return Ml.hls&&Ul.mp4&&Hl;case D.HLS_JS:return Ml.mse&&Ul.mp4&&ql&&Gl;case D.MPEG:return Ul.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new Cl(r.chromecastFormatsPriority.filter((t=>s(r.sources[t]))))}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 t=this.chooseDestination(),e=this.chooseFormat(t);if(r(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;l(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==x.None;this.params.desiredState.seekState.setState({state:x.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case _.SCREEN:return this.createScreenProvider(e);case _.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,r={container:i,source:null,desiredState:s,output:this.providerOutput,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case D.DASH:{const i=e[t];return l(i),new bc(Object.assign(Object.assign({},r),{source:i,config:Wl}))}case D.DASH_ONDEMAND_VK:case D.DASH_SEP_VK:case D.DASH_WEBM_VK:{const i=e[t];return l(i),new rl(Object.assign(Object.assign({},r),{source:i}))}case D.DASH_SEP:case D.DASH_WEBM:case D.DASH_ONDEMAND:case D.DASH_LIVE_WEBM:{const i=e[t];return l(i),new Xh(Object.assign(Object.assign({},r),{source:i,format:t,config:Xl}))}case D.HLS:case D.HLS_ONDEMAND:{const i=e[t];return l(i),new Ll(Object.assign(Object.assign({},r),{source:i}))}case D.HLS_LIVE:{const i=e[t];return l(i),new Il(Object.assign(Object.assign({},r),{source:i,config:Kl}))}case D.HLS_JS:{const i=e[t];return l(i),new dl(Object.assign(Object.assign({},r),{source:i}))}case D.MPEG:{const i=e[t];return l(i),new xl(Object.assign(Object.assign({},r),{source:i}))}case D.DASH_LIVE:{const i=e[t];return l(i),new cc(Object.assign(Object.assign({},r),{source:i,config:Jl}))}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:r}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new dd({connection:n,meta:r,container:i,source:e,format:t,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_.CHROMECAST:_.SCREEN}chooseFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.next();case _.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case _.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case _.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let t=[],r=0;const a=new i;var n;return a.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Yl,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(m((({type:t})=>void 0!==t)))},new S((t=>{const s=new i,r=n.desiredPlaybackState$.stateChangeStarted$.pipe(u((({from:t,to:e})=>`${t}-${e}`))),a=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let h=0,c='unknown';return s.add(r.subscribe((t=>{h&&window.clearTimeout(h),c=t,h=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(a.subscribe((()=>{window.clearTimeout(h),c='provider change',h=0}))),s.add(o.subscribe((()=>{h&&(window.clearTimeout(h),h=window.setTimeout((()=>d.next(c)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(h),s.unsubscribe()}}))).pipe(u((t=>({id:`ProviderHangup:${t}`,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),a.add(this.providerError$.pipe($(Ql,{leading:!1,trailing:!0})).subscribe((()=>{const e=Date.now();this.current$.getValue().destination===_.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(t[r])&&e<t[r]+jl?(t=[],this.switchToNextProvider()):(t[r]=e,this.reinitProvider()),r=(r+1)%zl}))),a}}const tp=(t,e,i)=>i*e+(1-i)*t;class ep{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Hh(`raw_${s}`),this.smoothedSeries$=new Hh(`smoothed_${s}`),this.reportedSeries$=new Hh(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=Math.pow(this.pastMeasures[t]-this.smoothed,2),i++);e/=i;const s=Math.sqrt(e),a=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=t,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(t),this.slow=tp(this.slow,t,this.params.emaAlphaSlow),this.fast=tp(this.fast,t,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>a||this.smoothed<n||(r(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))}}var ip;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(ip||(ip={}));const sp=new Map;let rp=ip.RUNTIME;const ap=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(ap,'test'),localStorage.removeItem(ap),rp=ip.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(ap),rp=ip.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;rp=ip.RUNTIME}}})();const np=(t,e)=>{switch(rp){case ip.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case ip.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case ip.RUNTIME:return void sp.set(t,e);default:n(rp)}},op=window.navigator.connection,dp=()=>{const t=null==op?void 0:op.downlink;if(s(t)&&10!==t)return 1e3*t},up=()=>{const t=null==op?void 0:op.rtt;if(s(t)&&3e3!==t)return t},hp=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class cp{constructor(e){var r,n;this.subscription=new i,this.concurrentDownloads=new Set,this.tuningConfig=e;const o=cp.load('one_video_throughput')||(e.useBrowserEstimation?dp():void 0)||5e3,d=null!==(n=null!==(r=cp.load('one_video_rtt'))&&void 0!==r?r:e.useBrowserEstimation?up():void 0)&&void 0!==n?n:0;if(this.throughput$=new t(o),this.rtt$=new t(d),this.rttAdjustedThroughput$=new t(hp(o,d,e.rttPenaltyRequestSize)),this.throughput=new ep({initial:o,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new ep({initial:d,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=dp();t&&this.throughput.next(t);const e=up();s(e)&&this.rtt.next(e)};op&&'onchange'in op&&this.subscription.add(a(op,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{np('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{np('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(y({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>hp(t,i,e.rttPenaltyRequestSize))),m((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(t){let e=0,s=g();const r=new i;switch(this.subscription.add(r),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:r.add(a(t,'progress').pipe(b()).subscribe((t=>{e=t.loaded,s=g()})));break;case 1:case 0:r.add(a(t,'loadstart').subscribe((()=>{e=0,s=g()})))}r.add(a(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,r=g(),a=t-e,n=r-s;this.addRawSpeed(a,n,1)}this.concurrentDownloads.delete(t),r.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=g();let r=0,a=g();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=({done:d,value:u})=>ud(this,void 0,void 0,(function*(){d?(this.addRawSpeed(i,g()-s,1),this.concurrentDownloads.delete(t)):u&&(i+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&g()-a>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,g()-a,this.concurrentDownloads.size),r=0,a=g()),yield null==e?void 0:e.read().then(o,n))}));this.concurrentDownloads.add(t),null==e||e.read().then(o,n)}addRawSpeed(t,e,i=1){if(cp.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){var e;const i=(t=>{var e,i;switch(rp){case ip.LOCAL_STORAGE:return null!==(e=localStorage.getItem(t))&&void 0!==e?e:void 0;case ip.SESSION_STORAGE:return null!==(i=sessionStorage.getItem(t))&&void 0!==i?i:void 0;case ip.RUNTIME:return sp.get(t);default:n(rp)}})(t);if(s(i))return null!==(e=parseInt(i,10))&&void 0!==e?e:void 0}}const lp={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:100},enableTelemetryAtStart:!1,formatsToAvoid:[D.DASH_WEBM,D.DASH_SEP,D.DASH_SEP_VK],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1};const pp=(t=(t=>t))=>({playbackState:e,seekState:s,playbackAbort$:a,looped$:n,position$:d})=>new S((h=>{let c;const l=e.transitionEnded$.pipe(m((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=e.stateChangeEnded$.pipe(m((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),f=s.stateChangeEnded$.pipe(m((({to:t})=>{var i,s;return t.state===x.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===P.PLAYING}))),v=s.stateChangeEnded$.pipe(m((({from:t,to:i})=>{var s,r;return t.state===x.Applying&&i.state===x.None&&(null!==(r=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:e.getState())===P.PLAYING}))),g=o(l,v).pipe(u((()=>t(d.getValue())))),S=o(o(p,f,a).pipe(u((()=>t(d.getValue())))),n.pipe(u(t)));return(new i).add(g.subscribe((e=>{c=t(e)}))).add(S.subscribe((e=>{const i=t(e);if(r(c)||c===i)return;const s={from:c,to:i};c=void 0,h.next(s)})))})),fp=pp((t=>t)),mp=pp((t=>Math.round(1e3*t)+Date.now())),vp={[_.SCREEN]:{vod:[D.HLS,D.HLS_ONDEMAND,D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS_JS,D.MPEG],live:[D.HLS_LIVE,D.DASH_LIVE,D.DASH_LIVE_WEBM]},[_.CHROMECAST]:{vod:[D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS,D.HLS_ONDEMAND,D.MPEG],live:[D.HLS_LIVE]}};class gp{constructor(s={}){if(this.subscription=new i,this.logger=new k,this.isPlaybackStarted=!1,this.desiredState={playbackState:new nd(P.STOPPED),seekState:new nd({state:x.None}),volume:new nd({volume:1,muted:!1}),videoTrack:new nd(void 0),autoVideoTrackSwitching:new nd(!0),autoVideoTrackLimits:new nd({}),isLooped:new nd(!1),externalTextTracks:new nd([]),currentTextTrack:new nd(void 0),textTrackCuesSettings:new nd({})},this.info={playbackState$:new t(P.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentBuffer$:new t(void 0),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(R.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)},this.events={inited$:new e,started$:new e,startAttempt$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,canplay$:new e,log$:new e},this.experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:qh},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(lp)){const s=lp[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?Object.assign(Object.assign({},s),r):null!=r?r:s}return e})(s),this.chromecastInitializer=new C({receiverApplicationId:s.chromecastReceiverId,isDisabled:s.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new cp(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),r=`Player.${String(e)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(t){var e,i;return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=null===(e=t.meta)||void 0===e?void 0:e.videoId,this.providerContainer=new Zl({screenFormatsPriority:[...vp[_.SCREEN].live,...vp[_.SCREEN].vod],chromecastFormatsPriority:[...vp[_.CHROMECAST].live,...vp[_.CHROMECAST].vod],sources:t.sources,meta:null!==(i=t.meta)&&void 0!==i?i:{},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.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:x.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===R.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===R.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){l(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>Object.assign({type:'external'},t)))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){l(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(r(t))return this.info.position$.getValue();const e=this.desiredState.seekState.getState(),i=e.state===x.None?void 0:e.position;return s(i)?i/1e3:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(o(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(u((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.autoQualityLimits$));const t=new i;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(m((t=>t.to===P.PLAYING)),m((()=>!this.isPlaybackStarted))).subscribe((()=>{this.initedAt=g(),this.events.inited$.next(),t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(m((t=>t.to===P.PLAYING||t.to===P.PAUSED)),p(0),b()).subscribe((t=>{const e=t.to===P.PLAYING,i=this.info.muted$.getValue(),s=e?i?I.SuccessWithoutSound:I.SuccessWithSound:I.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(m((t=>t.to===P.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case P.PAUSED:this.events.willPause$.next();break;case P.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===x.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},t),{state:x.Applying})):this.events.managedError$.next({id:`WillSeekIn${t.state}`,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===x.Applying&&(this.desiredState.seekState.setState({state:x.None}),this.events.seeked$.next())}))).add(e.current$.pipe(u((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(u((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(u((t=>t.map((({quality:t})=>t)).sort(((t,e)=>ad(t)?1:ad(e)?-1:ed(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).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(u((t=>t&&{start:t.from,end:t.to}))).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(u((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(u((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekState:t,position$:e})=>o(t.stateChangeEnded$.pipe(u((({to:t})=>{var e;return t.state===x.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),m(s)),e.pipe(m((()=>t.getState().state===x.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(v(!0)),e.providerOutput.seekedEvent$.pipe(v(!1))).pipe(c()).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(u((t=>({id:'NoProviders',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(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(b(),u((()=>g()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const r=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>r.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>r.next(!0))));const n=new t(!0);this.subscription.add(e.current$.subscribe((()=>n.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(m((({to:t})=>t===P.PLAYING)),b()).subscribe((()=>n.next(!1))));let d=0;const h=o(e.providerOutput.isBuffering$,r,n).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=r.getValue()||n.getValue();return t&&!i})),c());this.subscription.add(h.subscribe((t=>{t?d=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(d),this.info.isStalled$.next(!1))})));const p=new i;this.subscription.add(p);const f=o(a(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(m((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),p.unsubscribe(),t){case!0:p.add(mp({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:f,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break;case!1:p.add(fp({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:f,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(u((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(m((t=>t.length>0)),b()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=jh(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(o(this.desiredState.videoTrack.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(u((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;const e=null===(t=this.providerContainer)||void 0===t?void 0:t.providerOutput;l(this.providerContainer),l(e),Vh={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Uh=t})),this.providerContainer.current$.subscribe((({type:t})=>Fh('provider',t))),e.duration$.subscribe((t=>Fh('duration',t))),e.availableVideoTracks$.pipe(m((t=>!!t.length)),b()).subscribe((t=>Fh('tracks',t))),this.events.fatalError$.subscribe(new Hh('fatalError')),this.events.managedError$.subscribe(new Hh('managedError')),e.position$.subscribe(new Hh('position')),e.currentVideoTrack$.pipe(u((t=>null==t?void 0:t.quality))).subscribe(new Hh('quality')),e.currentBuffer$.subscribe(new Hh('buffer')),e.isBuffering$.subscribe(new Hh('isBuffering'))].forEach((t=>this.subscription.add(t))),Fh('codecs',Object.keys(Vl).filter((t=>Vl[t])))}}const Sp='@vkontakte/videoplayer-core@2.0.65';export{R as ChromecastState,L as HttpConnectionType,P as PlaybackState,gp as Player,Sp as SDK_VERSION,I as StartStatus,D as VideoFormat,Ko as VideoQuality};
6
+ import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as r,fromEvent as a,assertNever as n,merge as o,tap as d,map as u,observableFrom as h,filterChanged as c,assertNonNullable as l,debounce as p,timeout as f,filter as m,mapTo as v,now as g,Observable as S,once as b,combine as y,abortable as T,getExponentialDelay as E,interval as w,throttle as $,Logger as k}from'@vkontakte/videoplayer-shared/es2015.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/es2015.esm.js';import A from'lodash/debounce';var P,D,_,R,I,L,C;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_ONDEMAND_VK='DASH_ONDEMAND_VK',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(D||(D={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(_||(_={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(R||(R={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(I||(I={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(L||(L={})),function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(C||(C={}));class x{constructor(r){var a;this.connection$=new t(void 0),this.castState$=new t(R.NOT_AVAILABLE),this.errorEvent$=new e,this.realCastState$=new t(R.NOT_AVAILABLE),this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const n='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${n}`}),r.isDisabled||!n)return;var o;s(null===(a=window.chrome)||void 0===a?void 0:a.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(o='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();r(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();r(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(a(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{var e,s;switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(s=null===(e=i.getCurrentSession())||void 0===e?void 0:e.getMediaSession())||void 0===s?void 0:s.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 n(t.sessionState)}}))).add(o(a(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),h([i.getCastState()])).pipe(c(),u(O),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var n;const o=a===R.CONNECTED,d=s(this.connection$.getValue());if(o&&!d){const s=i.getCurrentSession();l(s);const a=s.getCastDevice(),o=null===(n=s.getMediaSession())||void 0===n?void 0:n.media.contentId;(r(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!o&&d&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===R.CONNECTED?s(this.connection$.getValue())?R.CONNECTED:R.AVAILABLE:a)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const O=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return R.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return R.AVAILABLE;case cast.framework.CastState.CONNECTING:return R.CONNECTING;case cast.framework.CastState.CONNECTED:return R.CONNECTED;default:return n(t)}};var N='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},B=function(t){return t&&t.Math==Math&&t},M=B('object'==typeof globalThis&&globalThis)||B('object'==typeof window&&window)||B('object'==typeof self&&self)||B('object'==typeof N&&N)||function(){return this}()||Function('return this')(),U=function(t){try{return!!t()}catch(t){return!0}},V=!U((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),q=V,F=Function.prototype,H=F.apply,G=F.call,Y='object'==typeof Reflect&&Reflect.apply||(q?G.bind(H):function(){return G.apply(H,arguments)}),j=V,z=Function.prototype,Q=z.bind,W=z.call,J=j&&Q.bind(W,W),K=j?function(t){return t&&J(t)}:function(t){return t&&function(){return W.apply(t,arguments)}},X=function(t){return'function'==typeof t},Z={},tt=!U((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),et=V,it=Function.prototype.call,st=et?it.bind(it):function(){return it.apply(it,arguments)},rt={},at={}.propertyIsEnumerable,nt=Object.getOwnPropertyDescriptor,ot=nt&&!at.call({1:2},1);rt.f=ot?function(t){var e=nt(this,t);return!!e&&e.enumerable}:at;var dt,ut,ht=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},ct=K,lt=ct({}.toString),pt=ct(''.slice),ft=function(t){return pt(lt(t),8,-1)},mt=U,vt=ft,gt=Object,St=K(''.split),bt=mt((function(){return!gt('z').propertyIsEnumerable(0)}))?function(t){return'String'==vt(t)?St(t,''):gt(t)}:gt,yt=TypeError,Tt=function(t){if(null==t)throw yt('Can\'t call method on '+t);return t},Et=bt,wt=Tt,$t=function(t){return Et(wt(t))},kt=X,At=function(t){return'object'==typeof t?null!==t:kt(t)},Pt={},Dt=Pt,_t=M,Rt=X,It=function(t){return Rt(t)?t:void 0},Lt=function(t,e){return arguments.length<2?It(Dt[t])||It(_t[t]):Dt[t]&&Dt[t][e]||_t[t]&&_t[t][e]},Ct=K({}.isPrototypeOf),xt=Lt('navigator','userAgent')||'',Ot=M,Nt=xt,Bt=Ot.process,Mt=Ot.Deno,Ut=Bt&&Bt.versions||Mt&&Mt.version,Vt=Ut&&Ut.v8;Vt&&(ut=(dt=Vt.split('.'))[0]>0&&dt[0]<4?1:+(dt[0]+dt[1])),!ut&&Nt&&(!(dt=Nt.match(/Edge\/(\d+)/))||dt[1]>=74)&&(dt=Nt.match(/Chrome\/(\d+)/))&&(ut=+dt[1]);var qt=ut,Ft=qt,Ht=U,Gt=!!Object.getOwnPropertySymbols&&!Ht((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Ft&&Ft<41})),Yt=Gt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,jt=Lt,zt=X,Qt=Ct,Wt=Object,Jt=Yt?function(t){return'symbol'==typeof t}:function(t){var e=jt('Symbol');return zt(e)&&Qt(e.prototype,Wt(t))},Kt=String,Xt=function(t){try{return Kt(t)}catch(t){return'Object'}},Zt=X,te=Xt,ee=TypeError,ie=function(t){if(Zt(t))return t;throw ee(te(t)+' is not a function')},se=ie,re=function(t,e){var i=t[e];return null==i?void 0:se(i)},ae=st,ne=X,oe=At,de=TypeError,ue={exports:{}},he=M,ce=Object.defineProperty,le=function(t,e){try{ce(he,t,{value:e,configurable:!0,writable:!0})}catch(i){he[t]=e}return e},pe=M['__core-js_shared__']||le('__core-js_shared__',{}),fe=pe;(ue.exports=function(t,e){return fe[t]||(fe[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.24.1',mode:'pure',copyright:'© 2014-2022 Denis Pushkarev (zloirock.ru)',license:'https://github.com/zloirock/core-js/blob/v3.24.1/LICENSE',source:'https://github.com/zloirock/core-js'});var me=Tt,ve=Object,ge=function(t){return ve(me(t))},Se=ge,be=K({}.hasOwnProperty),ye=Object.hasOwn||function(t,e){return be(Se(t),e)},Te=K,Ee=0,we=Math.random(),$e=Te(1..toString),ke=function(t){return'Symbol('+(void 0===t?'':t)+')_'+$e(++Ee+we,36)},Ae=M,Pe=ue.exports,De=ye,_e=ke,Re=Gt,Ie=Yt,Le=Pe('wks'),Ce=Ae.Symbol,xe=Ce&&Ce.for,Oe=Ie?Ce:Ce&&Ce.withoutSetter||_e,Ne=function(t){if(!De(Le,t)||!Re&&'string'!=typeof Le[t]){var e='Symbol.'+t;Re&&De(Ce,t)?Le[t]=Ce[t]:Le[t]=Ie&&xe?xe(e):Oe(e)}return Le[t]},Be=st,Me=At,Ue=Jt,Ve=re,qe=function(t,e){var i,s;if('string'===e&&ne(i=t.toString)&&!oe(s=ae(i,t)))return s;if(ne(i=t.valueOf)&&!oe(s=ae(i,t)))return s;if('string'!==e&&ne(i=t.toString)&&!oe(s=ae(i,t)))return s;throw de('Can\'t convert object to primitive value')},Fe=TypeError,He=Ne('toPrimitive'),Ge=function(t,e){if(!Me(t)||Ue(t))return t;var i,s=Ve(t,He);if(s){if(void 0===e&&(e='default'),i=Be(s,t,e),!Me(i)||Ue(i))return i;throw Fe('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),qe(t,e)},Ye=Jt,je=function(t){var e=Ge(t,'string');return Ye(e)?e:e+''},ze=At,Qe=M.document,We=ze(Qe)&&ze(Qe.createElement),Je=function(t){return We?Qe.createElement(t):{}},Ke=Je,Xe=!tt&&!U((function(){return 7!=Object.defineProperty(Ke('div'),'a',{get:function(){return 7}}).a})),Ze=tt,ti=st,ei=rt,ii=ht,si=$t,ri=je,ai=ye,ni=Xe,oi=Object.getOwnPropertyDescriptor;Z.f=Ze?oi:function(t,e){if(t=si(t),e=ri(e),ni)try{return oi(t,e)}catch(t){}if(ai(t,e))return ii(!ti(ei.f,t,e),t[e])};var di=U,ui=X,hi=/#|\.prototype\./,ci=function(t,e){var i=pi[li(t)];return i==mi||i!=fi&&(ui(e)?di(e):!!e)},li=ci.normalize=function(t){return String(t).replace(hi,'.').toLowerCase()},pi=ci.data={},fi=ci.NATIVE='N',mi=ci.POLYFILL='P',vi=ci,gi=ie,Si=V,bi=K(K.bind),yi=function(t,e){return gi(t),void 0===e?t:Si?bi(t,e):function(){return t.apply(e,arguments)}},Ti={},Ei=tt&&U((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),wi=At,$i=String,ki=TypeError,Ai=function(t){if(wi(t))return t;throw ki($i(t)+' is not an object')},Pi=tt,Di=Xe,_i=Ei,Ri=Ai,Ii=je,Li=TypeError,Ci=Object.defineProperty,xi=Object.getOwnPropertyDescriptor;Ti.f=Pi?_i?function(t,e,i){if(Ri(t),e=Ii(e),Ri(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=xi(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Ci(t,e,i)}:Ci:function(t,e,i){if(Ri(t),e=Ii(e),Ri(i),Di)try{return Ci(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Li('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Oi=Ti,Ni=ht,Bi=tt?function(t,e,i){return Oi.f(t,e,Ni(1,i))}:function(t,e,i){return t[e]=i,t},Mi=M,Ui=Y,Vi=K,qi=X,Fi=Z.f,Hi=vi,Gi=Pt,Yi=yi,ji=Bi,zi=ye,Qi=function(t){var e=function(i,s,r){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,r)}return Ui(t,this,arguments)};return e.prototype=t.prototype,e},Wi=function(t,e){var i,s,r,a,n,o,d,u,h=t.target,c=t.global,l=t.stat,p=t.proto,f=c?Mi:l?Mi[h]:(Mi[h]||{}).prototype,m=c?Gi:Gi[h]||ji(Gi,h,{})[h],v=m.prototype;for(r in e)i=!Hi(c?r:h+(l?'.':'#')+r,t.forced)&&f&&zi(f,r),n=m[r],i&&(o=t.dontCallGetSet?(u=Fi(f,r))&&u.value:f[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(d=t.bind&&i?Yi(a,Mi):t.wrap&&i?Qi(a):p&&qi(a)?Vi(a):a,(t.sham||a&&a.sham||n&&n.sham)&&ji(d,'sham',!0),ji(m,r,d),p&&(zi(Gi,s=h+'Prototype')||ji(Gi,s,{}),ji(Gi[s],r,a),t.real&&v&&!v[r]&&ji(v,r,a)))},Ji='process'==ft(M.process),Ki=Bi,Xi=function(t,e,i,s){return s&&s.enumerable?t[e]=i:Ki(t,e,i),t},Zi=(TypeError,K);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Zi(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var ts={};ts[Ne('toStringTag')]='z';var es='[object z]'===String(ts),is=es,ss=X,rs=ft,as=Ne('toStringTag'),ns=Object,os='Arguments'==rs(function(){return arguments}()),ds=is?rs:function(t){var e,i,s;return void 0===t?'Undefined':null===t?'Null':'string'==typeof(i=function(t,e){try{return t[e]}catch(t){}}(e=ns(t),as))?i:os?rs(e):'Object'==(s=rs(e))&&ss(e.callee)?'Arguments':s},us=ds,hs=es?{}.toString:function(){return'[object '+us(this)+']'},cs=es,ls=Ti.f,ps=Bi,fs=ye,ms=hs,vs=Ne('toStringTag'),gs=function(t,e,i,s){if(t){var r=i?t:t.prototype;fs(r,vs)||ls(r,vs,{configurable:!0,value:e}),s&&!cs&&ps(r,'toString',ms)}},Ss=Lt,bs=Ti,ys=tt,Ts=Ne('species'),Es=Ct,ws=TypeError,$s=X,ks=pe,As=K(Function.toString);$s(ks.inspectSource)||(ks.inspectSource=function(t){return As(t)});var Ps=ks.inspectSource,Ds=K,_s=U,Rs=X,Is=ds,Ls=Ps,Cs=function(){},xs=[],Os=Lt('Reflect','construct'),Ns=/^\s*(?:class|function)\b/,Bs=Ds(Ns.exec),Ms=!Ns.exec(Cs),Us=function(t){if(!Rs(t))return!1;try{return Os(Cs,xs,t),!0}catch(t){return!1}},Vs=function(t){if(!Rs(t))return!1;switch(Is(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return Ms||!!Bs(Ns,Ls(t))}catch(t){return!0}};Vs.sham=!0;var qs,Fs,Hs,Gs,Ys=!Os||_s((function(){var t;return Us(Us.call)||!Us(Object)||!Us((function(){t=!0}))||t}))?Vs:Us,js=Xt,zs=TypeError,Qs=Ai,Ws=function(t){if(Ys(t))return t;throw zs(js(t)+' is not a constructor')},Js=Ne('species'),Ks=function(t,e){var i,s=Qs(t).constructor;return void 0===s||null==(i=Qs(s)[Js])?e:Ws(i)},Xs=Lt('document','documentElement'),Zs=K([].slice),tr=TypeError,er=/(?:ipad|iphone|ipod).*applewebkit/i.test(xt),ir=M,sr=Y,rr=yi,ar=X,nr=ye,or=U,dr=Xs,ur=Zs,hr=Je,cr=function(t,e){if(t<e)throw tr('Not enough arguments');return t},lr=er,pr=Ji,fr=ir.setImmediate,mr=ir.clearImmediate,vr=ir.process,gr=ir.Dispatch,Sr=ir.Function,br=ir.MessageChannel,yr=ir.String,Tr=0,Er={};try{qs=ir.location}catch(t){}var wr=function(t){if(nr(Er,t)){var e=Er[t];delete Er[t],e()}},$r=function(t){return function(){wr(t)}},kr=function(t){wr(t.data)},Ar=function(t){ir.postMessage(yr(t),qs.protocol+'//'+qs.host)};fr&&mr||(fr=function(t){cr(arguments.length,1);var e=ar(t)?t:Sr(t),i=ur(arguments,1);return Er[++Tr]=function(){sr(e,void 0,i)},Fs(Tr),Tr},mr=function(t){delete Er[t]},pr?Fs=function(t){vr.nextTick($r(t))}:gr&&gr.now?Fs=function(t){gr.now($r(t))}:br&&!lr?(Gs=(Hs=new br).port2,Hs.port1.onmessage=kr,Fs=rr(Gs.postMessage,Gs)):ir.addEventListener&&ar(ir.postMessage)&&!ir.importScripts&&qs&&'file:'!==qs.protocol&&!or(Ar)?(Fs=Ar,ir.addEventListener('message',kr,!1)):Fs='onreadystatechange'in hr('script')?function(t){dr.appendChild(hr('script')).onreadystatechange=function(){dr.removeChild(this),wr(t)}}:function(t){setTimeout($r(t),0)});var Pr,Dr,_r,Rr,Ir,Lr,Cr,xr,Or={set:fr,clear:mr},Nr=M,Br=/ipad|iphone|ipod/i.test(xt)&&void 0!==Nr.Pebble,Mr=/web0s(?!.*chrome)/i.test(xt),Ur=M,Vr=yi,qr=Z.f,Fr=Or.set,Hr=er,Gr=Br,Yr=Mr,jr=Ji,zr=Ur.MutationObserver||Ur.WebKitMutationObserver,Qr=Ur.document,Wr=Ur.process,Jr=Ur.Promise,Kr=qr(Ur,'queueMicrotask'),Xr=Kr&&Kr.value;Xr||(Pr=function(){var t,e;for(jr&&(t=Wr.domain)&&t.exit();Dr;){e=Dr.fn,Dr=Dr.next;try{e()}catch(t){throw Dr?Rr():_r=void 0,t}}_r=void 0,t&&t.enter()},Hr||jr||Yr||!zr||!Qr?!Gr&&Jr&&Jr.resolve?((Cr=Jr.resolve(void 0)).constructor=Jr,xr=Vr(Cr.then,Cr),Rr=function(){xr(Pr)}):jr?Rr=function(){Wr.nextTick(Pr)}:(Fr=Vr(Fr,Ur),Rr=function(){Fr(Pr)}):(Ir=!0,Lr=Qr.createTextNode(''),new zr(Pr).observe(Lr,{characterData:!0}),Rr=function(){Lr.data=Ir=!Ir}));var Zr=Xr||function(t){var e={fn:t,next:void 0};_r&&(_r.next=e),Dr||(Dr=e,Rr()),_r=e},ta=M,ea=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},ia=function(){this.head=null,this.tail=null};ia.prototype={add:function(t){var e={item:t,next:null};this.head?this.tail.next=e:this.head=e,this.tail=e},get:function(){var t=this.head;if(t)return this.head=t.next,this.tail===t&&(this.tail=null),t.item}};var sa,ra,aa,na=ia,oa=X,da=Ps,ua=M.WeakMap,ha=oa(ua)&&/native code/.test(da(ua)),ca=ue.exports,la=ke,pa=ca('keys'),fa=function(t){return pa[t]||(pa[t]=la(t))},ma={},va=ha,ga=M,Sa=K,ba=At,ya=Bi,Ta=ye,Ea=pe,wa=fa,$a=ma,ka=ga.TypeError,Aa=ga.WeakMap;if(va||Ea.state){var Pa=Ea.state||(Ea.state=new Aa),Da=Sa(Pa.get),_a=Sa(Pa.has),Ra=Sa(Pa.set);sa=function(t,e){if(_a(Pa,t))throw new ka('Object already initialized');return e.facade=t,Ra(Pa,t,e),e},ra=function(t){return Da(Pa,t)||{}},aa=function(t){return _a(Pa,t)}}else{var Ia=wa('state');$a[Ia]=!0,sa=function(t,e){if(Ta(t,Ia))throw new ka('Object already initialized');return e.facade=t,ya(t,Ia,e),e},ra=function(t){return Ta(t,Ia)?t[Ia]:{}},aa=function(t){return Ta(t,Ia)}}var La={set:sa,get:ra,has:aa,enforce:function(t){return aa(t)?ra(t):sa(t,{})},getterFor:function(t){return function(e){var i;if(!ba(e)||(i=ra(e)).type!==t)throw ka('Incompatible receiver, '+t+' required');return i}}},Ca=M.Promise,xa='object'==typeof Deno&&Deno&&'object'==typeof Deno.version,Oa=!xa&&!Ji&&'object'==typeof window&&'object'==typeof document,Na=M,Ba=Ca,Ma=X,Ua=vi,Va=Ps,qa=Ne,Fa=Oa,Ha=xa,Ga=qt,Ya=Ba&&Ba.prototype,ja=qa('species'),za=!1,Qa=Ma(Na.PromiseRejectionEvent),Wa={CONSTRUCTOR:Ua('Promise',(function(){var t=Va(Ba),e=t!==String(Ba);if(!e&&66===Ga)return!0;if(!Ya.catch||!Ya.finally)return!0;if(!Ga||Ga<51||!/native code/.test(t)){var i=new Ba((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};if((i.constructor={})[ja]=s,!(za=i.then((function(){}))instanceof s))return!0}return!e&&(Fa||Ha)&&!Qa})),REJECTION_EVENT:Qa,SUBCLASSING:za},Ja={},Ka=ie,Xa=function(t){var e,i;this.promise=new t((function(t,s){if(void 0!==e||void 0!==i)throw TypeError('Bad Promise constructor');e=t,i=s})),this.resolve=Ka(e),this.reject=Ka(i)};Ja.f=function(t){return new Xa(t)};var Za,tn,en=Wi,sn=Ji,rn=M,an=st,nn=Xi,on=gs,dn=function(t){var e=Ss(t),i=bs.f;ys&&e&&!e[Ts]&&i(e,Ts,{configurable:!0,get:function(){return this}})},un=ie,hn=X,cn=At,ln=function(t,e){if(Es(e,t))return t;throw ws('Incorrect invocation')},pn=Ks,fn=Or.set,mn=Zr,vn=function(t,e){var i=ta.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},gn=ea,Sn=na,bn=La,yn=Ca,Tn=Ja,En=Wa.CONSTRUCTOR,wn=Wa.REJECTION_EVENT,$n=bn.getterFor('Promise'),kn=bn.set,An=yn&&yn.prototype,Pn=yn,Dn=An,_n=rn.TypeError,Rn=rn.document,In=rn.process,Ln=Tn.f,Cn=Ln,xn=!!(Rn&&Rn.createEvent&&rn.dispatchEvent),On=function(t){var e;return!(!cn(t)||!hn(e=t.then))&&e},Nn=function(t,e){var i,s,r,a=e.value,n=1==e.state,o=n?t.ok:t.fail,d=t.resolve,u=t.reject,h=t.domain;try{o?(n||(2===e.rejection&&qn(e),e.rejection=1),!0===o?i=a:(h&&h.enter(),i=o(a),h&&(h.exit(),r=!0)),i===t.promise?u(_n('Promise-chain cycle')):(s=On(i))?an(s,i,d,u):d(i)):u(a)}catch(t){h&&!r&&h.exit(),u(t)}},Bn=function(t,e){t.notified||(t.notified=!0,mn((function(){for(var i,s=t.reactions;i=s.get();)Nn(i,t);t.notified=!1,e&&!t.rejection&&Un(t)})))},Mn=function(t,e,i){var s,r;xn?((s=Rn.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),rn.dispatchEvent(s)):s={promise:e,reason:i},!wn&&(r=rn['on'+t])?r(s):'unhandledrejection'===t&&vn('Unhandled promise rejection',i)},Un=function(t){an(fn,rn,(function(){var e,i=t.facade,s=t.value;if(Vn(t)&&(e=gn((function(){sn?In.emit('unhandledRejection',s,i):Mn('unhandledrejection',i,s)})),t.rejection=sn||Vn(t)?2:1,e.error))throw e.value}))},Vn=function(t){return 1!==t.rejection&&!t.parent},qn=function(t){an(fn,rn,(function(){var e=t.facade;sn?In.emit('rejectionHandled',e):Mn('rejectionhandled',e,t.value)}))},Fn=function(t,e,i){return function(s){t(e,s,i)}},Hn=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,Bn(t,!0))},Gn=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw _n('Promise can\'t be resolved itself');var s=On(e);s?mn((function(){var i={done:!1};try{an(s,e,Fn(Gn,i,t),Fn(Hn,i,t))}catch(e){Hn(i,e,t)}})):(t.value=e,t.state=1,Bn(t,!1))}catch(e){Hn({done:!1},e,t)}}};En&&(Dn=(Pn=function(t){ln(this,Dn),un(t),an(Za,this);var e=$n(this);try{t(Fn(Gn,e),Fn(Hn,e))}catch(t){Hn(e,t)}}).prototype,(Za=function(t){kn(this,{type:'Promise',done:!1,notified:!1,parent:!1,reactions:new Sn,rejection:!1,state:0,value:void 0})}).prototype=nn(Dn,'then',(function(t,e){var i=$n(this),s=Ln(pn(this,Pn));return i.parent=!0,s.ok=!hn(t)||t,s.fail=hn(e)&&e,s.domain=sn?In.domain:void 0,0==i.state?i.reactions.add(s):mn((function(){Nn(s,i)})),s.promise})),tn=function(){var t=new Za,e=$n(t);this.promise=t,this.resolve=Fn(Gn,e),this.reject=Fn(Hn,e)},Tn.f=Ln=function(t){return t===Pn||undefined===t?new tn(t):Cn(t)}),en({global:!0,constructor:!0,wrap:!0,forced:En},{Promise:Pn}),on(Pn,'Promise',!1,!0),dn('Promise');var Yn={},jn=Yn,zn=Ne('iterator'),Qn=Array.prototype,Wn=Math.ceil,Jn=Math.floor,Kn=Math.trunc||function(t){var e=+t;return(e>0?Jn:Wn)(e)},Xn=function(t){var e=+t;return e!=e||0===e?0:Kn(e)},Zn=Xn,to=Math.min,eo=function(t){return t>0?to(Zn(t),9007199254740991):0},io=function(t){return eo(t.length)},so=ds,ro=re,ao=Yn,no=Ne('iterator'),oo=function(t){if(null!=t)return ro(t,no)||ro(t,'@@iterator')||ao[so(t)]},uo=st,ho=ie,co=Ai,lo=Xt,po=oo,fo=TypeError,mo=st,vo=Ai,go=re,So=yi,bo=st,yo=Ai,To=Xt,Eo=function(t){return void 0!==t&&(jn.Array===t||Qn[zn]===t)},wo=io,$o=Ct,ko=function(t,e){var i=arguments.length<2?po(t):e;if(ho(i))return co(uo(i,t));throw fo(lo(t)+' is not iterable')},Ao=oo,Po=function(t,e,i){var s,r;vo(t);try{if(!(s=go(t,'return'))){if('throw'===e)throw i;return i}s=mo(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return vo(s),i},Do=TypeError,_o=function(t,e){this.stopped=t,this.result=e},Ro=_o.prototype,Io=function(t,e,i){var s,r,a,n,o,d,u,h=i&&i.that,c=!(!i||!i.AS_ENTRIES),l=!(!i||!i.IS_RECORD),p=!(!i||!i.IS_ITERATOR),f=!(!i||!i.INTERRUPTED),m=So(e,h),v=function(t){return s&&Po(s,'normal',t),new _o(!0,t)},g=function(t){return c?(yo(t),f?m(t[0],t[1],v):m(t[0],t[1])):f?m(t,v):m(t)};if(l)s=t.iterator;else if(p)s=t;else{if(!(r=Ao(t)))throw Do(To(t)+' is not iterable');if(Eo(r)){for(a=0,n=wo(t);n>a;a++)if((o=g(t[a]))&&$o(Ro,o))return o;return new _o(!1)}s=ko(t,r)}for(d=l?t.next:s.next;!(u=bo(d,s)).done;){try{o=g(u.value)}catch(t){Po(s,'throw',t)}if('object'==typeof o&&o&&$o(Ro,o))return o}return new _o(!1)},Lo=Ne('iterator'),Co=!1;try{var xo=0,Oo={next:function(){return{done:!!xo++}},return:function(){Co=!0}};Oo[Lo]=function(){return this},Array.from(Oo,(function(){throw 2}))}catch(t){}var No=Ca,Bo=Wa.CONSTRUCTOR||!function(t,e){if(!e&&!Co)return!1;var i=!1;try{var s={};s[Lo]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i}((function(t){No.all(t).then(void 0,(function(){}))})),Mo=st,Uo=ie,Vo=Ja,qo=ea,Fo=Io;Wi({target:'Promise',stat:!0,forced:Bo},{all:function(t){var e=this,i=Vo.f(e),s=i.resolve,r=i.reject,a=qo((function(){var i=Uo(e.resolve),a=[],n=0,o=1;Fo(t,(function(t){var d=n++,u=!1;o++,Mo(i,e,t).then((function(t){u||(u=!0,a[d]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise}});var Ho=Wi,Go=Wa.CONSTRUCTOR;Ca&&Ca.prototype,Ho({target:'Promise',proto:!0,forced:Go,real:!0},{catch:function(t){return this.then(void 0,t)}});var Yo=st,jo=ie,zo=Ja,Qo=ea,Wo=Io;Wi({target:'Promise',stat:!0,forced:Bo},{race:function(t){var e=this,i=zo.f(e),s=i.reject,r=Qo((function(){var r=jo(e.resolve);Wo(t,(function(t){Yo(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var Jo=st,Ko=Ja;Wi({target:'Promise',stat:!0,forced:Wa.CONSTRUCTOR},{reject:function(t){var e=Ko.f(this);return Jo(e.reject,void 0,t),e.promise}});var Xo=Ai,Zo=At,td=Ja,ed=function(t,e){if(Xo(t),Zo(e)&&e.constructor===t)return e;var i=td.f(t);return(0,i.resolve)(e),i.promise},id=Wi,sd=Ca,rd=Wa.CONSTRUCTOR,ad=ed,nd=Lt('Promise'),od=!rd;id({target:'Promise',stat:!0,forced:true},{resolve:function(t){return ad(od&&this===nd?sd:this,t)}});var dd=Wi,ud=Ca,hd=U,cd=Lt,ld=X,pd=Ks,fd=ed,md=ud&&ud.prototype;dd({target:'Promise',proto:!0,real:!0,forced:!!ud&&hd((function(){md.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=pd(this,cd('Promise')),i=ld(t);return this.then(i?function(i){return fd(e,t()).then((function(){return i}))}:t,i?function(i){return fd(e,t()).then((function(){throw i}))}:t)}});var vd,gd=Lt,Sd=gd('Promise','finally');!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(vd||(vd={}));var bd,yd=(t,e=0,i=vd.OFFSET_P)=>{switch(i){case vd.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case vd.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:n(i)}return t},Td=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(bd||(bd={}));const Ed={[bd.Q_144P]:{width:256,height:144},[bd.Q_240P]:{width:428,height:240},[bd.Q_360P]:{width:640,height:360},[bd.Q_480P]:{width:856,height:480},[bd.Q_720P]:{width:1280,height:720},[bd.Q_1080P]:{width:1920,height:1080},[bd.Q_1440P]:{width:2560,height:1440},[bd.Q_2160P]:{width:3840,height:2160},[bd.Q_4320P]:{width:7680,height:4320}},wd=(t,e)=>Ed[t].height>Ed[e].height,$d=(t,e)=>Ed[t].height<Ed[e].height,kd=Object.keys(Ed).sort(((t,e)=>$d(t,e)?-1:1)),Ad=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return kd.find((t=>{const e=Ed[t];return e.width>=s&&e.height>=i}))},Pd=t=>t===bd.INVARIANT;class Dd{constructor(t){this.transitionStarted$=new e,this.transitionEnded$=new e,this.transitionUpdated$=new e,this.forceChanged$=new e,this.stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$),this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var _d;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(_d||(_d={}));class Rd{constructor(t){this.subscription=new i,this.loadMediaTimeoutSubscription=new i,this.videoState=new Dd(_d.STOPPED),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)if((null==s?void 0:s.to)===P.PAUSED||r.state!==C.Requested||t===_d.STOPPED)switch(i){case P.PLAYING:switch(t){case _d.PLAYING:break;case _d.PAUSED:case _d.READY:this.videoState.startTransitionTo(_d.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case _d.STOPPED:this.videoState.startTransitionTo(_d.READY),this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case _d.PLAYING:this.videoState.startTransitionTo(_d.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case _d.PAUSED:break;case _d.READY:this.videoState.startTransitionTo(_d.PAUSED),this.videoState.setState(_d.PAUSED);break;case _d.STOPPED:this.videoState.startTransitionTo(_d.READY),this.prepare();break;default:n(t)}break;default:n(i)}else this.seek(r.position)}else t!==_d.STOPPED&&(this.videoState.startTransitionTo(_d.STOPPED),this.stop())},this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case D.MPEG:case D.DASH:case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.HLS:case D.HLS_JS:case D.HLS_ONDEMAND:return!1;case D.HLS_LIVE:case D.DASH_LIVE:case D.DASH_LIVE_WEBM:return!0;default:return n(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(o(this.videoState.stateChangeStarted$.pipe(u((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(u((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const s=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new e;t.add(i.pipe(p(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);(this.params.desiredState.seekState.getState().state===C.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),Td(this.params.desiredState.playbackState,P.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:n(i)}})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),s(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));s(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)),this.syncPlayback)}restoreSession(t){this.log({message:'restoreSession'});const{remotePlayer:e}=this.params.connection;if(t.playerState!==chrome.cast.media.PlayerState.IDLE){e.isPaused?(this.videoState.setState(_d.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(_d.PLAYING),Td(this.params.desiredState.playbackState,P.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekState.setState({state:C.None})}}prepare(){const t=this.params.format;this.log({message:`[prepare] format: ${t}`});const e=this.createMediaInfo(t),i=this.createLoadRequest(e);this.loadMedia(i)}handleRemotePause(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==_d.PAUSED&&t!==_d.PLAYING||(this.videoState.setState(_d.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==_d.PLAYING&&t!==_d.PAUSED||(this.videoState.setState(_d.PLAYING),Td(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===_d.READY&&this.videoState.setState(_d.READY)}handleRemoteStop(){this.videoState.getState()!==_d.STOPPED&&this.videoState.setState(_d.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){var e;const i=this.params.source;let r,a,o;switch(t){case D.MPEG:{const e=i[t];l(e);const s=Object.keys(e).sort(((t,e)=>t===e?0:t===bd.INVARIANT?1:e===bd.INVARIANT?-1:$d(t,e)?1:-1))[0];l(s);const n=e[s];l(n),r=n,a='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS:case D.HLS_ONDEMAND:{const e=i[t];l(e),r=e.url,a='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case D.DASH_SEP:case D.DASH_SEP_VK:case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:case D.DASH_WEBM_VK:case D.DASH_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case D.HLS_LIVE:{const e=i[t];l(e),r=yd(e.url),a='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case D.DASH_LIVE_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case D.HLS_JS:case D.DASH:case D.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return n(t)}const d=new chrome.cast.media.MediaInfo(null!==(e=this.params.meta.videoId)&&void 0!==e?e:r,a);d.contentUrl=r,d.streamType=o,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:h}=this.params.meta;return s(u)&&(d.metadata.title=u),s(h)&&(d.metadata.subtitle=h),d}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===C.Applying||i.state===C.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(f(7e3).subscribe((()=>e('timeout(7000)'))))}));Sd(Promise.race([e,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.handleRemoteReady()}),(t=>{const e=`[prepare] loadMedia failed, format: ${this.params.format}, reason: ${t}`;this.log({message:e}),this.params.output.error$.next({id:'ChromecastProvider.loadMedia',message:e,thrown:t})})),(()=>{this.loadMediaTimeoutSubscription.unsubscribe()}))}logRemoteEvent(t){this.log({message:`[remoteEvent] ${JSON.stringify(t)}`})}}function Id(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{d(s.next(t))}catch(t){a(t)}}function o(t){try{d(s.throw(t))}catch(t){a(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}d((s=s.apply(t,e||[])).next())}))}function Ld(t){return this instanceof Ld?(this.v=t,this):new Ld(t)}function Cd(t,e,i){if(!Symbol.asyncIterator)throw new TypeError('Symbol.asyncIterator is not defined.');var s,r=i.apply(t,e||[]),a=[];return s={},n('next'),n('throw'),n('return'),s[Symbol.asyncIterator]=function(){return this},s;function n(t){r[t]&&(s[t]=function(e){return new Promise((function(i,s){a.push([t,e,i,s])>1||o(t,e)}))})}function o(t,e){try{(i=r[t](e)).value instanceof Ld?Promise.resolve(i.value.v).then(d,u):h(a[0][2],i)}catch(t){h(a[0][3],t)}var i}function d(t){o('next',t)}function u(t){o('throw',t)}function h(t,e){t(e),a.shift(),a.length&&o(a[0][0],a[0][1])}}class xd{constructor(){Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}addEventListener(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}removeEventListener(t,e){if(!(t in this.listeners))return;const i=this.listeners[t];for(let t=0,s=i.length;t<s;t++)if(i[t].callback===e)return void i.splice(t,1)}dispatchEvent(t){if(!(t.type in this.listeners))return;const e=this.listeners[t.type].slice();for(let i=0,s=e.length;i<s;i++){const s=e[i];try{s.callback.call(this,t)}catch(t){Promise.resolve().then((()=>{throw t}))}s.options&&s.options.once&&this.removeEventListener(t.type,s.callback)}return!t.defaultPrevented}}class Od extends xd{constructor(){super(),this.listeners||xd.call(this),Object.defineProperty(this,'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(this,'onabort',{value:null,writable:!0,configurable:!0})}toString(){return'[object AbortSignal]'}dispatchEvent(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),super.dispatchEvent(t)}}class Nd{constructor(){Object.defineProperty(this,'signal',{value:new Od,writable:!0,configurable:!0})}abort(){let t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event'),t.initEvent('abort',!1,!1)):(t=document.createEventObject(),t.type='abort'):t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}toString(){return'[object AbortController]'}}function Bd(t){return t.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL?(console.log('__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL=true is set, will force install polyfill'),!0):'function'==typeof t.Request&&!t.Request.prototype.hasOwnProperty('signal')||!t.AbortController}'undefined'!=typeof Symbol&&Symbol.toStringTag&&(Nd.prototype[Symbol.toStringTag]='AbortController',Od.prototype[Symbol.toStringTag]='AbortSignal');const Md=Bd({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),Ud=Md?function(t){'function'==typeof t&&(t={fetch:t});const{fetch:e,Request:i=e.Request,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r=!1}=t;if(!Bd({fetch:e,Request:i,AbortController:s,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:r}))return{fetch:e,Request:a};let a=i;(a&&!a.prototype.hasOwnProperty('signal')||r)&&(a=function(t,e){let s;e&&e.signal&&(s=e.signal,delete e.signal);const r=new i(t,e);return s&&Object.defineProperty(r,'signal',{writable:!1,enumerable:!1,configurable:!0,value:s}),r},a.prototype=i.prototype);const n=e;return{fetch:(t,e)=>{const i=a&&a.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){let s;try{s=new DOMException('Aborted','AbortError')}catch(t){s=new Error('Aborted'),s.name='AbortError'}if(i.aborted)return Promise.reject(s);const r=new Promise(((t,e)=>{i.addEventListener('abort',(()=>e(s)),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,n(t,e)])}return n(t,e)},Request:a}}({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}):void 0,Vd=Md?Ud.fetch:window.fetch;Md?Ud.Request:window.Request;const qd=Md?Nd:window.AbortController,Fd=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Hd{constructor(t){this.params=t,this.dashJsRequestQueue=new Map,this.activeRequests=new Map}setMetrics(t){this.dashMetrics=t}queueDashJSRequest(t){var e;const{url:i}=t.request,s=null!==(e=this.dashJsRequestQueue.get(i))&&void 0!==e?e:[];s.push(t),this.dashJsRequestQueue.set(i,s)}executeNextRequests(){return Id(this,void 0,void 0,(function*(){for(const[t,e]of this.dashJsRequestQueue.entries()){const i=this.activeRequests.get(t);if(i){e.length&&this.onBigRequestProgress(i);const s=e[0];if(!s||!s.request.range)continue;const[r,a]=Fd(s.request);if(r>=i.from&&a<=i.to)continue;this.activeRequests.delete(t)}if(e.length){const i=this.sendBigRequest(t,e.map((({request:t})=>t)));this.activeRequests.set(t,i)}}}))}abort(t){var e;if(t){const{request:i}=t,s=(null!==(e=this.dashJsRequestQueue.get(i.url))&&void 0!==e?e:[]).includes(t),r=this.activeRequests.get(i.url);s&&r&&r.abortController.abort()}else for(const{abortController:t}of this.activeRequests.values())t.abort()}destroy(){this.abort(),this.dashMetrics=void 0,this.dashJsRequestQueue.clear(),this.activeRequests.clear()}sendBigRequest(t,e){const i=e.map(Fd),s=i[0][0];let r=i[0][1];for(let t=1;t<i.length&&r<this.params.minDataSize;t++){const e=i[t][1];e-s<=2*this.params.minDataSize&&(r=Math.max(r,e))}r=0===s?Math.max(r,s+this.params.minInitSize):Math.max(r,s+this.params.minDataSize);const a=new URL(t,location.href);a.searchParams.append('bytes',`${s}-${r}`);const n=a.toString(),o=new qd,d=o.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return Vd(n,{signal:d}).then((t=>{var e,i,a;if(u.response=t,!t.ok||!t.body)return void this.onBigRequestError(u);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const d=n.getReader(),c=parseInt(null!==(a=t.headers.get('Content-Length'))&&void 0!==a?a:'',10)||r-s+1;u.data=new ArrayBuffer(c);const l=new Uint8Array(u.data),p=({done:t,value:e})=>Id(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(u):e&&(l.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),yield null==d?void 0:d.read().then(p,Hd.suppressStreamErrors).catch(h))}));null==d||d.read().then(p,Hd.suppressStreamErrors).catch(h)}),Hd.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r,response:a}){var n,o,d,u,h,c,l,p;if(!this.activeRequests.has(t)||!r)return;const f=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const n of f){const{request:f}=n,[m,v]=Fd(f),g=m>=e&&v<=e+s,S=e>=m&&e+s<v,b=r.slice(m-e,Math.min(v-e+1,s));if((g||S)&&(f.requestStartDate=null!==(o=f.requestStartDate)&&void 0!==o?o:new Date,f.firstByteDate=null!==(d=f.firstByteDate)&&void 0!==d?d:new Date,f.bytesLoaded=b.byteLength,f.bytesTotal=i-e),g){f.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==n))),null===(h=n.success)||void 0===h||h.call(n,b,'',t);const e=a?Array.from(a.headers.entries()).map((([t,e])=>`${t}: ${e}`)).join('\r\n'):'';null===(c=this.dashMetrics)||void 0===c||c.addHttpRequest(f,t,null!==(l=null==a?void 0:a.status)&&void 0!==l?l:200,e,[])}else S&&(null===(p=n.progress)||void 0===p||p.call(n,{loaded:s,total:i-e,lengthComputable:!0,stream:!0}))}}onBigRequestError({url:t,from:e,to:i},s){var r,a,n,o;if(null===(a=(r=this.params).onError)||void 0===a||a.call(r,{id:'BigRequest',message:'Download error',thrown:s}),!this.activeRequests.has(t))return;const d=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of d){const[r,a]=Fd(t.request);(r>=e&&r<i||a>e&&a<=i)&&(null===(o=null==t?void 0:t.error)||void 0===o||o.call(t,t.request,String(s)))}if(this.activeRequests.delete(t),s)throw s}onBigRequestAbort({url:t,from:e,to:i}){var s,r;if(!this.activeRequests.has(t))return;const a=null!==(s=this.dashJsRequestQueue.get(t))&&void 0!==s?s:[];for(const t of a){const[s,a]=Fd(t.request);(s>=e&&s<i||a>e&&a<=i)&&(null===(r=null==t?void 0:t.abort)||void 0===r||r.call(t,t.request))}this.activeRequests.delete(t)}static suppressAbort(t){if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t}static suppressStreamErrors(){}}class Gd{constructor(t,e,i){this.baseLoader=t,this.config=i,this.bigRequest=e,e.setMetrics(i.dashMetrics)}static shouldDelegateToBase(t){return'download'!==t.action||'text'===t.mediaType||!t.range||'arraybuffer'!==t.responseType}load(t){const{request:e}=t;if(Gd.shouldDelegateToBase(e))return this.baseLoader.load(t);this.bigRequest.queueDashJSRequest(t),this.bigRequest.executeNextRequests()}abort(t){if(!t)return this.baseLoader.abort(),void this.bigRequest.abort();const{request:e}=t;Gd.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const Yd=(t,e)=>{const i=new Hd(e);return t.extend('SchemeLoaderFactory',(function(){const{parent:t}=this,e=t.getLoader;return{getLoader:t=>((t,e)=>i=>({create:s=>{const r=t(i).create(s);return new Gd(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var jd=t=>{let e,i=!1,s=!1;t.on('playbackTimeUpdated',(({timeToEnd:t})=>{s=t<=3,i&&s&&(null==e||e())})),t.extend('MediaSourceController',(function(){const{parent:t}=this,r=t.signalEndOfStream;return{signalEndOfStream:t=>{i=!0,e=()=>r(t),i&&s&&(null==e||e())}}}),!0)},zd=tt,Qd=ye,Wd=Function.prototype,Jd=zd&&Object.getOwnPropertyDescriptor,Kd=Qd(Wd,'name'),Xd={EXISTS:Kd,PROPER:Kd&&'something'===function(){}.name,CONFIGURABLE:Kd&&(!zd||zd&&Jd(Wd,'name').configurable)},Zd={},tu=Xn,eu=Math.max,iu=Math.min,su=$t,ru=function(t,e){var i=tu(t);return i<0?eu(i+e,0):iu(i,e)},au=io,nu=function(t){return function(e,i,s){var r,a=su(e),n=au(a),o=ru(s,n);if(t&&i!=i){for(;n>o;)if((r=a[o++])!=r)return!0}else for(;n>o;o++)if((t||o in a)&&a[o]===i)return t||o||0;return!t&&-1}},ou={includes:nu(!0),indexOf:nu(!1)},du=ye,uu=$t,hu=ou.indexOf,cu=ma,lu=K([].push),pu=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],fu=function(t,e){var i,s=uu(t),r=0,a=[];for(i in s)!du(cu,i)&&du(s,i)&&lu(a,i);for(;e.length>r;)du(s,i=e[r++])&&(~hu(a,i)||lu(a,i));return a},mu=pu,vu=Object.keys||function(t){return fu(t,mu)},gu=tt,Su=Ei,bu=Ti,yu=Ai,Tu=$t,Eu=vu;Zd.f=gu&&!Su?Object.defineProperties:function(t,e){yu(t);for(var i,s=Tu(e),r=Eu(e),a=r.length,n=0;a>n;)bu.f(t,i=r[n++],s[i]);return t};var wu,$u=Ai,ku=Zd,Au=pu,Pu=ma,Du=Xs,_u=Je,Ru=fa('IE_PROTO'),Iu=function(){},Lu=function(t){return'<script>'+t+'<\/script>'},Cu=function(t){t.write(Lu('')),t.close();var e=t.parentWindow.Object;return t=null,e},xu=function(){try{wu=new ActiveXObject('htmlfile')}catch(t){}var t,e;xu='undefined'!=typeof document?document.domain&&wu?Cu(wu):((e=_u('iframe')).style.display='none',Du.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Lu('document.F=Object')),t.close(),t.F):Cu(wu);for(var i=Au.length;i--;)delete xu.prototype[Au[i]];return xu()};Pu[Ru]=!0;var Ou,Nu,Bu,Mu=Object.create||function(t,e){var i;return null!==t?(Iu.prototype=$u(t),i=new Iu,Iu.prototype=null,i[Ru]=t):i=xu(),void 0===e?i:ku.f(i,e)},Uu=!U((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),Vu=ye,qu=X,Fu=ge,Hu=Uu,Gu=fa('IE_PROTO'),Yu=Object,ju=Yu.prototype,zu=Hu?Yu.getPrototypeOf:function(t){var e=Fu(t);if(Vu(e,Gu))return e[Gu];var i=e.constructor;return qu(i)&&e instanceof i?i.prototype:e instanceof Yu?ju:null},Qu=U,Wu=X,Ju=Mu,Ku=zu,Xu=Xi,Zu=Ne('iterator'),th=!1;[].keys&&('next'in(Bu=[].keys())?(Nu=Ku(Ku(Bu)))!==Object.prototype&&(Ou=Nu):th=!0);var eh=null==Ou||Qu((function(){var t={};return Ou[Zu].call(t)!==t}));Wu((Ou=eh?{}:Ju(Ou))[Zu])||Xu(Ou,Zu,(function(){return this}));var ih={IteratorPrototype:Ou,BUGGY_SAFARI_ITERATORS:th},sh=ih.IteratorPrototype,rh=Mu,ah=ht,nh=gs,oh=Yn,dh=function(){return this},uh=Wi,hh=st,ch=function(t,e,i,s){var r=e+' Iterator';return t.prototype=rh(sh,{next:ah(+!s,i)}),nh(t,r,!1,!0),oh[r]=dh,t},lh=zu,ph=gs,fh=Xi,mh=Yn,vh=Xd.PROPER,gh=ih.BUGGY_SAFARI_ITERATORS,Sh=Ne('iterator'),bh=function(){return this},yh=$t,Th=Yn,Eh=La;Ti.f;var wh=function(t,e,i,s,r,a,n){ch(i,e,s);var o,d,u,h=function(t){if(t===r&&m)return m;if(!gh&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},c=e+' Iterator',l=!1,p=t.prototype,f=p[Sh]||p['@@iterator']||r&&p[r],m=!gh&&f||h(r),v='Array'==e&&p.entries||f;if(v&&(o=lh(v.call(new t)))!==Object.prototype&&o.next&&(ph(o,c,!0,!0),mh[c]=bh),vh&&'values'==r&&f&&'values'!==f.name&&(l=!0,m=function(){return hh(f,this)}),r)if(d={values:h('values'),keys:a?m:h('keys'),entries:h('entries')},n)for(u in d)(gh||l||!(u in p))&&fh(p,u,d[u]);else uh({target:e,proto:!0,forced:gh||l},d);return n&&p[Sh]!==m&&fh(p,Sh,m,{name:r}),mh[e]=m,d},$h=Eh.set,kh=Eh.getterFor('Array Iterator');wh(Array,'Array',(function(t,e){$h(this,{type:'Array Iterator',target:yh(t),index:0,kind:e})}),(function(){var t=kh(this),e=t.target,i=t.kind,s=t.index++;return!e||s>=e.length?(t.target=void 0,{value:void 0,done:!0}):'keys'==i?{value:s,done:!1}:'values'==i?{value:e[s],done:!1}:{value:[s,e[s]],done:!1}}),'values'),Th.Arguments=Th.Array;var Ah=je,Ph=Ti,Dh=ht,_h=Io,Rh=function(t,e,i){var s=Ah(e);s in t?Ph.f(t,s,Dh(0,i)):t[s]=i};Wi({target:'Object',stat:!0},{fromEntries:function(t){var e={};return _h(t,(function(t,i){Rh(e,t,i)}),{AS_ENTRIES:!0}),e}});var Ih=Pt.Object.fromEntries,Lh={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},Ch=M,xh=ds,Oh=Bi,Nh=Yn,Bh=Ne('toStringTag');for(var Mh in Lh){var Uh=Ch[Mh],Vh=Uh&&Uh.prototype;Vh&&xh(Vh)!==Bh&&Oh(Vh,Bh,Mh),Nh[Mh]=Nh.Array}var qh=Ih,Fh=i=>{const r=new t(1/0),a=new e,n=new t(void 0),o=new t(void 0);let d=NaN,u=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{var e,i,a,d,u;const h=qh(t.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in h||'x-playback-duration-millis'in h){const n=parseInt(null!==(e=t.getResponseHeader('X-Playback-Duration'))&&void 0!==e?e:'',10),o=parseInt(null!==(i=t.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==i?i:'',10),d=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;s(d)&&!isNaN(d)&&r.next(d)}const c=null!==(d=h['x-delivery-type'])&&void 0!==d?d:L.HTTP1,l=null!==(u={1:!0,0:!1}[h['x-reused']])&&void 0!==u?u:void 0;n.next(c),o.next(l)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!u&&(u=!0,a.next(Date.now()-d)),i(...t)},d=Date.now(),u=!1}return e(t)}}}),!0),{playbackDuration$:r,ping$:a,connectionReused$:o,connectionType$:n}},Hh=t=>{const e=new URL(t);return e.searchParams.set('quic','1'),e.toString()},Gh=t=>{t.extend('HTTPLoader',(function(){const{parent:t}=this,e=t.load;return{load:t=>{if(t.request&&t.request.range){const[e,i]=t.request.range.split('-').map((t=>parseInt(t,10))),s=new URL(t.request.url,location.href);s.searchParams.append('bytes',`${e}-${i}`),t.request.url=s.toString(),t.request.range=void 0}e(t)}}}),!0)};const Yh=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),u=e(),h=r(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(u,d)||(s(d),h&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),h&&t.setState(e.to)}),o)),c},jh=(t,e,i)=>Yh(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),zh=(t,e,i,r)=>Yh(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:i,onError:r}),Qh=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class Wh{constructor(){this.available$=new e,this.current$=new t(void 0),this.error$=new e,this.subscription=new i,this.externalTracks=new Map}connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};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(Yh(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(u((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(Yh(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:r})),this.subscription.add(Yh(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(a(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(a(t,'addtrack'),a(t,'removetrack'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(o(a(t,'change'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(a(t,'addtrack').subscribe((t=>{var i,s;null===(i=t.track)||void 0===i||i.addEventListener('cuechange',e);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(a(t,'removetrack').subscribe((t=>{var i;null===(i=t.track)||void 0===i||i.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(Wh.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&Qh(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){l(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var Jh=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class Kh{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(){0===this.pauseTimestamp&&(this.pauseTimestamp=Date.now())}resume(){this.pauseTimestamp>0&&(this.pausedTime+=this.getCurrentPausedTime(),this.pauseTimestamp=0)}resetTo(t){this.streamOffset=t,this.pauseTimestamp=0,this.pausedTime=0}}class Xh{constructor(t){this._buffer=[],this._source=t}fill(){this._buffer=[];const t=this._source.currentTime;for(let e=0,i=this._source.buffered.length;e<i;e++){let i=this._source.buffered.start(e);const s=this._source.buffered.end(e);i>t&&i-t<3&&(i=t),this._buffer.push({from:i,to:s,i:e})}return this._buffer.sort((function(t,e){return t.from-e.from})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.from&&t<e.to))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.from-t.to<(e||3))return i}getNext(t){let e=this._buffer.indexOf(t);if(~e&&this._buffer.length-1>e)return this._buffer[++e]}smartRemove(t,e,i){this._buffer.forEach((({from:s,to:r})=>{const a=s>=t&&s<e,n=r>=t&&r<e;a&&n||(a?i(e,r):n?i(s,t):s<t&&r>e?(i(e,r),i(s,t)):i(s,r))}))}destroy(){this._buffer=[]}}var Zh=(t,e,i=3)=>{let s=0,r=0;for(let a=0;a<t.length;a++){const n=t.start(a),o=t.end(a);if(n<=e&&e<=o){if(s=n,r=o,!i)return{from:s,to:r};for(let e=a-1;e>=0;e--)t.end(e)+i>=s&&(s=t.start(e));for(let e=a+1;e<t.length;e++)t.start(e)-i<=r&&(r=t.end(e))}}return{from:s,to:r}};const tc=t=>{const i=e=>a(t,e).pipe(v(void 0)),r=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>a(t,e)))).pipe(u((()=>t.readyState<3)),c()),n=o(a(t,'progress'),a(t,'timeupdate')).pipe(u((()=>Zh(t.buffered,t.currentTime)))),d=a(t,'volumechange').pipe(p(0),u((()=>({muted:t.muted,volume:t.volume})))),h=a(t,'error').pipe(u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),l=a(t,'timeupdate').pipe(u((()=>t.currentTime))),f=new e;let g;return l.subscribe((e=>{t.loop&&s(g)&&s(e)&&g>=t.duration-.3&&e<=.3&&f.next(g),g=e})),{playing$:i('playing'),pause$:i('pause').pipe(m((()=>!t.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:f,error$:h,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadStart$:i('loadstart'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:a(t,'durationchange').pipe(u((()=>t.duration))),isBuffering$:r,currentBuffer$:n,volumeState$:d}},ec=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var ic=ge,sc=io,rc=Xn;Wi({target:'Array',proto:!0},{at:function(t){var e=ic(this),i=sc(e),s=rc(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var ac=gd('Array','at');let nc=!1,oc={};const dc=t=>{t(oc)},uc=(t,e)=>{var i;nc&&(oc.meta=null!==(i=oc.meta)&&void 0!==i?i:{},oc.meta[t]=e)};class hc{constructor(t){this.name=t}next(t){var e,i;if(!nc)return;oc.series=null!==(e=oc.series)&&void 0!==e?e:{};const s=null!==(i=oc.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),oc.series[this.name]=s}}const cc=new hc('best_bitrate');class lc{constructor(){this.history={}}recordSelection(t){this.history[t.id]=g()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const pc=(t,{container:e,throughput:i,tuning:a,limits:n,reserve:o=0,forwardBufferHealth:d,playbackRate:u,current:h,history:c})=>{var l,p,f,m;const v=a.usePixelRatio&&null!==(l=window.devicePixelRatio)&&void 0!==l?l:1,S=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*v*a.containerSizeFactor,height:e.height*v*a.containerSizeFactor},b=S&&Ad(S),y=a.considerPlaybackRate&&s(u)?u:1,T=t.filter((t=>!Pd(t.quality))).sort(((t,e)=>wd(t.quality,e.quality)?-1:1)),E=null===(p=ac(T,-1))||void 0===p?void 0:p.quality,w=null===(f=ac(T,0))||void 0===f?void 0:f.quality,$=r(n)||s(n.min)&&s(n.max)&&$d(n.max,n.min)||s(n.min)&&w&&wd(n.min,w)||s(n.max)&&E&&$d(n.max,E),k=y*(A=null!=d?d:.5,P=a.bitrateFactorAtEmptyBuffer,D=a.bitrateFactorAtFullBuffer,(P-D)*Math.pow(2,-10*A)+D);var A,P,D;const _=T.filter((t=>{const e=!b||$d(t.quality,b),u=!(s(i)&&isFinite(i)&&s(t.bitrate))||i-o>=t.bitrate*k,c=a.lazyQualitySwitch&&s(a.minBufferToSwitchUp)&&h&&!Pd(h.quality)&&(null!=d?d:0)<a.minBufferToSwitchUp&&wd(t.quality,h.quality),l=$||(r(n.max)||(p=t.quality,f=n.max,Ed[p].height<=Ed[f].height))&&(r(n.min)||((t,e)=>Ed[t].height>=Ed[e].height)(t.quality,n.min));var p,f;return e&&u&&!c&&l}))[0];_&&_.bitrate&&cc.next(_.bitrate);const R=null!==(m=null!=_?_:T[Math.ceil((T.length-1)/2)])&&void 0!==m?m:t[0],I=R&&c&&c.history[R.id]&&g()-c.history[R.id]<=a.trackCooldown&&(!c.last||R.id!==c.last.id);if((null==R?void 0:R.id)&&c&&!I&&c.recordSelection(R),I&&(null==c?void 0:c.last)){const t=c.last;return null==c||c.recordSwitch(t),t}return null==c||c.recordSwitch(R),R};var fc=t=>new URL(t).hostname;const mc=(t,e=300)=>new S((i=>{const{width:r,height:a}=t.getBoundingClientRect();if(i.next({width:r,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(A((t=>{const e=t[0];if(!e)return;let r,a;e.contentBoxSize&&e.contentBoxSize[0]?(a=e.contentBoxSize[0].blockSize,r=e.contentBoxSize[0].inlineSize):e.contentRect&&(r=e.contentRect.width,a=e.contentRect.height),s(r)&&s(a)&&i.next({width:r,height:a})}),e));return n.observe(t),()=>n.disconnect()})),vc={};var gc;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(gc||(gc={}));const Sc=(t,e)=>new S((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class bc{constructor(e){this.subscription=new i,this.videoState=new Dd(gc.DOWNLOADING_LIB),this.textTracksManager=new Wh,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t(void 0),this.maxSeekBackTime$=new t(1/0),this.availableFrom$=new t(void 0),this.elementSize$=new t(void 0),this.liveOffset=new Kh,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState(),r=this.isLive$.getValue();if(!this.videoState.getTransition()&&t!==gc.DOWNLOADING_LIB&&t!==gc.STREAM_INITIALIZED)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&t!==gc.STOPPED&&e!==P.STOPPED&&(r?this.seek(s.position-this.liveOffset.getTotalPausedTime()):this.seek(s.position)),e){case P.STOPPED:switch(t){case gc.STOPPED:break;case gc.PLAYING:case gc.PAUSED:case gc.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case gc.PLAYING:break;case gc.PAUSED:r&&(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 gc.READY:this.play();break;case gc.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case gc.PLAYING:this.pause(),this.liveOffset.pause();break;case gc.PAUSED:break;case gc.READY:this.videoState.setState(gc.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED);break;case gc.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}},this.video=Jh(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(fc(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Sd(import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(vc.MediaPlayer=e.MediaPlayer,vc.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(vc.MediaPlayer,'dashjs not loaded'),l(vc.Debug,'dashjs not loaded'),this.player=vc.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?ec(t.frameRate+''):void 0),!0)));(this.params.format===D.DASH_WEBM||this.params.format===D.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Yd(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&&Gh(this.player),jd(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:Hh})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(gc.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(mc(this.video),this.elementSize$),a(Sc(this.player,'error').pipe(u((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),a(Sc(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Sc(this.player,'qualityChangeRendered').pipe(m((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));n.pipe(m(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(m((({to:t})=>t===gc.STREAM_INITIALIZED)),b()).subscribe((()=>{this.subscription.add(Yh(e.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.videoTracks.find((({track:e})=>e.id===t)))||void 0===e?void 0:e.bitrateInfo;i&&this.player.setQualityFor('video',i.qualityIndex)}),{changed$:n.pipe(u((t=>null==t?void 0:t.id))),onError:i}))}),i)),this.subscription.add(Yh(e.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),a(Sc(this.player,'bufferStateChanged').pipe(m((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),a(Sc(this.player,'fragmentLoadingStarted'),(({mediaType:e,request:{url:i}})=>{var s,r;const a=this.player.getDashMetrics(),n=a.getLatestFragmentRequestHeaderValueByID(e,'X-Reused'),o=null!==(s=a.getLatestFragmentRequestHeaderValueByID(e,'X-Delivery-Type'))&&void 0!==s?s:L.HTTP1,d=null!==(r={1:!0,0:!1}[n])&&void 0!==r?r:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(d),t.hostname$.next(fc(i))})),a(Sc(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=Ad(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===r&&(a=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&t.currentVideoTrack$.next(a),this.videoState.setState(gc.STREAM_INITIALIZED),this.videoState.startTransitionTo(gc.READY)})),a(Sc(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),a(o(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=pc(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(y({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(m(s))}).pipe(m((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const d=Sc(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>null!=t?t:0)));a(y({availableFrom:this.availableFrom$.pipe(m(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(d.pipe(m((()=>!1===this.isLive$.getValue()))),t.position$),a(Sc(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(Sc(this.player,'playbackEnded'),t.endedEvent$),a(Sc(this.player,'playbackProgress').pipe(u((()=>Zh(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(Sc(this.player,'playbackPlaying'),(()=>{this.videoState.setState(gc.PLAYING),Td(e.playbackState,P.PLAYING)})),a(Sc(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(gc.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Sc(this.player,'playbackPaused'),(()=>{this.videoState.setState(gc.PAUSED),Td(e.playbackState,P.PAUSED)})),a(Sc(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===gc.READY&&this.videoState.setState(gc.READY)})),a(this.isLive$,t.isLive$),a(mc(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l,connectionType$:f,connectionReused$:g}=Fh(this.player);a(f,this.params.output.httpConnectionType$),a(g,this.params.output.httpConnectionReused$),a(c,this.maxSeekBackTime$),a(l.pipe(b()),t.firstBytesEvent$),a(Sc(this.player,'canPlay'),t.canplay$),this.params.tuning.flushShortLoopedBuffers&&a(y({isLive:this.isLive$,isShort:t.duration$.pipe(u((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(d.pipe(m((t=>t>this.params.tuning.insufficientBufferRuleMargin)),b()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Sc(this.player,'manifestLoaded').pipe(b()).subscribe((()=>{this.subscription.add(Sc(this.player,'playbackPlaying').pipe(b(),v(void 0)).subscribe(t.firstFrameEvent$,i))}),i)),this.subscription.add(jh(this.video,e.isLooped,i));const{volumeState$:S,looped$:T}=tc(this.video);this.subscription.add(zh(this.video,e.volume,S,i)),this.subscription.add(S.subscribe(t.volume$,i)),this.subscription.add(T.subscribe(t.loopedEvent$))}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(gc.STOPPED),Td(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(gc.STREAM_INITIALIZED),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.player.attachView(this.video),this.player.attachSource(this.params.source.url)}seek(t){if(this.params.output.willSeekEvent$.next(),this.isLive$.getValue()){const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3);const s=yd(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,vd.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(gc.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(gc.PAUSED),this.video.pause()}destroy(){var t,e;this.subscription.unsubscribe(),this.textTracksManager.destroy();try{null===(t=this.player)||void 0===t||t.destroy()}catch(t){}this.video.remove(),this.params.output.element$.next(void 0),null===(e=this.destroyBigRequest)||void 0===e||e.call(this)}}var yc=t=>{switch(t){case'mobile':return bd.Q_144P;case'lowest':return bd.Q_240P;case'low':return bd.Q_360P;case'sd':case'medium':return bd.Q_480P;case'hd':case'high':return bd.Q_720P;case'fullhd':case'full':return bd.Q_1080P;case'quadhd':case'quad':return bd.Q_1440P;case'ultrahd':case'ultra':return bd.Q_2160P}},Tc=t=>Id(void 0,void 0,void 0,(function*(){const e=t.muted;try{yield t.play()}catch(i){if(i instanceof DOMException&&(20===i.code||'AbortError'===i.name))return!1;if(e)return console.warn(i),!1;t.muted=!0;try{yield t.play()}catch(e){return t.muted=!1,console.warn(e),!1}}return!0}));function Ec(){return g()}function wc(t){return Ec()-t}function $c(t){const e=t.split('/'),i=e.slice(0,e.length-1).join('/'),s=/^([a-z]+:)?\/\//i;return{resolve:(t,e,r=!1)=>{(t=>s.test(t))(t)||(t.startsWith('/')||(t='/'+t),t=i+t);let a=t.indexOf('?')>-1?'&':'?';return r&&(t+=a+'lowLat=1',a='&'),e&&(t+=a+'_rnd='+Math.floor(999999999*Math.random())),t}}}function kc(t,e,i,r){const a=window.XMLHttpRequest;let n,o,d,u,h,c=!1,p=0,f=!1,m='arraybuffer',v=7e3,g=2e3,S=()=>{if(c)return;l(u);const t=wc(u);let e;if(t<g)return e=g-t,void setTimeout(S,e);g*=2,g>v&&(g=v),o&&o.abort(),o=new a,y()};const b=()=>{if(!c){if(--p>=0)return S(),void(r&&r());c=!0,h&&h(),i&&i()}},y=()=>{u=Ec(),o=new a,o.open('get',t);let i,s=0,r=0;const p=()=>(l(u),Math.max(u,Math.max(i||0,r||0)));if(n&&o.addEventListener('progress',(t=>{const e=Ec();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(c)return;l(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(p(),t)}h&&h(),o&&e(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),f){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(r=Ec(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=m,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(f=t,T),withJSONResponse:()=>(m='json',T),withRetryCount:t=>(p=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(v=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(h=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return T}class Ac{constructor(t){this.intervals=[],this.currentRate=0,this.logger=t}_updateRate(t){let e=.2;this.currentRate&&(t<.1*this.currentRate?e=.8:t<.5*this.currentRate?e=.5:t<.7*this.currentRate&&(e=.3)),t=Math.max(1,Math.min(t,104857600)),this.currentRate=this.currentRate?this.currentRate*(1-e)+t*e:t}_createInterval(t,e,i){return{start:t,end:e,bytes:i}}_doMergeIntervals(t,e){t.start=Math.min(e.start,t.start),t.end=Math.max(e.end,t.end),t.bytes+=e.bytes}_mergeIntervals(t,e){return t.start<=e.end&&e.start<=t.end&&(this._doMergeIntervals(t,e),!0)}_flushIntervals(){if(!this.intervals.length)return!1;const t=this.intervals[0].start,e=this.intervals[this.intervals.length-1].end-500;if(e-t>2e3){let i=0,s=0;for(;this.intervals.length>0;){const t=this.intervals[0];if(t.end<=e)i+=t.end-t.start,s+=t.bytes,this.intervals.splice(0,1);else{if(t.start>=e)break;{const r=e-t.start,a=t.end-t.start;i+=r;const n=t.bytes*r/a;s+=n,t.start=e,t.bytes-=n}}}if(s>0&&i>0){const r=8*s/(i/1e3);return this._updateRate(r),this.logger(`rate updated, new=${Math.round(r/1024)}K; average=${Math.round(this.currentRate/1024)}K bytes/ms=${Math.round(s)}/${Math.round(i)} interval=${Math.round(e-t)}`),!0}}return!1}_joinIntervals(){let t;do{t=!1;for(let e=0;e<this.intervals.length-1;++e)this._mergeIntervals(this.intervals[e],this.intervals[e+1])&&(this.intervals.splice(e+1,1),t=!0)}while(t)}addInterval(t,e,i){return this.intervals.push(this._createInterval(t,e,i)),this._joinIntervals(),this.intervals.length>100&&(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 Pc{constructor(t,e,i,s,r){this.pendingQueue=[],this.activeRequests={},this.completeRequests={},this.averageSegmentDuration=2e3,this.lastPrefetchStart=0,this.throttleTimeout=null,this.RETRY_COUNT=t,this.TIMEOUT=e,this.BITRATE_ESTIMATOR=i,this.MAX_PARALLEL_REQUESTS=s,this.logger=r}limitCompleteCount(){let t;for(;(t=Object.keys(this.completeRequests)).length>this._getParallelRequestCount()+2;){const e=t[Math.floor(Math.random()*t.length)];this.logger(`Dropping completed request for url ${e}`,{type:'warn'}),delete this.completeRequests[e]}}_sendRequest(t,e){const i=Ec(),s=i=>{delete this.activeRequests[e],this.limitCompleteCount(),this.completeRequests[e]=t,this._sendPending(),t._error=1,t._errorMsg=i,t._errorCB?t._errorCB(i):(this.limitCompleteCount(),this.completeRequests[e]=t)};t._request=kc(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Ec()-i,delete this.activeRequests[e],this._sendPending(),t._cb?t._cb(s,t._downloadTime):(this.limitCompleteCount(),this.completeRequests[e]=t)}),(()=>s('error')),(()=>{t._retry=1,t._retryCB&&t._retryCB()})),t._request.withRetryCount(this.RETRY_COUNT).withTimeout(this.TIMEOUT).withBitrateReporting(this.BITRATE_ESTIMATOR).withParallel(this._getParallelRequestCount()>1).withFinally((()=>{t._finallyCB&&t._finallyCB()})),this.activeRequests[e]=t,t._request.send(),this.lastPrefetchStart=Ec()}_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 t=this._getParallelRequestCount(),e=Ec();if(Object.keys(this.activeRequests).length>=t)return!1;const i=this._getPrefetchDelay()-(e-this.lastPrefetchStart);return this.throttleTimeout&&clearTimeout(this.throttleTimeout),!(i>0)||(this.throttleTimeout=window.setTimeout((()=>this._sendPending()),i),!1)}_sendPending(){for(;this._canSendPending();){const t=this.pendingQueue.pop();if(!t)return;this.activeRequests[t]||this.completeRequests[t]||(this.logger(`Submitting pending request url=${t}`),this._sendRequest({},t))}}_removeFromActive(t){delete this.completeRequests[t],delete this.activeRequests[t]}abortAll(){Object.values(this.activeRequests).forEach((t=>{t&&t._request&&t._request.abort()})),this.activeRequests={},this.pendingQueue=[],this.completeRequests={}}requestData(t,e,i,s){const r={};return r.send=()=>{const a=this.activeRequests[t]||this.completeRequests[t];if(a)a._cb=e,a._errorCB=i,a._retryCB=s,a._finallyCB=r._finallyCB,a._error||a._complete?(this._removeFromActive(t),setTimeout((()=>{a._complete?(this.logger(`Requested url already prefetched, url=${t}`),e(a._responseData,a._downloadTime)):(this.logger(`Requested url already prefetched with error, url=${t}`),i(a._errorMsg)),r._finallyCB&&r._finallyCB()}),0)):this.logger(`Attached to active request, url=${t}`);else{const e=this.pendingQueue.indexOf(t);-1!==e&&this.pendingQueue.splice(e,1),this.logger(`Request not prefetched, starting new request, url=${t}${-1===e?'':'; removed pending'}`),this._sendRequest(r,t)}},r._cb=e,r._errorCB=i,r._retryCB=s,r.abort=function(){r.request&&r.request.abort()},r.withFinally=t=>(r._finallyCB=t,r),r}prefetch(t){this.activeRequests[t]||this.completeRequests[t]?this.logger(`Request already active for url=${t}`):(this.logger(`Added to pending queue; url=${t}`),this.pendingQueue.unshift(t),this._sendPending())}optimizeForSegDuration(t){this.averageSegmentDuration=t}}class Dc{constructor(t){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=t,this.chunkRateEstimator=new Ac(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=$c(t),this.bitrateSwitcher=this._initBitrateSwitcher(),this._initManifest()}setAutoQualityEnabled(t){this.autoQuality=t}setMaxAutoQuality(t){this.maxAutoQuality=t}switchByName(t){let e;for(let i=0;i<this.manifest.length;++i)if(e=this.manifest[i],e.name===t)return void this._switchToQuality(e)}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(t){this.paused=!1;const e=this.lowLatency&&this._getBufferSizeSec()>this.sourceJitter+5;this.rep&&!e?(this.bufferStates=[],this.videoPlayStarted=!1,this.shouldPlay()?this._playVideoElement(t):this._notifyBuffering(!0)):this.catchUp()}startPlay(t,e){this.autoQuality=e,this._initPlayerWith(t)}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(t){this.manifestUrl=t,this.urlResolver=$c(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{this.mediaSource&&(this.sourceBuffer=this.mediaSource.addSourceBuffer(t.codecs),this.bufferStates=[],e())})),this.videoPlayStarted=!1,s.addEventListener('canplay',(()=>{this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement())}));const a=()=>{!function(t,e,i){const s=(...r)=>{i.apply(null,r),t.removeEventListener(e,s)};t.addEventListener(e,s)}(s,'progress',(()=>{s.buffered.length?(s.currentTime=s.buffered.start(0),r({name:'playing'})):a()}))};a()}_initPlayerWith(t){this.bitrate=0,this.rep=0,this.sourceBuffer=0,this.bufferStates=[],this.filesFetcher&&this.filesFetcher.abortAll(),this.filesFetcher=new Pc(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,d=null,u=null,h=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},f=(t,e,i)=>{u&&u.abort(),u=kc(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},m=(t,e,i)=>{l(this.filesFetcher),null==d||d.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},v=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void v(1);const i=Ec()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const r=this.bufferStates[e];t=Math.min(t,r.buf),r.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,v(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else v(1)},b=t=>{let i;const r=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,u=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,s=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=i.dur.length-1;for(;a>=0&&(r-=i.dur[a],!(r<=0));--a);t=Math.min(a,i.dur.length-1-s),t=Math.max(t,0)}return u(t,!0)},f=(t,e,i)=>{h&&h.abort(),h=kc(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{h=null})).withJSONResponse().send()};return{seek:(e,o)=>{f(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let h=0;for(let t=0;t<i.dur.length;++t)h+=i.dur[t];h>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(h/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=r();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return u(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=r(),a=t?t.chunkIdx+1:0,n=a-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return u(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),u&&u.abort(),h&&h.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,u,c,v,g,T,E=b(t.jidxUrl),w=0;const $=()=>{v&&(clearTimeout(v),v=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Ec(),s=Math.min(1e4,e-i);w=i;const r=()=>{h||p()&&E.seek((()=>{p()&&(w=Ec(),k(),$())}))};s>0?v=window.setTimeout((()=>{this.paused?$():r()}),s):r()},k=()=>{let e;for(;e=E.nextChunk(c);)c=e,R(e);const i=E.nextChunk(u);if(i){if(u&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));_(i)}else $()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let r,a,n;const o=i=>{window.setTimeout((()=>{p()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Ec(),u=i.currentTime;!this.paused&&i.buffered.length>1&&g===u&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,T=d);const h=this._getBufferSizeSec();if(h>30)s(`Buffered ${h} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(r=this.sourceBuffer.buffered.start(0),a=u,a-r>4&&this.sourceBuffer.remove(r,a-3)),o(1e3)}}},P=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(u)]),A(d,(function(){d=null,k()})))},D=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),_=t=>{p()&&m(D(t),((e,i)=>{if(p()){if(i/=1e3,d=e,u=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}P()}}),(()=>this._handleNetworkError()))},R=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(D(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{a=!0,P()})))};n=!0,E.seek((t=>{p()&&(w=Ec(),t?(c=t,!r(e)||t.startTS>e?_(t):(u=t,k())):$())}),e),t.cachedHeader?I(t.cachedHeader):f(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let r;t.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Ec();if(this.chunkRateEstimator.addInterval(t,s,i)){const r=this.chunkRateEstimator.getBitRate();return e({name:'bandwidth',size:i,duration:s-t,speed:r}),!0}},get:()=>{const t=this.chunkRateEstimator.getBitRate();return t?.85*t:0}}))();let r,a=-1/0,n=!0;const o=()=>{let t=s.get();if(t&&r&&this.autoQuality){if(n&&t>r&&wc(a)<3e4)return;i(t)}n=this.autoQuality};return{updateChunk:(t,e)=>{const i=s.updateChunk(t,e);return i&&o(),i},notifySwitch:t=>{const e=Ec();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=kc(this.urlResolver.resolve(t,!0),e,i,(()=>this._retryCallback())).withJSONResponse().withTimeout(1e4).withRetryCount(3).withRetryInterval(300,2e3).send().withFinally((()=>{this.manifestRequest=void 0}))}_playVideoElement(t){const{videoElement:e}=this.params;Tc(e).then((e=>{e||null==t||t()}))}_handleManifestUpdate(t){const{logger:e,playerCallback:i,videoElement:s}=this.params;this.manifest=(t=>{const e=[];return(null==t?void 0:t.length)?(t.forEach(((t,i)=>{t.video&&s.canPlayType(t.codecs).replace(/no/,'')&&window.MediaSource.isTypeSupported(t.codecs)&&(t.index=i,e.push(t))})),e.sort((function(t,e){return t.video&&e.video?e.video.height-t.video.height:e.bitrate-t.bitrate})),e):(this.params.playerCallback({name:'error',type:'partial_metadata'}),[])})(t),e(`Valid manifest entries: ${this.manifest.length}/${t.length}`),i({name:'manifest',manifest:this.manifest})}_refetchManifest(t){this.destroyed||(this.manifestRefetchTimer&&clearTimeout(this.manifestRefetchTimer),this.manifestRefetchTimer=window.setTimeout((()=>{this._fetchManifest(t,(e=>{this.destroyed||(this._handleManifestUpdate(e),this._refetchManifest(t))}),(()=>this._refetchManifest(t)))}),6e4))}_initManifest(){this._fetchManifest(this.manifestUrl,(t=>{this.destroyed||(this._handleManifestUpdate(t),this._refetchManifest(this.manifestUrl))}),(()=>this._handleNetworkError()))}}var _c;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(_c||(_c={}));const Rc=[_c.PAUSED,_c.PLAYING,_c.READY],Ic=[_c.PAUSED,_c.PLAYING,_c.READY];class Lc{constructor(e){this.subscription=new i,this.videoState=new Dd(_c.STOPPED),this.representations$=new t([]),this.textTracksManager=new Wh,this.maxSeekBackTime$=new t(1/0),this.zeroTime$=new t(void 0),this.liveOffset=new Kh,this._dashCb=t=>{var e,i,r,a;switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const s=t.manifest,a=[];for(const t of s){const s=null!==(e=t.name)&&void 0!==e?e:t.index.toString(10),r=null!==(i=yc(t.name))&&void 0!==i?i:Ad(t.video),n=t.bitrate/1e3,o=Object.assign({},t.video);if(!r)continue;const d={id:s,quality:r,bitrate:n,size:o};a.push({track:d,representation:t})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===_c.MANIFEST_READY&&this.videoState.setState(_c.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=null===(a=this.representations$.getValue().find((({representation:t})=>t===e)))||void 0===a?void 0:a.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}},this.syncPlayback=()=>{var t;const e=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(o)};`}),r!==P.STOPPED){if(!i){if(Ic.includes(e)){const e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to;s(e)&&this.setVideoTrack(e);const i=this.params.desiredState.autoVideoTrackSwitching.getTransition();i&&this.setAutoQuality(i.to)}if((null==a?void 0:a.to)!==P.PAUSED&&o.state===C.Requested&&Rc.includes(e))this.seek(o.position-this.liveOffset.getTotalPausedTime());else switch(e){case _c.STOPPED:return this.videoState.startTransitionTo(_c.MANIFEST_READY),void this.dash.attachSource(yd(this.params.source.url));case _c.MANIFEST_READY:this.videoState.startTransitionTo(_c.READY),this.prepare();break;case _c.READY:return void(r===P.PAUSED?this.videoState.setState(_c.PAUSED):r===P.PLAYING&&(this.videoState.startTransitionTo(_c.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(_c.PAUSED)}))));case _c.PLAYING:return void(r===P.PAUSED&&(this.videoState.startTransitionTo(_c.PAUSED),this.liveOffset.pause(),this.dash.pause()));case _c.PAUSED:return void(r===P.PLAYING&&(this.videoState.startTransitionTo(_c.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(_c.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return n(e)}}}else e!==_c.STOPPED&&(this.videoState.startTransitionTo(_c.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(_c.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const r=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Jh(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(fc(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const a=tc(this.video);this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===_c.READY&&this.videoState.setState(_c.READY)}),r)).add(a.pause$.subscribe((()=>{this.videoState.setState(_c.PAUSED)}),r)).add(a.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===C.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(_c.PLAYING)}),r)).add(a.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),u((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(y({zeroTime:this.zeroTime$.pipe(m(s)),position:a.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),r)).add(jh(this.video,this.params.desiredState.isLooped,r)).add(zh(this.video,this.params.desiredState.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(this.params.output.volume$,r)).add(a.loadStart$.subscribe(this.params.output.firstBytesEvent$)).add(a.playing$.subscribe(this.params.output.firstFrameEvent$)).add(a.canplay$.subscribe(this.params.output.canplay$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&Ed[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case _c.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case _c.MANIFEST_READY:case _c.READY:break;case _c.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case _c.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return n(t.to)}}),r)).add(o(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Dc({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},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var t,e,i,r,a,n;const o=this.representations$.getValue(),d=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState(),u=null!==(r=null===(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===i?void 0:i.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&s(d)?d:null===(a=pc(o.map((({track:t})=>t)),{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()}))||void 0===a?void 0:a.id,c=null===(n=o.find((({track:t})=>t.id===h)))||void 0===n?void 0:n.representation;l(c,'Representations missing'),this.dash.startPlay(c,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(h),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(t){var e;const i=null===(e=this.representations$.getValue().find((({track:e})=>e.id===t)))||void 0===e?void 0:e.representation;l(i,`No such representation ${t}`),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.dash.reinit(yd(this.params.source.url,i))}}var Cc=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?L.HTTP1:null!==(e=s)&&void 0!==e?e:void 0,reused:null===r?void 0:null!==(i={1:!0,0:!1}[r])&&void 0!==i?i:void 0}},xc=(t,e)=>{let i=0;for(let s=0;s<t.length;s++){const r=1e3*t.start(s),a=1e3*t.end(s);r<=e&&e<=a&&(i=a)}return Math.max(i-e,0)};class Oc{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{var e,i,s,r,a,n,o,d;if(l(this._xhr),(null===(e=this._xhr)||void 0===e?void 0:e.status)>=400)return null===(i=this._errorCb)||void 0===i||i.call(this,`Http${null===(s=this._xhr)||void 0===s?void 0:s.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=qh(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(a=this._headersCb)||void 0===a||a.call(this,new Headers(e))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(o=this._progressCb)||void 0===o||o.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!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 Nc{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,r,a,n){this.abort((()=>{let o=0;const d=Date.now();let u=0,h=0,c=0;const l=t=>{s(Nc._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=Hh(p)),this._lastXhr=new Oc(p,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-o>n&&l(t),0===h)return void(h=Date.now());c=t.length-u;const e=Date.now()-h;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,u=t.length,h=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.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((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Nc._concatUint8(this._appendPromiseUint8Array,t):(this._appendPromiseUint8Array=t,this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&this._appendBuffer(this._appendPromiseUint8Array,(()=>{this._appendPromiseUint8Array=void 0,e&&this._sbUpdatingWatch(e)}))})))}endOfStream(){'open'===this._mediaSource.readyState&&this._sbUpdatingWatch((()=>this._mediaSource.endOfStream()))}static _concatUint8(t,e){const i=new Uint8Array(t.byteLength+e.byteLength);return i.set(t,0),i.set(e,t.byteLength),i}static _str2ua(t){const e=new Uint8Array(t.length);for(let i=0;i<t.length;i++)e[i]=t.charCodeAt(i);return e}remove(t,e){this._sbUpdatingWatch((()=>{!this._sourceBuffer.updating&&this._sourceBuffer.remove&&this._sourceBuffer.remove(t,e),this._maxBufferDuration=Number.POSITIVE_INFINITY}))}destroy(){var t;null===(t=this._lastXhr)||void 0===t||t.abort(),this._sbUpdatingStop(this._lastStreamUpdatingCallback),'open'===this._mediaSource.readyState&&this._sourceBuffer.abort()}}class Bc{constructor(t){var e;this._representations=[],this._appendVector={},this._cachingPaused=!1,this._duration=0,this.STREAM_END_THRESHOLD=1,this._params=t,this._video=t.video,this._buffer=t.buffer,this._onDashCallback=null!==(e=t.onDashCallback)&&void 0!==e?e:()=>{},this._config=t.config}_parseDurationFromISO8601(t){const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},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(t),s='-'===(null==i?void 0:i[1])?-1:1;e(null==i?void 0:i[2],s),e(null==i?void 0:i[3],s),e(null==i?void 0:i[4],s),e(null==i?void 0:i[5],s);return 3600*e(null==i?void 0:i[6],s)+60*e(null==i?void 0:i[7],s)+e(null==i?void 0:i[8],s)}getRepresentations(){return this._representations}attachSource(t,e){let i=t;this._config.REQUEST_QUIC&&(i=Hh(i)),new Oc(i,e,(t=>{this.attachManifest(t,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(i))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$;const k=t.getElementsByTagName('SegmentBase')[0],A=k&&r(k,'indexRange').split('-'),P=k&&k.getElementsByTagName('Initialization')[0],D=P&&r(P,'range').split('-');if(!D||!A){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(h=null===(u=null===(d=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===d?void 0:d.childNodes)||void 0===u?void 0:u[0])||void 0===h?void 0:h.data),l=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:l})}return}const _=Number(null===(l=t.attributes.getNamedItem('bandwidth'))||void 0===l?void 0:l.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let I;const L=null!==(f=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==f?f:void 0;I=L?ec(L):void 0,a.push({width:Number(null===(m=t.attributes.getNamedItem('width'))||void 0===m?void 0:m.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:_,baseURL:R,failoverHosts:e,indexFrom:Number(A[0]),indexTo:Number(A[1]),initFrom:Number(D[0]),initTo:Number(D[1]),codecs:null!==(S=null===(g=t.attributes.getNamedItem('codecs'))||void 0===g?void 0:g.value)&&void 0!==S?S:void 0,mimeType:null!==(y=null===(b=t.attributes.getNamedItem('mimeType'))||void 0===b?void 0:b.value)&&void 0!==y?y:void 0,fps:I,bufferSize:.1*_/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==($=null===(w=t.attributes.getNamedItem('id'))||void 0===w?void 0:w.value)&&void 0!==$?$:void 0})})),a.length?(this._representations=a,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const u=t.refs[t.refs.length-1];u.toTime-u.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,r;const a=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let a;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');a=e.to-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.to&&(r=e.to,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.from)}catch(t){throw this._params.onError('GapSyncError',`Seek Error ${String(t)}`,t),t}}),1e3*a)))}},n=()=>{this._loopTimeout=window.setTimeout((()=>{try{a()}catch(t){throw this._params.onError('LoopError',`Dash Loop exception ${String(t)}`,t),t}n()}),250)},o=()=>{if(!this._stream)try{const e=i.addSourceBuffer(`${t.mimeType}; codecs="${t.codecs}"`);this._stream=new Nc({mediaSource:i,sourceBuffer:e,requestQuic:this._params.config.REQUEST_QUIC,onBandwidthChange:this._params.onBandwidthChange,onError:this._params.onError,onDashCallback:this._onDashCallback})}catch(t){throw this._params.onError('DashSourceOpen',`Source open exception ${String(t)}`,t),t}this._loadInitAndSidx(t),i.duration||(i.duration=this._duration),this._loopTimeout||n(),i.removeEventListener('sourceopen',o),i.removeEventListener('webkitsourceopen',o)};i.addEventListener('sourceopen',o,!1),i.addEventListener('webkitsourceopen',o,!1),this._video&&(this._video.src=window.URL.createObjectURL(i),this._video.addEventListener('waiting',(()=>{const t=this._video&&this._video.played.length;t&&!this._video.currentTime&&this._video.loop?this._video.duration-this._video.played.end(t-1)<this.STREAM_END_THRESHOLD&&this.seek(0):this._video.duration-this._video.currentTime<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()})))}_loadRef(t,e,i=!1,s=!1){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const r=this._findRef(e);if(r){if(i){this._isLastRef(r)&&e>=r.toTime&&(e=r.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),a=s||this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||r===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=a?e:r.fromTime}this._appendVector[String(r.fromTime)]=t,this._stream.load(t,r.fromOffset,r.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=r.toTime,this._video.duration-this._lastLoadOffset<this.STREAM_END_THRESHOLD&&this._stream.endOfStream()}),(t=>this._params.onResponseHeaders(t)),t.bufferSize)}}))}setQualityByRepresentation(t,e=!1){const i=this._buffer.getByTime(this._video.currentTime),s=this._findRef(this._video.currentTime);if(!i||!s)return void(this._video.currentTime&&e&&this._loadRef(t,this._video.currentTime));const r=.1;if(s.toTime<i.to+r){const e=this._findRef(s.toTime);e&&e.toTime<i.to+r?(this._buffer.smartRemove(s.fromTime-r,e.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,e.toTime)):(this._buffer.smartRemove(s.fromTime-r,s.toTime+r,((t,e)=>this._stream.remove(t,e))),this._loadRef(t,s.toTime))}}setQuality(t){return this.setQualityByRepresentation(this._representations[t])}pauseCaching(){this._cachingPaused=!0}resumeCaching(){this._cachingPaused=!1}seek(t,e){this._stream&&this._buffer.getByTime(t)?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0,e)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!r(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var Mc;!function(t){t.STOPPED='stopped',t.MANIFEST_LOADED='manifest-loaded',t.INITIAL_REPRESENTATION_SELECTED='initial-representation-selected',t.METADATA_LOADED='metadata-loaded',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Mc||(Mc={}));const Uc=[Mc.PAUSED,Mc.PLAYING];class Vc{constructor(s){this.videoState=new Dd(Mc.STOPPED),this.subscription=new i,this.representations$=new t([]),this.currentRepresentation$=new t(void 0),this.textTracksManager=new Wh,this.elementSize$=new t(void 0),this.dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&yc(a.name))&&void 0!==s?s:Ad(a),o=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!n)continue;const h={id:t,quality:n,bitrate:o,size:d,fps:u};r.push({track:h,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(Mc.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t},this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekState: ${JSON.stringify(r)};`}),i!==P.STOPPED){if(!e)switch((null==s?void 0:s.to)!==P.PAUSED&&r.state===C.Requested&&Uc.includes(t)&&this.seek(r.position,r.forcePrecise),t){case Mc.STOPPED:return this.videoState.startTransitionTo(Mc.MANIFEST_LOADED),void this.prepare();case Mc.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Mc.INITIAL_REPRESENTATION_SELECTED);case Mc.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Mc.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Mc.METADATA_LOADED:return this.videoState.startTransitionTo(Mc.READY),void this.dash.updateRefsForCurrentTime();case Mc.READY:return void(i===P.PAUSED?(this.videoState.setState(Mc.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo(Mc.PLAYING),this.playIfAllowed()));case Mc.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo(Mc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===P.PLAYING&&Td(this.params.desiredState.playbackState,P.PLAYING));case Mc.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo(Mc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===P.PAUSED&&Td(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==Mc.STOPPED&&(this.videoState.startTransitionTo(Mc.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(Mc.STOPPED),Td(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=s,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Jh(s.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(fc(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Xh(this.video),this.dash=new Bc({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,e,i)=>{this.log({message:`[DashLite error], ${t}`}),this.dashLiteEvents.error$.next({id:t,message:e,thrown:i})},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:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=tc(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,i));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.looped$,t.loopedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.playing$,t.firstFrameEvent$),l(d.canplay$,t.canplay$),this.subscription.add(d.seeking$.subscribe((()=>{r(this.params.desiredState.seekState.getState().state!==C.Applying)&&(this.videoState.getState()===Mc.PLAYING||this.videoState.getState()===Mc.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(jh(this.video,e.isLooped,i)),this.subscription.add(zh(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(mc(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Mc.READY&&this.videoState.setState(Mc.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(Mc.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(Mc.PLAYING),Td(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(Mc.METADATA_LOADED)}),i)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(u((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(o(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$,a(this.video,'progress')).pipe(u((()=>{var t,e,i;const r=this.currentRepresentation$.getValue(),a=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),d=this.params.desiredState.videoTrack.getState(),u=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),h=this.elementSize$.getValue(),c=n();let l;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!c&&s(d))l=d;else{const i=xc(this.video.buffered,1e3*this.video.currentTime),s=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,n=Math.min(i/s,1);l=null===(e=pc(a.map((({track:t})=>t)),{container:h,throughput:u,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:n,playbackRate:this.video.playbackRate,current:null===(t=a.find((({representation:t})=>t===r)))||void 0===t?void 0:t.track}))||void 0===e?void 0:e.id}return s(l)?null===(i=a.find((({track:t})=>t.id===l)))||void 0===i?void 0:i.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(y({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(m((t=>t.to===Mc.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(m(s))}).pipe(b()).subscribe((()=>this.videoState.setState(Mc.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(m(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=xc(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(fc(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Cc(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(b(),v(void 0)).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(m(s)).subscribe(this.handleRepresentationPlay,i)).add(o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(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 t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return n(t)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Tc(this.video).then((t=>{t||(this.videoState.setState(Mc.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var qc,Fc,Hc,Gc,Yc;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(qc||(qc={})),function(t){t.WEBM_AS_IN_SPEC='urn:mpeg:dash:profile:webm-on-demand:2012',t.WEBM_AS_IN_FFMPEG='urn:webm:dash:profile:webm-on-demand:2012'}(Fc||(Fc={})),function(t){t.BYTE_RANGE='byteRange',t.TEMPLATE='template'}(Hc||(Hc={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(Gc||(Gc={})),function(t){t.MP4='mp4',t.WEBM='webm'}(Yc||(Yc={}));var jc=(t,e)=>{for(let i=0;i<t.length;i++){if(1e3*t.start(i)<=e&&1e3*t.end(i)>e)return!0}return!1};const zc='function'!=typeof window.requestIdleCallback||'function'!=typeof window.cancelIdleCallback?(t,e={})=>{const i=e.timeout||1,s=performance.now();return window.setTimeout((()=>{t({get didTimeout(){return!e.timeout&&performance.now()-s-1>i},timeRemaining:()=>Math.max(0,performance.now()-s+1)})}),1)}:window.requestIdleCallback;var Qc,Wc,Jc=()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)};let Kc=!1;try{Kc=Jc()&&parseInt(null!==(Wc=null===(Qc=navigator.userAgent.match(/Version\/(\d+)/))||void 0===Qc?void 0:Qc[1])&&void 0!==Wc?Wc:'',10)<16}catch(t){console.error(t)}class Xc{constructor(t){this.bufferFull$=new e,this.error$=new e,this.queue=[],this.currentTask=null,this.destroyed=!1,this.completeTask=()=>{var t;try{if(this.currentTask){const e=null===(t=this.currentTask.signal)||void 0===t?void 0:t.aborted;this.currentTask.callback(!e),this.currentTask=null}this.queue.length&&this.pull()}catch(t){this.error$.next({id:'BufferTaskQueueUnknown',message:'Buffer appending or removal failed',thrown:t})}},this.buffer=t,this.buffer.addEventListener('updateend',this.completeTask)}append(t,e){return Id(this,void 0,void 0,(function*(){return(!e||!e.aborted)&&new Promise((i=>{const s={operation:'append',data:t,signal:e,callback:i};this.queue.push(s),this.pull()}))}))}remove(t,e,i){return Id(this,void 0,void 0,(function*(){return(!i||!i.aborted)&&new Promise((s=>{const r={operation:'remove',from:t,to:e,signal:i,callback:s};this.queue.unshift(r),this.pull()}))}))}abort(t){return Id(this,void 0,void 0,(function*(){return new Promise((e=>{let i;i=Kc&&t?{operation:'safariAbort',init:t,callback:e}:{operation:'abort',callback:e};for(const{callback:t}of this.queue)t(!1);i&&(this.queue=[i]),this.pull()}))}))}destroy(){this.destroyed=!0,this.buffer.removeEventListener('updateend',this.completeTask)}pull(){var t;if(this.buffer.updating||this.currentTask||this.destroyed)return;const e=this.queue.shift();if(!e)return;if(null===(t=e.signal)||void 0===t?void 0:t.aborted)return e.callback(!1),void this.pull();this.currentTask=e;const{operation:i}=this.currentTask;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===i&&this.bufferFull$.next(this.currentTask.data.byteLength),t instanceof DOMException&&'InvalidStateError'===t.name&&'remove'===i||this.error$.next({id:`BufferTaskQueue:${i}`,message:'Buffer operation failed',thrown:t}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(t){const{operation:e}=t;switch(e){case'append':this.buffer.appendBuffer(t.data);break;case'remove':this.buffer.remove(t.from/1e3,t.to/1e3);break;case'abort':this.buffer.abort();break;case'safariAbort':this.buffer.abort(),this.buffer.appendBuffer(t.init);break;default:n(e)}}}var Zc;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(Zc||(Zc={}));class tl{constructor({throughputEstimator:e,requestQuic:s}){this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.abortAllController=new qd,this.subscription=new i,this.fetchManifest=T(this.abortAllController.signal,function(t){return Cd(this,arguments,(function*(){let e=t;this.requestQuic&&(e=Hh(e));const i=yield yield Ld(Vd(e,{signal:this.abortAllController.signal}).catch(el));return i?(this.onHeadersReceived(i.headers),yield Ld(i.text())):yield Ld(null)}))}.bind(this)),this.fetch=T(this.abortAllController.signal,function(t,{rangeMethod:e=Zc.HEADER,range:i,onProgress:s,priority:r='auto',signal:d,measureThroughput:u=!0}={}){var h,c,l,p;return Cd(this,arguments,(function*(){let f=t;const m=new Headers;if(i)switch(e){case Zc.HEADER:m.append('Range',`${i.from}-${i.to}`);break;case Zc.PARAM:{const t=new URL(f,location.href);t.searchParams.append('bytes',`${i.from}-${i.to}`),f=t.toString();break}default:n(e)}this.requestQuic&&(f=Hh(f));let v=this.abortAllController.signal;if(d){const t=new qd;if(this.subscription.add(o(a(this.abortAllController.signal,'abort'),a(d,'abort')).subscribe((()=>{try{t.abort()}catch(t){el(t)}}))),this.abortAllController.signal.aborted||d.aborted)try{t.abort()}catch(t){el(t)}v=t.signal}const S=g(),b=yield yield Ld(Vd(f,{priority:r,headers:m,signal:v}).catch(el)),y=g();if(null===(h=this.throughputEstimator)||void 0===h||h.addRawRtt(y-S),!b)return yield Ld(null);if(!b.ok||!b.body)return yield Ld(Promise.reject(new Error(`Fetch error ${b.status}: ${b.statusText}`)));this.onHeadersReceived(b.headers);const E=parseInt(null!==(c=b.headers.get('Content-Length'))&&void 0!==c?c:'',10)||i&&i.to-i.from+1||NaN;if(!E){const t=yield yield Ld(b.arrayBuffer());return null===(l=this.throughputEstimator)||void 0===l||l.addRawSpeed(t.byteLength,g()-y),null==s||s(new DataView(t),t.byteLength),yield Ld(t)}if(!s&&!u)return yield Ld(b.arrayBuffer());const[w,$]=b.body.tee(),k=w.getReader();u&&(null===(p=this.throughputEstimator)||void 0===p||p.trackStream($));let A=0;const P=new ArrayBuffer(E),D=new Uint8Array(P),_=new DataView(P);let R=!1;const I=t=>{R=!0,el(t)},L=T(v,function({done:t,value:e}){return Cd(this,arguments,(function*(){if(0===A&&this.lastRequestFirstBytes$.next(g()-S),v.aborted)return yield Ld(void 0);t?null==s||s(_,A):e&&(D.set(e,A),A+=e.byteLength,null==s||s(_,A),yield yield Ld(null==k?void 0:k.read().then(L,I)))}))}.bind(this));return yield yield Ld(null==k?void 0:k.read().then(L,I)),yield Ld(R?null:P)}))}.bind(this)),this.fetchByteRangeRepresentation=T(this.abortAllController.signal,function(t,e,i){return Cd(this,arguments,(function*(){if(t.type!==Hc.BYTE_RANGE)return yield Ld(null);const{from:s,to:r}=t.initRange;let a,n,o=s,d=r,u=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,u=r+1===a,u&&(o=Math.min(a,s),d=Math.max(n,r))),o=Math.min(o,0);const h=yield yield Ld(this.fetch(t.url,{rangeMethod:Zc.PARAM,range:{from:o,to:d},priority:i,measureThroughput:!1}));if(!h)return yield Ld(null);const c=new DataView(h,s-o,r-o+1);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(u&&void 0!==a&&void 0!==n)p=new DataView(h,a-o,n-a+1);else{const s=e.getIndexRange(l);if(s){const e=yield yield Ld(this.fetch(t.url,{rangeMethod:Zc.PARAM,range:s,priority:i,measureThroughput:!1}));if(!e)return yield Ld(null);p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const f=e.parseSegments(p,l);return yield Ld({dataView:new DataView(h),segments:f})}))}.bind(this)),this.fetchTemplateRepresentation=T(this.abortAllController.signal,function(t,e){return Cd(this,arguments,(function*(){if(t.type!==Hc.TEMPLATE)return yield Ld(null);const i=new URL(t.initUrl,t.baseUrl).toString(),s=yield yield Ld(this.fetch(i,{priority:e,measureThroughput:!1}));if(!s)return yield Ld(null);const r=t.segments.map((t=>Object.assign(Object.assign({},t),{status:Gc.NONE,size:void 0})));return yield Ld({segments:r,dataView:new DataView(s)})}))}.bind(this)),this.throughputEstimator=e,this.requestQuic=s}onHeadersReceived(t){const{type:e,reused:i}=Cc(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchRepresentation(t,e,i='auto'){var s,r;return Id(this,void 0,void 0,(function*(){const{type:a}=t;switch(a){case Hc.BYTE_RANGE:return null!==(s=yield this.fetchByteRangeRepresentation(t,e,i))&&void 0!==s?s:null;case Hc.TEMPLATE:return null!==(r=yield this.fetchTemplateRepresentation(t,i))&&void 0!==r?r:null;default:n(a)}}))}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const el=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},il=new TextDecoder('ascii'),sl=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=il.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}},rl={validateData:t=>'ftyp'===il.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=sl(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),d=4294967295&r();let u=n/a*1e3,h=t.byteOffset+t.byteLength+o;for(let t=0;t<d;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:Gc.NONE,time:{from:u,to:u+o},byte:{from:h,to:h+s-1}}),u+=o,h+=s}return i},parseFeedableSegmentChunk:t=>{let e=0,i=!1,s=!1;for(;e<=t.byteLength&&!i;){const r=new DataView(t.buffer,t.byteOffset+e);try{const i=sl(r);if(s||(s='mdat'===i.id),!(e+i.size<=t.byteLength))break;e+=i.size}catch(t){i=!0}}return e>0&&e<=t.byteLength&&s?new DataView(t.buffer,t.byteOffset,e):null}};var al,nl;!function(t){t[t.EBML=440786851]='EBML',t[t.EBMLVersion=17030]='EBMLVersion',t[t.EBMLReadVersion=17143]='EBMLReadVersion',t[t.EBMLMaxIDLength=17138]='EBMLMaxIDLength',t[t.EBMLMaxSizeLength=17139]='EBMLMaxSizeLength',t[t.DocType=17026]='DocType',t[t.DocTypeVersion=17031]='DocTypeVersion',t[t.DocTypeReadVersion=17029]='DocTypeReadVersion',t[t.Void=236]='Void',t[t.Segment=408125543]='Segment',t[t.SeekHead=290298740]='SeekHead',t[t.Seek=19899]='Seek',t[t.SeekID=21419]='SeekID',t[t.SeekPosition=21420]='SeekPosition',t[t.Info=357149030]='Info',t[t.TimestampScale=2807729]='TimestampScale',t[t.Duration=17545]='Duration',t[t.Tracks=374648427]='Tracks',t[t.Chapters=272869232]='Chapters',t[t.Cluster=524531317]='Cluster',t[t.Timestamp=231]='Timestamp',t[t.SilentTracks=22612]='SilentTracks',t[t.SilentTrackNumber=22743]='SilentTrackNumber',t[t.Position=167]='Position',t[t.PrevSize=171]='PrevSize',t[t.SimpleBlock=163]='SimpleBlock',t[t.BlockGroup=160]='BlockGroup',t[t.EncryptedBlock=175]='EncryptedBlock',t[t.Attachments=423732329]='Attachments',t[t.Tags=307544935]='Tags',t[t.Cues=475249515]='Cues',t[t.CuePoint=187]='CuePoint',t[t.CueTime=179]='CueTime',t[t.CueTrackPositions=183]='CueTrackPositions',t[t.CueTrack=247]='CueTrack',t[t.CueClusterPosition=241]='CueClusterPosition',t[t.CueRelativePosition=240]='CueRelativePosition',t[t.CueDuration=178]='CueDuration',t[t.CueBlockNumber=21368]='CueBlockNumber',t[t.CueCodecState=234]='CueCodecState',t[t.CueReference=219]='CueReference',t[t.CueRefTime=150]='CueRefTime'}(al||(al={})),function(t){t.SignedInteger='int',t.UnsignedInteger='uint',t.Float='float',t.String='string',t.UTF8='utf8',t.Date='date',t.Master='master',t.Binary='binary'}(nl||(nl={}));const ol={[al.EBML]:{type:nl.Master},[al.EBMLVersion]:{type:nl.UnsignedInteger},[al.EBMLReadVersion]:{type:nl.UnsignedInteger},[al.EBMLMaxIDLength]:{type:nl.UnsignedInteger},[al.EBMLMaxSizeLength]:{type:nl.UnsignedInteger},[al.DocType]:{type:nl.String},[al.DocTypeVersion]:{type:nl.UnsignedInteger},[al.DocTypeReadVersion]:{type:nl.UnsignedInteger},[al.Void]:{type:nl.Binary},[al.Segment]:{type:nl.Master},[al.SeekHead]:{type:nl.Master},[al.Seek]:{type:nl.Master},[al.SeekID]:{type:nl.Binary},[al.SeekPosition]:{type:nl.UnsignedInteger},[al.Info]:{type:nl.Master},[al.TimestampScale]:{type:nl.UnsignedInteger},[al.Duration]:{type:nl.Float},[al.Tracks]:{type:nl.Master},[al.Chapters]:{type:nl.Master},[al.Cluster]:{type:nl.Master},[al.Timestamp]:{type:nl.UnsignedInteger},[al.SilentTracks]:{type:nl.Master},[al.SilentTrackNumber]:{type:nl.UnsignedInteger},[al.Position]:{type:nl.UnsignedInteger},[al.PrevSize]:{type:nl.UnsignedInteger},[al.SimpleBlock]:{type:nl.Binary},[al.BlockGroup]:{type:nl.Master},[al.EncryptedBlock]:{type:nl.Binary},[al.Attachments]:{type:nl.Master},[al.Tags]:{type:nl.Master},[al.Cues]:{type:nl.Master},[al.CuePoint]:{type:nl.Master},[al.CueTime]:{type:nl.UnsignedInteger},[al.CueTrackPositions]:{type:nl.Master},[al.CueTrack]:{type:nl.UnsignedInteger},[al.CueClusterPosition]:{type:nl.UnsignedInteger},[al.CueRelativePosition]:{type:nl.UnsignedInteger},[al.CueDuration]:{type:nl.UnsignedInteger},[al.CueBlockNumber]:{type:nl.UnsignedInteger},[al.CueCodecState]:{type:nl.UnsignedInteger},[al.CueReference]:{type:nl.Master},[al.CueRefTime]:{type:nl.UnsignedInteger}},dl=t=>{const e=t.getUint8(0);let i=0;128&e?i=1:64&e?i=2:32&e?i=3:16&e&&(i=4);const s=ul(t,i),r=s in ol,a=r?ol[s].type:nl.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),u=((n&255>>o)<<8*(o-1))+ul(d),h=i+o;let c;return c=h+u>t.byteLength?new DataView(t.buffer,t.byteOffset+h):new DataView(t.buffer,t.byteOffset+h,u),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:h,tagSize:h+u,value:c,valueSize:u}},ul=(t,e=t.byteLength)=>{switch(e){case 1:return t.getUint8(0);case 2:return t.getUint16(0);case 3:return t.getUint16(0)<<8|t.getUint8(2);case 4:return t.getUint32(0);case 5:return t.getUint32(0)<<8|t.getUint8(4);case 6:return t.getUint32(0)<<16|t.getUint16(4);case 7:return t.getUint32(0)<<32|t.getUint16(4)<<8|t.getUint8(6);case 8:return t.getUint32(0)<<32|t.getUint32(4)}return 0},hl=(t,e)=>{switch(e){case nl.SignedInteger:return t.getInt8(0);case nl.UnsignedInteger:return ul(t);case nl.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case nl.String:return new TextDecoder('ascii').decode(t);case nl.UTF8:return new TextDecoder('utf-8').decode(t);case nl.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case nl.Master:case nl.Binary:return t;default:n(e)}},cl=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=dl(s);if(!e(r))return;r.type===nl.Master&&cl(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},ll=[al.Info,al.SeekHead,al.Tracks,al.Chapters,al.Cluster,al.Cues,al.Attachments,al.Tags],pl=[al.Timestamp,al.SilentTracks,al.SilentTrackNumber,al.Position,al.PrevSize,al.SimpleBlock,al.BlockGroup,al.EncryptedBlock],fl={validateData:t=>{if(t.getUint32(0)!==al.EBML)return!1;let e,i,s;const r=dl(t);return cl(r.value,(({tag:t,type:r,value:a})=>(t===al.EBMLReadVersion?e=hl(a,r):t===al.DocType?i=hl(a,r):t===al.DocTypeReadVersion&&(s=hl(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,r,a,n,o=!1,d=!1,u=!1;return cl(t,(({tag:t,type:h,value:c,valueSize:l})=>{if(t===al.SeekID){const t=hl(c,h);n=ul(t)}else t!==al.SeekPosition&&(n=void 0);return t===al.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===al.Info?o=!0:t===al.SeekHead?d=!0:t===al.TimestampScale?s=hl(c,h):t===al.Duration?r=hl(c,h):t===al.SeekPosition&&n===al.Cues?a=hl(c,h):o&&d&&ll.includes(t)&&(u=!0),!u})),l(e,'Failed to parse webm Segment start'),l(i,'Failed to parse webm Segment end'),l(r,'Failed to parse webm Segment duration'),s=null!=s?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:a}},getIndexRange:t=>{if(r(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,r=!1;const a=t=>s(t.time)&&s(t.position),n=[];let o;return cl(t,(({tag:t,type:e,value:s})=>{switch(t){case al.Cues:i=!0;break;case al.CuePoint:o&&a(o)&&n.push(o),o={};break;case al.CueTime:o&&(o.time=hl(s,e));break;case al.CueTrackPositions:break;case al.CueClusterPosition:o&&(o.position=hl(s,e));break;default:i&&ll.includes(t)&&(r=!0)}return!(i&&r)})),o&&a(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:r}=t,a=n[i+1];return{status:Gc.NONE,time:{from:s,to:a?a.time:e.segmentDuration},byte:{from:e.segmentStart+r,to:a?e.segmentStart+a.position-1:e.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{cl(t,(s=>s.tag===al.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!pl.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[al.SimpleBlock,al.BlockGroup,al.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class ml{constructor(o,d,u,h,{fetcher:c,tuning:p,getCurrentPosition:f}){switch(this.onLastSegment$=new t(!1),this.fullyBuffered$=new t(!1),this.playingRepresentation$=new t(void 0),this.error$=new e,this.gaps=[],this.subscription=new i,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new qd,this.destroyAbortController=new qd,this.bufferLimit=1/0,this.failedDownloads=0,this.startWith=T(this.destroyAbortController.signal,function(t){return Cd(this,arguments,(function*(){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`),this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.sourceBufferTaskQueue=new Xc(this.sourceBuffer),this.subscription.add(a(this.sourceBuffer,'updateend').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejected by browser',thrown:t})))),this.subscription.add(a(this.sourceBuffer,'error').subscribe((()=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired'})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>this.pruneBuffer(t)))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t)))),yield yield Ld(this.loadInit(e,'high',!0));const i=this.initData.get(e.id),r=this.segments.get(e.id);if(l(i,'No init buffer for starting representation'),l(r,'No segments for starting representation'),!(i instanceof ArrayBuffer))return yield Ld(void 0);let n=0;for(const t of r)t.time.from-n>=300&&this.gaps.push({representation:e.id,from:n,to:t.time.from}),n=t.time.to;s(e.duration)&&e.duration-n>=300&&this.gaps.push({representation:e.id,from:n,to:e.duration}),yield yield Ld(this.sourceBufferTaskQueue.append(i,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)}))}.bind(this)),this.switchTo=T(this.destroyAbortController.signal,function(t){return Cd(this,arguments,(function*(){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return yield Ld(void 0);this.switchingToRepresentationId=t;const e=this.representations.get(t);l(e,`No such representation ${t}`);let i=this.initData.get(t);if(r(i)?yield yield Ld(this.loadInit(e,'high',!1)):i instanceof Promise&&(yield yield Ld(i)),i=this.initData.get(t),!(i&&i instanceof ArrayBuffer&&this.sourceBuffer))return yield Ld(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abort(),yield yield Ld(this.sourceBufferTaskQueue.append(i,this.downloadAbortController.signal));const a=this.getCurrentPosition();s(a)&&this.maintain(a)}))}.bind(this)),this.fetcher=c,this.tuning=p,this.forwardBufferTarget=p.dash.forwardBufferTargetAuto,this.getCurrentPosition=f,this.container=u,u){case Yc.MP4:this.containerParser=rl;break;case Yc.WEBM:this.containerParser=fl;break;default:n(u)}this.initData=new Map(h.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(h.map((t=>[t.id,t]))),this.kind=o,this.mediaSource=d,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new qd,this.abortBuffer()}maintain(t){if(r(this.downloadingRepresentationId)||r(this.playingRepresentationId)||r(this.sourceBuffer))return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);if(l(e,`No such representation ${this.downloadingRepresentationId}`),!i)return;const s=i.find((e=>t>=e.time.from&&t<e.time.to));let a=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=100,i=xc(this.sourceBuffer.buffered,t),r=s?s.time.to+e:-1/0;s&&i>=s.time.to-t+e&&(a=r)}let n=[];if(isFinite(this.bufferLimit)&&(t=>{let e=0;for(let i=0;i<t.length;i++)e+=t.end(i)-t.start(i);return 1e3*e})(this.sourceBuffer.buffered)>=.8*this.bufferLimit)this.pruneBuffer(1/0);else if(!this.activeSegments.size&&(n=this.selectForwardBufferSegments(i,e.segmentReference.type,a),n.length)){let t='auto';if(this.tuning.dash.useFetchPriorityHints&&s)if(n.includes(s))t='high';else{const e=ac(n,0);e&&e.time.from-s.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,e,t)}!this.allInitsLoaded&&s&&s.status===Gc.FED&&!n.length&&xc(this.sourceBuffer.buffered,t)>3e3&&this.loadNextInit();const o=ac(i,-1);o&&o.status===Gc.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(s===o))}findSegmentStartTime(t){var e,i,s;const r=null!==(i=null!==(e=this.switchingToRepresentationId)&&void 0!==e?e:this.downloadingRepresentationId)&&void 0!==i?i:this.playingRepresentationId;if(!r)return;const a=this.segments.get(r);if(!a)return;const n=a.find((e=>e.time.from<=t&&e.time.to>=t));return null!==(s=null==n?void 0:n.time.from)&&void 0!==s?s:void 0}setTarget(t){this.forwardBufferTarget=t}destroy(){var t;this.initData.clear(),this.segments.clear(),this.representations.clear(),null===(t=this.sourceBufferTaskQueue)||void 0===t||t.destroy(),this.gapDetectionIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.gapDetectionIdleCallback),this.initLoadIdleCallback&&window.cancelIdleCallback&&window.cancelIdleCallback(this.initLoadIdleCallback),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.sourceBuffer=null,this.downloadAbortController.abort(),this.destroyAbortController.abort()}selectForwardBufferSegments(t,e,i){const s=t.findIndex((({status:t,time:{from:e,to:s}})=>t===Gc.NONE&&(e>i||e<=i&&s>=i)&&s<=i+this.forwardBufferTarget));if(-1===s)return[];if(e!==Hc.BYTE_RANGE)return t.slice(s,s+1);const r=t;let a=0;const n=[];for(let t=s;t<r.length&&a<=this.tuning.dash.segmentRequestSize;t++){const e=r[t];if(a+=e.byte.to+1-e.byte.from,e.status!==Gc.NONE)break;n.push(e)}return n}loadSegments(t,e,i='auto'){return Id(this,void 0,void 0,(function*(){if(!t.length)return;let s,r,a=t;const{type:o}=e.segmentReference;switch(o){case Hc.BYTE_RANGE:s=e.segmentReference.url,r={from:ac(t,0).byte.from,to:ac(t,-1).byte.to};break;case Hc.TEMPLATE:{const i=ac(t,0);s=new URL(i.url,e.segmentReference.baseUrl).toString(),a=[i];break}default:n(o)}for(const t of a)t.status=Gc.DOWNLOADING,this.activeSegments.add({segment:t,loadedBytes:0,fedBytes:0,representationId:e.id});const{signal:d}=this.downloadAbortController;if(this.failedDownloads&&(yield T(d,function(){return Cd(this,arguments,(function*(){const t=E(this.failedDownloads,this.tuning.downloadBackoff);yield yield Ld(new Promise((e=>setTimeout(e,t))))}))}.bind(this))(),d.aborted))for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.fetcher.fetch(s,{rangeMethod:Zc.PARAM,range:r,onProgress:(t,i)=>{if(!d.aborted)try{this.onSomeDataLoaded(t,e.id,r?r.from:0,i,d)}catch(t){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:t})}},signal:d,priority:i}).then((()=>this.failedDownloads=0),(e=>{for(const e of this.activeSegments)t.includes(e.segment)&&this.abortSegment(e.segment);this.onSegmentDownloadError(e)}))}))}onSegmentDownloadError(t){var e;let i=!1;const r=this.getCurrentPosition();if(this.sourceBuffer&&s(r)){i=xc(null===(e=this.sourceBuffer)||void 0===e?void 0:e.buffered,r)>=this.tuning.downloadBackoff.bufferThreshold}this.failedDownloads++,i||this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})}onSomeDataLoaded(t,e,i,s,r){if(!this.activeSegments.size)return;const a=t=>{this.abortSegment(t.segment)},n=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=Gc.FED,'size'in t.segment&&(t.segment.size=t.fedBytes);for(const s of this.representations.values())if(s.id!==e)for(const e of null!==(i=this.segments.get(s.id))&&void 0!==i?i:[])e.status===Gc.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=Gc.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])},o=this.representations.get(e);if(!o)return;const d=o.segmentReference.type,u=t.byteLength;for(const o of this.activeSegments){const{segment:h}=o,c=d===Hc.BYTE_RANGE,l=c?h.byte.to-h.byte.from+1:u;if(o.representationId!==e)continue;if(!(!c||h.byte.from>=i&&h.byte.to<i+t.byteLength))continue;if(r.aborted){a(o);continue}const p=c?h.byte.from-i:0,f=p<s,m=(c?h.byte.to-i:t.byteLength)<=s;if(h.status===Gc.DOWNLOADING&&f&&m){h.status=Gc.DOWNLOADED,this.activeSegments.delete(o);const e=new DataView(t.buffer,t.byteOffset+p,l);this.sourceBufferTaskQueue.append(e,r).then((t=>t&&!r.aborted?n(o):a(o)))}else if(this.tuning.dash.enableSubSegmentBufferFeeding&&f&&(o.loadedBytes=Math.min(l,s-p),o.loadedBytes>o.fedBytes)){const e=new DataView(t.buffer,t.byteOffset+p+o.fedBytes,o.loadedBytes-o.fedBytes),i=o.loadedBytes===l?e:this.containerParser.parseFeedableSegmentChunk(e);(null==i?void 0:i.byteLength)&&(h.status=Gc.PARTIALLY_FED,o.fedBytes+=i.byteLength,this.sourceBufferTaskQueue.append(i,r).then((t=>{!t||r.aborted?a(o):o.fedBytes===l&&n(o)})))}}}abortSegment(t){t.status===Gc.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=Gc.NONE)),t.status=Gc.NONE):t.status=Gc.NONE;for(const e of this.activeSegments.values())if(e.segment===t){this.activeSegments.delete(e);break}}loadNextInit(){if(this.allInitsLoaded||this.initLoadIdleCallback)return;let t=null,e=!1;for(const[i,s]of this.initData.entries()){const r=s instanceof Promise;e||(e=r),null===s&&(t=i)}if(!t)return void(this.allInitsLoaded=!0);if(e)return;const i=this.representations.get(t);i&&(this.initLoadIdleCallback=zc((()=>Sd(this.loadInit(i,'low',!1),(()=>this.initLoadIdleCallback=null)))))}loadInit(t,e='auto',i=!1){return Id(this,void 0,void 0,(function*(){const s=this.tuning.dash.useFetchPriorityHints?e:'auto',r=(!i&&this.failedDownloads>0?T(this.destroyAbortController.signal,function(){return Cd(this,arguments,(function*(){const t=E(this.failedDownloads,this.tuning.downloadBackoff);yield yield Ld(new Promise((e=>setTimeout(e,t))))}))}.bind(this))():Promise.resolve()).then((()=>this.fetcher.fetchRepresentation(t.segmentReference,this.containerParser,s))).then((e=>{if(!e)return;const{dataView:i,segments:s}=e,r=i.buffer.slice(i.byteOffset,i.byteOffset+i.byteLength);this.initData.set(t.id,r),this.segments.set(t.id,s)})).then((()=>this.failedDownloads=0),(e=>{this.initData.set(t.id,null),i&&this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,r),r}))}pruneBuffer(t){return Id(this,void 0,void 0,(function*(){const e=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||r(e))return!1;if(this.sourceBuffer.updating)return!1;const i=this.segments.get(this.playingRepresentationId);if(!i)return!1;let s=0,a=1/0,n=-1/0,o=!1;const d=t=>{var e;a=Math.min(a,t.time.from),n=Math.max(n,t.time.to);const i='size'in t?null!==(e=t.size)&&void 0!==e?e:0:t.byte.to-t.byte.from;s+=i};for(const r of i){if(r.time.to>=e||s>=t)break;r.status===Gc.FED&&d(r)}if(o=isFinite(a)&&isFinite(n),!o){s=0,a=1/0,n=-1/0;for(const r of i){if(r.time.from<e+this.forwardBufferTarget||s>t)break;r.status===Gc.FED&&d(r)}}return o=isFinite(a)&&isFinite(n),!!o&&this.sourceBufferTaskQueue.remove(a/1e3,n/1e3)}))}abortBuffer(){if(!this.sourceBuffer||'open'!==this.mediaSource.readyState)return;const t=this.playingRepresentationId&&this.initData.get(this.playingRepresentationId),e=t instanceof ArrayBuffer?t:void 0;this.sourceBufferTaskQueue.abort(e)}detectGaps(t,e){if(this.sourceBuffer)for(const i of e){let e={representation:t,from:i.time.from,to:i.time.to};for(let t=0;t<this.sourceBuffer.buffered.length;t++){const s=1e3*this.sourceBuffer.buffered.start(t),r=1e3*this.sourceBuffer.buffered.end(t);if(!(r<=i.time.from||s>=i.time.to)){if(s<=i.time.from&&r>=i.time.to){e=void 0;break}r>i.time.from&&r<i.time.to&&(e.from=r),s<i.time.to&&s>i.time.from&&(e.to=s)}}e&&e.to-e.from>=1&&this.gaps.push(e)}}detectGapsWhenIdle(t,e){this.gapDetectionIdleCallback||(this.gapDetectionIdleCallback=zc((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(r(this.sourceBuffer)||r(this.playingRepresentationId))return;const t=[];for(let e=0;e<this.sourceBuffer.buffered.length;e++){const i=1e3*this.sourceBuffer.buffered.start(e),s=1e3*this.sourceBuffer.buffered.end(e);t.push({from:i,to:s})}const e=this.tuning.dash.segmentTimelineTolerance;for(const i of this.segments.values())for(const s of i){const i=t.some((t=>t.from-e<=s.time.from&&t.to+e>=s.time.to));s.status!==Gc.FED||i||(s.status=Gc.NONE)}}}const vl=t=>{if(!t.startsWith('P'))return;const e=(t,e)=>{const i=t?parseFloat(t.replace(',','.')):NaN;return(isNaN(i)?0:i)*e},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(t),s='-'===(null==i?void 0:i[1])?-1:1;return 24*e(null==i?void 0:i[5],s)*60*60*1e3+60*e(null==i?void 0:i[6],s)*60*1e3+60*e(null==i?void 0:i[7],s)*1e3+1e3*e(null==i?void 0:i[8],s)},gl=(t,e)=>{let i=t;i=i.replaceAll('$$','$');const s={RepresentationID:e.representationId,Number:e.segmentNumber,Bandwidth:e.bandwidth,Time:e.segmentTime};for(const[t,e]of Object.entries(s)){const s=new RegExp(`\\$${t}(?:%0(\\d+)d)?\\$`,'g');i=i.replaceAll(s,((t,i)=>r(e)?t:r(i)?e:e.padStart(parseInt(i,10),'0')))}return i},Sl=(t,e)=>{var i,r,a,n,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$,k,A,P,D,_,R,I,L,C,x,O,N,B;const M={video:[],audio:[],text:[]},U=(new DOMParser).parseFromString(t,'application/xml').children[0],V=U.getElementsByTagName('Period')[0],q=V.children;let F;const H=U.getAttribute('mediaPresentationDuration'),G=V.getAttribute('duration');if(H)F=vl(H);else if(G){const t=vl(G);s(t)&&(F=t)}let Y=0;const j=null!==(r=null===(i=U.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==r?r:[],z=j.includes(Fc.WEBM_AS_IN_FFMPEG)||j.includes(Fc.WEBM_AS_IN_SPEC)?Yc.WEBM:Yc.MP4;for(const t of q){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==i?void 0:i.split('/')[0],U=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],V=t.querySelectorAll('Representation');if('text'!==r)for(const a of V){const n=null!==(d=a.getAttribute('mimeType'))&&void 0!==d?d:i,o=null!==(h=null!==(u=a.getAttribute('codecs'))&&void 0!==u?u:s)&&void 0!==h?h:'',V=null!==(l=null!==(c=a.getAttribute('contentType'))&&void 0!==c?c:null==n?void 0:n.split('/')[0])&&void 0!==l?l:r,q=null!==(f=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==f?f:[],H=parseInt(null!==(m=a.getAttribute('width'))&&void 0!==m?m:'',10),G=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),z=parseInt(null!==(g=a.getAttribute('bandwidth'))&&void 0!==g?g:'',10)/1e3,Q=null!==(S=a.getAttribute('frameRate'))&&void 0!==S?S:'',W=null!==(b=a.getAttribute('quality'))&&void 0!==b?b:void 0,J=Q?ec(Q):void 0,K=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(Y++).toString(10)}@${'video'===V?`${G}p`:'audio'===V?`${z}Kbps`:o}`,X=null!==(w=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==w?w:'',Z=new URL(X,e).toString(),tt=[...j,...U,...q];let et;const it=a.querySelector('SegmentBase'),st=a.querySelector('SegmentTemplate');if(it){const t=null!==(k=null===($=a.querySelector('SegmentBase Initialization'))||void 0===$?void 0:$.getAttribute('range'))&&void 0!==k?k:'',[e,i]=t.split('-').map((t=>parseInt(t,10))),s={from:e,to:i},r=null===(A=a.querySelector('SegmentBase'))||void 0===A?void 0:A.getAttribute('indexRange'),[n,o]=r?r.split('-').map((t=>parseInt(t,10))):[],d=r?{from:n,to:o}:void 0;et={type:Hc.BYTE_RANGE,url:Z,initRange:s,indexRange:d}}else{if(!st)throw new ReferenceError('Unknown MPD segment referencing type');{const t={representationId:null!==(P=a.getAttribute('id'))&&void 0!==P?P:void 0,bandwidth:null!==(D=a.getAttribute('bandwidth'))&&void 0!==D?D:void 0},e=parseInt(null!==(_=st.getAttribute('timescale'))&&void 0!==_?_:'',10),i=null!==(R=st.getAttribute('initialization'))&&void 0!==R?R:'',s=st.getAttribute('media'),r=null!==(L=parseInt(null!==(I=st.getAttribute('startNumber'))&&void 0!==I?I:'',10))&&void 0!==L?L:1,n=gl(i,t);if(!s)throw new ReferenceError('No media attribute in SegmentTemplate');const o=null!==(C=st.querySelectorAll('SegmentTimeline S'))&&void 0!==C?C:[],d=[];let u=r,h=0;for(const i of o){const r=1e3*parseInt(null!==(x=i.getAttribute('d'))&&void 0!==x?x:'',10),a=parseInt(null!==(O=i.getAttribute('r'))&&void 0!==O?O:'',10)||0,n=null!==(B=parseInt(null!==(N=i.getAttribute('t'))&&void 0!==N?N:'',10))&&void 0!==B?B:void 0;for(let i=0;i<a+1;i++){const i=gl(s,Object.assign(Object.assign({},t),{segmentNumber:u.toString(10),segmentTime:n.toString(10)})),a=n?n/e:h;h+=r/e;const o=h;u++,d.push({time:{from:a,to:o},url:i})}}et={type:Hc.TEMPLATE,baseUrl:Z,initUrl:n,segments:d}}}if(!V||!n)continue;const rt={video:qc.VIDEO,audio:qc.AUDIO,text:qc.TEXT}[V];rt&&M[rt].push({id:K,kind:rt,segmentReference:et,profiles:tt,duration:F,bitrate:z,mime:n,codecs:o,width:H,height:G,fps:J,quality:W})}}return{duration:F,container:z,representations:M}},bl=['timeupdate','progress','play','seeked','stalled'];var yl,Tl;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(yl||(yl={}));class El{constructor(r){this.element=null,this.source=null,this.manifest=null,this.subscription=new i,this.state$=new Dd(yl.NONE),this.currentVideoRepresentation$=new t(void 0),this.error$=new e,this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.forceEnded$=new e,this.gapWatchdogStarted=!1,this.destroyController=new qd,this.initManifest=T(this.destroyController.signal,function(t,e){return Cd(this,arguments,(function*(){this.element=t,this.state$.startTransitionTo(yl.MANIFEST_LOADED);const i=yield yield Ld(this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:t}))));if(!i)return yield Ld(null);let s;try{s=Sl(null!=i?i:'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}if(!s)return yield Ld(null);const r=({mime:e,codecs:i})=>{var s,r,a;return Boolean((null===(s=t.canPlayType)||void 0===s?void 0:s.call(t,e))&&(null===(a=null===(r=window.MediaSource)||void 0===r?void 0:r.isTypeSupported)||void 0===a?void 0:a.call(r,`${e}; codecs="${i}"`)))};return this.manifest=Object.assign(Object.assign({},s),{representations:qh(Object.entries(s.representations).map((([t,e])=>[t,e.filter(r)])))}),this.manifest.representations.video.length?this.state$.setState(yl.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),yield Ld(this.manifest)}))}.bind(this)),this.initRepresentations=T(this.destroyController.signal,function(t,e){return Cd(this,arguments,(function*(){l(this.manifest),l(this.element),this.state$.startTransitionTo(yl.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new ml(qc.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.bufferManagers=[this.videoBufferManager],s(e)&&(this.audioBufferManager=new ml(qc.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),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 r=o(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(u((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),n=o(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(u((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(o(this.forceEnded$,y({allBuffersFull:r,someBufferEnded:n}).pipe(m((({allBuffersFull:t,someBufferEnded:e})=>t&&e)))).subscribe((()=>{var t;if(this.source&&'open'===this.source.readyState&&Array.from(this.source.sourceBuffers).every((t=>!t.updating)))try{null===(t=this.source)||void 0===t||t.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield yield Ld(new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)})))),s(this.manifest.duration)&&(this.source.duration=this.manifest.duration/1e3),this.audioBufferManager&&s(e)?yield yield Ld(Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)])):yield yield Ld(this.videoBufferManager.startWith(t)),this.state$.setState(yl.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...bl.map((t=>a(this.element,t))),a(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(a(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(a(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&jc(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}))}.bind(this)),this.tick=()=>{var t,e;if(!this.element||!this.videoBufferManager)return;const i=1e3*this.element.currentTime;this.videoBufferManager.maintain(i),null===(t=this.audioBufferManager)||void 0===t||t.maintain(i),!this.videoBufferManager.gaps.length&&!(null===(e=this.audioBufferManager)||void 0===e?void 0:e.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=w(this.tuning.gapWatchdogInterval).subscribe((()=>this.jumGap()),(t=>{this.error$.next({id:'GapWatchdog',message:'Error handling gaps',thrown:t})})),this.subscription.add(this.gapWatchdogSubscription))},this.throughputEstimator=r.throughputEstimator,this.tuning=r.tuning,this.fetcher=new tl({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}switchRepresentation(t,e){return Id(this,void 0,void 0,(function*(){const i={[qc.VIDEO]:this.videoBufferManager,[qc.AUDIO]:this.audioBufferManager,[qc.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}))}seek(t,e){var i,s,r,a,n;let o;l(this.element),l(this.videoBufferManager),o=e||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-t)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?t:Math.max(null!==(i=this.videoBufferManager.findSegmentStartTime(t))&&void 0!==i?i:t,null!==(r=null===(s=this.audioBufferManager)||void 0===s?void 0:s.findSegmentStartTime(t))&&void 0!==r?r:t),jc(this.element.buffered,o)||(this.videoBufferManager.abort(),null===(a=this.audioBufferManager)||void 0===a||a.abort()),this.videoBufferManager.maintain(o),null===(n=this.audioBufferManager)||void 0===n||n.maintain(o),this.element.currentTime=o/1e3}stop(){var t,e;this.element=null,this.source=null,this.manifest=null,this.currentVideoRepresentation$.next(void 0),null===(t=this.videoBufferManager)||void 0===t||t.destroy(),this.videoBufferManager=null,null===(e=this.audioBufferManager)||void 0===e||e.destroy(),this.audioBufferManager=null,this.bufferManagers=[],this.state$.setState(yl.NONE)}setBufferTarget(t){for(const e of this.bufferManagers)e.setTarget(t)}destroy(){this.subscription.unsubscribe(),this.destroyController.abort(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager)return;const t=1e3*this.element.currentTime,e=1===this.element.readyState?this.tuning.endGapTolerance:0;for(const i of this.bufferManagers)for(const s of i.gaps)if(i.playingRepresentation$.getValue()===s.representation&&s.from-e<=t&&s.to+e>t){if(1e3*this.element.duration-s.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=s.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Tl||(Tl={}));const wl=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?yc(a):void 0)&&void 0!==n?n:Ad({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},$l=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=ac(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:ac(t,-1)};class kl{constructor(e){this.subscription=new i,this.videoState=new Dd(Tl.STOPPED),this.elementSize$=new t(void 0),this.textTracksManager=new Wh,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new lc,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(s.state===C.Requested&&(null==i?void 0:i.to)!==P.PAUSED&&t!==Tl.STOPPED&&e!==P.STOPPED&&this.seek(s.position,s.forcePrecise),e!==P.STOPPED){if(t===Tl.STOPPED)return this.videoState.startTransitionTo(Tl.READY),void this.prepare();switch(t){case Tl.READY:return void(e===P.PAUSED?(this.videoState.setState(Tl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Tl.PLAYING),this.playIfAllowed()));case Tl.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Tl.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Td(this.params.desiredState.playbackState,P.PLAYING));case Tl.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Tl.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Td(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==Tl.STOPPED&&(this.videoState.startTransitionTo(Tl.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(Tl.STOPPED),Td(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=e,this.video=Jh(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(fc(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new El({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=tc(this.video),r=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,r));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.playing$,t.firstFrameEvent$),n(i.canplay$,t.canplay$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(m(s),b(),v(void 0)),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(jh(this.video,e.isLooped,r)),this.subscription.add(zh(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),n(mc(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(Tl.PLAYING),Td(e.playbackState,P.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(Tl.PAUSED),Td(e.playbackState,P.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===Tl.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(m((({to:t})=>t===yl.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(Tl.READY)})));const d=e=>t.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:e});this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a(this.video,'progress')).subscribe((()=>{var i,s,r,a,n,o,u,h;const c=this.player.state$.getState(),p=this.player.state$.getTransition();if(c===yl.NONE||!this.videoTracks.length)return;const f=c===yl.MANIFEST_LOADED&&!p,m=c===yl.REPRESENTATION_SELECTED&&!p,v=e.autoVideoTrackSwitching.getState(),g=e.videoTrack.getState(),S=null===(i=this.videoTracks.find((({track:{id:t}})=>t===g)))||void 0===i?void 0:i.track,b=t.currentVideoTrack$.getValue(),y=xc(this.video.buffered,1e3*this.video.currentTime),T=v?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,E=Math.min(y/Math.min(T,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),w=Math.max(S&&!v&&null!==(r=null===(s=this.audioRepresentations.get(S.id))||void 0===s?void 0:s.bitrate)&&void 0!==r?r:0,b&&null!==(n=null===(a=this.audioRepresentations.get(b.id))||void 0===a?void 0:a.bitrate)&&void 0!==n?n:0),$=pc(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),reserve:w,forwardBufferHealth:E,current:b,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),k=v?null!=$?$:S:null!=S?S:$;if(e.autoVideoTrackSwitching.getTransition()&&(e.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),f){const t=k&&(null===(o=this.videoTracks.find((({track:t})=>t===k)))||void 0===o?void 0:o.representation);l(t),this.player.initRepresentations(t.id,null===(u=this.audioRepresentations.get(t.id))||void 0===u?void 0:u.id)}else if(m){const t=k&&(null===(h=this.videoTracks.find((({track:t})=>t===k)))||void 0===h?void 0:h.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(qc.VIDEO,t.id).catch(d),e&&this.player.switchRepresentation(qc.AUDIO,e.id).catch(d)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),u((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const f=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(f.subscribe(this.syncPlayback,r))}prepare(){return Id(this,void 0,void 0,(function*(){const t=yield this.player.initManifest(this.video,this.params.source.url);if(!t)return;this.videoTracks=[];const e=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),i=Array.from(t.representations.video).sort(((t,e)=>e.bitrate-t.bitrate));for(const t of i){const s=wl(t);if(s){this.videoTracks.push({track:s,representation:t});const r=$l(e,i,t);r&&this.audioRepresentations.set(t.id,r)}}this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}))}seek(t,e){this.params.output.willSeekEvent$.next(),this.player.seek(t,e)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){Tc(this.video).then((t=>{t||(this.videoState.setState(Tl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}const Al={};var Pl;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Pl||(Pl={}));const Dl=(t,e)=>new S((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class _l{constructor(t){this.subscription=new i,this.videoState=new Dd(Pl.INITIALIZING),this.textTracksManager=new Wh,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.seekState.getState();if(t!==Pl.INITIALIZING)switch((null==i?void 0:i.to)!==P.PAUSED&&s.state===C.Requested&&this.seek(s.position),e){case P.STOPPED:switch(t){case Pl.STOPPED:break;case Pl.READY:case Pl.PLAYING:case Pl.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Pl.PLAYING:break;case Pl.STOPPED:this.prepare();break;case Pl.READY:case Pl.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case Pl.PAUSED:break;case Pl.STOPPED:this.prepare();break;case Pl.READY:this.videoState.setState(Pl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED);break;case Pl.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}},this.video=Jh(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(fc(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Sd(import('hls.js').then((e=>{t||(Al.Hls=e.default,Al.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(Al.Hls,'hls.js not loaded'),this.hls=new Al.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Pl.STOPPED)}subscribe(){l(Al.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=tc(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,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.loadStart$,e.firstBytesEvent$),n(a.playing$,e.firstFrameEvent$),n(a.canplay$,e.canplay$),n(a.seeked$,e.seekedEvent$),this.subscription.add(jh(this.video,t.isLooped,i)),this.subscription.add(zh(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Dl(this.hls,Al.Events.ERROR).subscribe((t=>{var i;t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(i=t.err)||void 0===i?void 0:i.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(Pl.PLAYING),Td(t.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(Pl.PAUSED),Td(t.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Pl.READY&&this.videoState.setState(Pl.READY),this.videoState.getState()===Pl.PLAYING&&this.playIfAllowed()}),i)),n(Dl(this.hls,Al.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=yc(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:Ad({width:a,height:n});if(!o)return t;const d=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:d};return this.trackLevels.set(r,{track:u,level:e}),t.push(u),t}),[])))),e.availableVideoTracks$),n(Dl(this.hls,Al.Events.LEVEL_LOADING).pipe(u((({url:t})=>fc(t)))),e.hostname$),this.subscription.add(Yh(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const d=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},c=Dl(this.hls,Al.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>d(this.hls.levels[t]))));c.pipe(m(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(Yh(t.videoTrack,(()=>{var t;return null===(t=d(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.trackLevels.get(t))||void 0===e?void 0:e.level;if(!i)return;const s=this.hls.levels.indexOf(i),a=this.hls.currentLevel,n=this.hls.levels[a];!n||i.bitrate>n.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:c.pipe(u((t=>null==t?void 0:t.id))),onError:i})),n(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const f=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(f.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(Pl.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return Id(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(Pl.PLAYING);(yield Tc(this.video))||(this.videoState.setState(Pl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(Pl.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/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(Pl.STOPPED),Td(this.params.desiredState.playbackState,P.STOPPED,!0)}}const Rl=t=>{let e=null;if(t.QUALITY&&(e=yc(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=Ad({width:i,height:s})}return null!=e?e:null},Il=(t,e=t)=>Id(void 0,void 0,void 0,(function*(){var i;const s=yield Vd(t),r=(yield s.text()).split('\n'),a=[];for(let t=0;t<r.length;t++){const s=r[t].match(/^#EXT-X-STREAM-INF:(.+)/);if(!s)continue;const n=qh(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,d=Rl(n);let u;n.BANDWIDTH&&(u=parseInt(n.BANDWIDTH,10)/1e3||void 0),!u&&n['AVERAGE-BANDWIDTH']&&(u=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let c;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(c={width:t,height:e})}const l=new URL(r[++t],e).toString();d&&a.push({id:o,quality:d,url:l,bandwidth:u,size:c,fps:h})}return a}));var Ll,Cl,xl,Ol,Nl,Bl,Ml,Ul,Vl,ql,Fl,Hl,Gl,Yl,jl,zl,Ql,Wl,Jl,Kl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Ll||(Ll={}));class Xl{constructor(e){var s;this.subscription=new i,this.videoState=new Dd(Ll.STOPPED),this.textTracksManager=new Wh,this.manifests$=new t([]),this.liveOffset=new Kh,this.manifestStartTime$=new t(void 0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Ll.STOPPED&&(this.videoState.startTransitionTo(Ll.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(Ll.STOPPED),Td(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===Ll.STOPPED)return this.videoState.startTransitionTo(Ll.READY),void this.prepare();if(s||r){const t=this.videoState.getState();return this.videoState.setState(Ll.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested)return this.videoState.startTransitionTo(Ll.READY),this.seek(a.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(t){case Ll.READY:return void(e===P.PAUSED?(this.videoState.setState(Ll.PAUSED),this.liveOffset.pause(),Td(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Ll.PLAYING),this.playIfAllowed()));case Ll.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Ll.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Td(this.params.desiredState.playbackState,P.PLAYING));case Ll.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Ll.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())):(null==i?void 0:i.to)===P.PAUSED&&(Td(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case Ll.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=Jh(e.container),this.params.output.element$.next(this.video);const r={id:'master',quality:bd.INVARIANT,url:this.params.source.url};this.manifests$.next([r]),Il(yd(this.params.source.url),this.params.source.url).then((t=>{this.manifests$.next([r,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.params.output.isLive$.next(!0),this.params.output.hostname$.next(fc(this.params.source.url)),this.maxSeekBackTime$=new t(null!==(s=e.source.maxSeekBackTime)&&void 0!==s?s:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},r=tc(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.ended$,t.endedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(zh(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Ll.PLAYING),Td(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Ll.PAUSED),Td(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Ll.READY&&this.videoState.setState(Ll.READY),this.videoState.getState()===Ll.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),u((t=>-t/1e3))).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(fc(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Ll.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&t.state===C.Requested&&this.seek(t.position)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),i)),this.subscription.add(y({startTime:this.manifestStartTime$.pipe(m(s)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,h(['init'])).pipe(p(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(r(t))return;const e=yd(t.url,this.liveOffset.getTotalOffset());var i;this.video.setAttribute('src',e),this.video.load(),(i=e,Id(void 0,void 0,void 0,(function*(){const t=yield Vd(i,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){Tc(this.video).then((t=>{t||(this.videoState.setState(Ll.PAUSED),this.liveOffset.pause(),Td(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-t,i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(-i/1e3),this.params.output.seekedEvent$.next()}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Cl||(Cl={}));class Zl{constructor(e){this.subscription=new i,this.videoState=new Dd(Cl.STOPPED),this.textTracksManager=new Wh,this.manifests$=new t([]),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==Cl.STOPPED&&(this.videoState.startTransitionTo(Cl.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(Cl.STOPPED),Td(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const a=this.params.desiredState.seekState.getState();if(t===Cl.STOPPED)return this.videoState.startTransitionTo(Cl.READY),void this.prepare();if(s||r){const t=this.videoState.getState();this.videoState.setState(Cl.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(a.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&a.state===C.Requested&&this.seek(a.position),t){case Cl.READY:return void(e===P.PAUSED?(this.videoState.setState(Cl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(Cl.PLAYING),this.playIfAllowed()));case Cl.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(Cl.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Td(this.params.desiredState.playbackState,P.PLAYING));case Cl.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(Cl.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Td(this.params.desiredState.playbackState,P.PAUSED));case Cl.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=Jh(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:bd.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(fc(this.params.source.url)),Il(this.params.source.url).then((t=>{this.manifests$.next([s,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},r=tc(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(jh(this.video,e.isLooped,i)),this.subscription.add(zh(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Cl.PLAYING),Td(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Cl.PAUSED),Td(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Cl.READY&&this.videoState.setState(Cl.READY),this.videoState.getState()===Cl.PLAYING&&this.playIfAllowed()}),i).add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(fc(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Cl.CHANGING_MANIFEST&&this.videoState.setState(e.to),t.state===C.Requested&&this.seek(t.position)}),i))),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();r(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){Tc(this.video).then((t=>{t||(this.videoState.setState(Cl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(xl||(xl={}));class tp{constructor(t){this.subscription=new i,this.videoState=new Dd(xl.STOPPED),this.trackUrls={},this.textTracksManager=new Wh,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==xl.STOPPED&&(this.videoState.startTransitionTo(xl.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(xl.STOPPED),Td(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.seekState.getState();if(t===xl.STOPPED)return this.videoState.startTransitionTo(xl.READY),void this.prepare();if(s){const{currentTime:t}=this.video;return this.prepare(),void(r.state===C.None&&this.params.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==i?void 0:i.to)!==P.PAUSED&&r.state===C.Requested&&this.seek(r.position),t){case xl.READY:return void(e===P.PAUSED?(this.videoState.setState(xl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(xl.PLAYING),this.playIfAllowed()));case xl.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(xl.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Td(this.params.desiredState.playbackState,P.PLAYING));case xl.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(xl.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Td(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}},this.params=t,this.video=Jh(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},r=tc(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.loadedMetadata$,t.firstBytesEvent$),a(r.playing$,t.firstFrameEvent$),a(r.canplay$,t.canplay$),a(r.seeked$,t.seekedEvent$),this.subscription.add(jh(this.video,e.isLooped,i)),this.subscription.add(zh(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(xl.PLAYING),Td(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(xl.PAUSED),Td(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===xl.READY&&this.videoState.setState(xl.READY);const e=this.params.desiredState.videoTrack.getTransition();e&&s(e.to)&&(this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to].track)),this.videoState.getState()===xl.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,h(['init'])).pipe(p(0));this.subscription.add(n.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 t,e;const i=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState();l(i,'MpegProvider: track is not selected');let{url:s}=this.trackUrls[i];l(s,`MpegProvider: No url for ${i}`),this.params.tuning.requestQuick&&(s=Hh(s)),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(fc(s))}playIfAllowed(){Tc(this.video).then((t=>{t||(this.videoState.setState(xl.PAUSED),Td(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}class ep{constructor(t){this.iterator=t[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)}}const ip=Jc(),sp=(null===(Ol=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Ol?void 0:Ol.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),rp=document.createElement('video'),ap={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Bl=null===(Nl=window.SourceBuffer)||void 0===Nl?void 0:Nl.prototype)||void 0===Bl?void 0:Bl.appendBuffer)),hls:Boolean((null===(Ml=rp.canPlayType)||void 0===Ml?void 0:Ml.call(rp,'application/x-mpegurl'))||(null===(Ul=rp.canPlayType)||void 0===Ul?void 0:Ul.call(rp,'vnd.apple.mpegURL')))},np={mp4:Boolean(null===(Vl=rp.canPlayType)||void 0===Vl?void 0:Vl.call(rp,'video/mp4')),webm:Boolean(null===(ql=rp.canPlayType)||void 0===ql?void 0:ql.call(rp,'video/webm'))},op={h264:Boolean(null===(Hl=null===(Fl=window.MediaSource)||void 0===Fl?void 0:Fl.isTypeSupported)||void 0===Hl?void 0:Hl.call(Fl,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(Yl=null===(Gl=window.MediaSource)||void 0===Gl?void 0:Gl.isTypeSupported)||void 0===Yl?void 0:Yl.call(Gl,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(zl=null===(jl=window.MediaSource)||void 0===jl?void 0:jl.isTypeSupported)||void 0===zl?void 0:zl.call(jl,'video/webm; codecs="vp9"')),aac:Boolean(null===(Wl=null===(Ql=window.MediaSource)||void 0===Ql?void 0:Ql.isTypeSupported)||void 0===Wl?void 0:Wl.call(Ql,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Kl=null===(Jl=window.MediaSource)||void 0===Jl?void 0:Jl.isTypeSupported)||void 0===Kl?void 0:Kl.call(Jl,'audio/webm; codecs="opus"'))},dp=(op.h264||op.h265)&&op.aac,up=!ip,hp=sp||ip,cp=!ap.hls||!hp;const lp=3e4,pp=18e4,fp=3,mp=100,vp={cacheDuration:12e4},gp={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},Sp={maxPausedTime:3e4},bp={maxPausedTime:3e4};class yp{constructor(r){this.current$=new t({type:void 0}),this.providerError$=new e,this.noAvailableProvidersError$=new e,this.providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,canplay$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)},this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:a}=this.params.tuning,o=a.length?[...r.screenFormatsPriority.filter((t=>!a.includes(t))),...r.screenFormatsPriority.filter((t=>a.includes(t)))]:r.screenFormatsPriority;this.screenFormatsIterator=new ep(o.filter((t=>s(r.sources[t]))).filter((t=>{switch(t){case D.DASH:return ap.mse&&np.mp4&&dp&&up;case D.DASH_SEP:case D.DASH_SEP_VK:return ap.mse&&np.mp4&&dp;case D.DASH_WEBM:case D.DASH_WEBM_VK:case D.DASH_LIVE_WEBM:return ap.mse&&np.webm&&op.vp9&&op.opus;case D.DASH_LIVE:return ap.mse&&np.mp4&&dp;case D.DASH_ONDEMAND:case D.DASH_ONDEMAND_VK:return ap.mse&&np.mp4&&dp;case D.HLS:case D.HLS_LIVE:case D.HLS_ONDEMAND:return ap.hls&&np.mp4&&hp;case D.HLS_JS:return ap.mse&&np.mp4&&dp&&cp;case D.MPEG:return np.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new ep(r.chromecastFormatsPriority.filter((t=>s(r.sources[t]))))}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 t=this.chooseDestination(),e=this.chooseFormat(t);if(r(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;l(t,'No current provider'),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=1e3*this.providerOutput.position$.getValue(),i=this.params.desiredState.seekState.getState(),s=i.state!==C.None;this.params.desiredState.seekState.setState({state:C.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case _.SCREEN:return this.createScreenProvider(e);case _.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,r={container:i,source:null,desiredState:s,output:this.providerOutput,dependencies:this.params.dependencies,tuning:this.params.tuning};switch(t){case D.DASH:{const i=e[t];return l(i),new Vc(Object.assign(Object.assign({},r),{source:i,config:vp}))}case D.DASH_ONDEMAND_VK:case D.DASH_SEP_VK:case D.DASH_WEBM_VK:{const i=e[t];return l(i),new kl(Object.assign(Object.assign({},r),{source:i}))}case D.DASH_SEP:case D.DASH_WEBM:case D.DASH_ONDEMAND:case D.DASH_LIVE_WEBM:{const i=e[t];return l(i),new bc(Object.assign(Object.assign({},r),{source:i,format:t,config:bp}))}case D.HLS:case D.HLS_ONDEMAND:{const i=e[t];return l(i),new Zl(Object.assign(Object.assign({},r),{source:i}))}case D.HLS_LIVE:{const i=e[t];return l(i),new Xl(Object.assign(Object.assign({},r),{source:i,config:Sp}))}case D.HLS_JS:{const i=e[t];return l(i),new _l(Object.assign(Object.assign({},r),{source:i}))}case D.MPEG:{const i=e[t];return l(i),new tp(Object.assign(Object.assign({},r),{source:i}))}case D.DASH_LIVE:{const i=e[t];return l(i),new Lc(Object.assign(Object.assign({},r),{source:i,config:gp}))}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:r}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new Rd({connection:n,meta:r,container:i,source:e,format:t,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?_.CHROMECAST:_.SCREEN}chooseFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case _.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case _.SCREEN:return this.screenFormatsIterator.next();case _.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case _.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case _.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let t=[],r=0;const a=new i;var n;return a.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:lp,position$:this.providerOutput.position$,providerChanged$:this.current$.pipe(m((({type:t})=>void 0!==t)))},new S((t=>{const s=new i,r=n.desiredPlaybackState$.stateChangeStarted$.pipe(u((({from:t,to:e})=>`${t}-${e}`))),a=n.desiredPlaybackState$.stateChangeEnded$,o=n.providerChanged$,d=new e;let h=0,c='unknown';return s.add(r.subscribe((t=>{h&&window.clearTimeout(h),c=t,h=window.setTimeout((()=>d.next(t)),n.maxTransitionInterval)}))),s.add(a.subscribe((()=>{window.clearTimeout(h),c='provider change',h=0}))),s.add(o.subscribe((()=>{h&&(window.clearTimeout(h),h=window.setTimeout((()=>d.next(c)),n.maxTransitionInterval))}))),s.add(d.subscribe(t)),()=>{window.clearTimeout(h),s.unsubscribe()}}))).pipe(u((t=>({id:`ProviderHangup:${t}`,message:`A ${t} transition failed to complete within reasonable time`}))))).subscribe(this.providerError$)),a.add(this.providerError$.pipe($(mp,{leading:!1,trailing:!0})).subscribe((()=>{const e=Date.now();this.current$.getValue().destination===_.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(t[r])&&e<t[r]+pp?(t=[],this.switchToNextProvider()):(t[r]=e,this.reinitProvider()),r=(r+1)%fp}))),a}}const Tp=(t,e,i)=>i*e+(1-i)*t;class Ep{constructor(e){var i;this.prevReported=void 0,this.pastMeasures=[],this.measuresCursor=0,this.params=e,this.pastMeasures=Array(e.deviationDepth),this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new hc(`raw_${s}`),this.smoothedSeries$=new hc(`smoothed_${s}`),this.reportedSeries$=new hc(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(t){let e=0,i=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(e+=Math.pow(this.pastMeasures[t]-this.smoothed,2),i++);e/=i;const s=Math.sqrt(e),a=this.smoothed+this.params.deviationFactor*s,n=this.smoothed-this.params.deviationFactor*s;this.pastMeasures[this.measuresCursor]=t,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(t),this.slow=Tp(this.slow,t,this.params.emaAlphaSlow),this.fast=Tp(this.fast,t,this.params.emaAlphaFast);const o=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=o(this.slow,this.fast),this.smoothed$.next(this.smoothed),this.smoothedSeries$.next(this.smoothed),this.smoothed>a||this.smoothed<n||(r(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))}}var wp;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(wp||(wp={}));const $p=new Map;let kp=wp.RUNTIME;const Ap=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Ap,'test'),localStorage.removeItem(Ap),kp=wp.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Ap),kp=wp.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;kp=wp.RUNTIME}}})();const Pp=(t,e)=>{switch(kp){case wp.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case wp.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case wp.RUNTIME:return void $p.set(t,e);default:n(kp)}},Dp=window.navigator.connection,_p=()=>{const t=null==Dp?void 0:Dp.downlink;if(s(t)&&10!==t)return 1e3*t},Rp=()=>{const t=null==Dp?void 0:Dp.rtt;if(s(t)&&3e3!==t)return t},Ip=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Lp{constructor(e){var r,n;this.subscription=new i,this.concurrentDownloads=new Set,this.tuningConfig=e;const o=Lp.load('one_video_throughput')||(e.useBrowserEstimation?_p():void 0)||5e3,d=null!==(n=null!==(r=Lp.load('one_video_rtt'))&&void 0!==r?r:e.useBrowserEstimation?Rp():void 0)&&void 0!==n?n:0;if(this.throughput$=new t(o),this.rtt$=new t(d),this.rttAdjustedThroughput$=new t(Ip(o,d,e.rttPenaltyRequestSize)),this.throughput=new Ep({initial:o,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Ep({initial:d,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=_p();t&&this.throughput.next(t);const e=Rp();s(e)&&this.rtt.next(e)};Dp&&'onchange'in Dp&&this.subscription.add(a(Dp,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Pp('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Pp('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(y({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>Ip(t,i,e.rttPenaltyRequestSize))),m((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.concurrentDownloads.clear(),this.subscription.unsubscribe()}trackXHR(t){let e=0,s=g();const r=new i;switch(this.subscription.add(r),this.concurrentDownloads.add(t),t.readyState){case 4:break;case 3:case 2:r.add(a(t,'progress').pipe(b()).subscribe((t=>{e=t.loaded,s=g()})));break;case 1:case 0:r.add(a(t,'loadstart').subscribe((()=>{e=0,s=g()})))}r.add(a(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,r=g(),a=t-e,n=r-s;this.addRawSpeed(a,n,1)}this.concurrentDownloads.delete(t),r.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=g();let r=0,a=g();const n=i=>{this.concurrentDownloads.delete(t),e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=({done:d,value:u})=>Id(this,void 0,void 0,(function*(){d?(this.addRawSpeed(i,g()-s,1),this.concurrentDownloads.delete(t)):u&&(i+=u.byteLength,r+=u.byteLength,r>=this.tuningConfig.streamMinSampleSize&&g()-a>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,g()-a,this.concurrentDownloads.size),r=0,a=g()),yield null==e?void 0:e.read().then(o,n))}));this.concurrentDownloads.add(t),null==e||e.read().then(o,n)}addRawSpeed(t,e,i=1){if(Lp.sanityCheck(t,e)){const s=8*t/e;this.throughput.next(s*i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){var e;const i=(t=>{var e,i;switch(kp){case wp.LOCAL_STORAGE:return null!==(e=localStorage.getItem(t))&&void 0!==e?e:void 0;case wp.SESSION_STORAGE:return null!==(i=sessionStorage.getItem(t))&&void 0!==i?i:void 0;case wp.RUNTIME:return $p.get(t);default:n(kp)}})(t);if(s(i))return null!==(e=parseInt(i,10))&&void 0!==e?e:void 0}}const Cp={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.05,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300,deviationDepth:10,deviationFactor:.5},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!0,minBufferToSwitchUp:.3,considerPlaybackRate:!1,trackCooldown:3e3},dash:{forwardBufferTarget:6e4,forwardBufferTargetAuto:6e4,forwardBufferTargetManual:3e5,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3,enableSubSegmentBufferFeeding:!0,segmentTimelineTolerance:100,useFetchPriorityHints:!0},live:{minBuffer:3e3,minBufferSegments:3,lowLatencyMinBuffer:1e3,lowLatencyMinBufferSegments:1},downloadBackoff:{bufferThreshold:100,start:100,factor:2,max:3e3,random:.1},enableTelemetryAtStart:!1,formatsToAvoid:[D.DASH_WEBM,D.DASH_SEP,D.DASH_SEP_VK],disableChromecast:!1,chromecastReceiverId:void 0,useWebmBigRequest:!0,bigRequestMinInitSize:51200,bigRequestMinDataSize:1048576,stripRangeHeader:!0,flushShortLoopedBuffers:!0,insufficientBufferRuleMargin:1e4,dashSeekInSegmentDurationThreshold:18e4,dashSeekInSegmentAlwaysSeekDelta:1e4,endGapTolerance:300,stallIgnoreThreshold:33,gapWatchdogInterval:50,requestQuick:!1};const xp=(t=(t=>t))=>({playbackState:e,seekState:s,playbackAbort$:a,looped$:n,position$:d})=>new S((h=>{let c;const l=e.transitionEnded$.pipe(m((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),p=e.stateChangeEnded$.pipe(m((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),f=s.stateChangeEnded$.pipe(m((({to:t})=>{var i,s;return t.state===C.Requested&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===P.PLAYING}))),v=s.stateChangeEnded$.pipe(m((({from:t,to:i})=>{var s,r;return t.state===C.Applying&&i.state===C.None&&(null!==(r=null===(s=e.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:e.getState())===P.PLAYING}))),g=o(l,v).pipe(u((()=>t(d.getValue())))),S=o(o(p,f,a).pipe(u((()=>t(d.getValue())))),n.pipe(u(t)));return(new i).add(g.subscribe((e=>{c=t(e)}))).add(S.subscribe((e=>{const i=t(e);if(r(c)||c===i)return;const s={from:c,to:i};c=void 0,h.next(s)})))})),Op=xp((t=>t)),Np=xp((t=>Math.round(1e3*t)+Date.now())),Bp={[_.SCREEN]:{vod:[D.HLS,D.HLS_ONDEMAND,D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS_JS,D.MPEG],live:[D.HLS_LIVE,D.DASH_LIVE,D.DASH_LIVE_WEBM]},[_.CHROMECAST]:{vod:[D.DASH_WEBM_VK,D.DASH_WEBM,D.DASH_SEP_VK,D.DASH_SEP,D.DASH_ONDEMAND,D.DASH_ONDEMAND_VK,D.HLS,D.HLS_ONDEMAND,D.MPEG],live:[D.HLS_LIVE]}};class Mp{constructor(s={}){if(this.subscription=new i,this.logger=new k,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Dd(P.STOPPED),seekState:new Dd({state:C.None}),volume:new Dd({volume:1,muted:!1}),videoTrack:new Dd(void 0),autoVideoTrackSwitching:new Dd(!0),autoVideoTrackLimits:new Dd({}),isLooped:new Dd(!1),externalTextTracks:new Dd([]),currentTextTrack:new Dd(void 0),textTrackCuesSettings:new Dd({})},this.info={playbackState$:new t(P.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentBuffer$:new t({start:0,end:0}),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(R.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)},this.events={inited$:new e,started$:new e,startAttempt$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,canplay$:new e,log$:new e},this.experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:dc},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Cp)){const s=Cp[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?Object.assign(Object.assign({},s),r):null!=r?r:s}return e})(s),this.chromecastInitializer=new x({receiverApplicationId:s.chromecastReceiverId,isDisabled:s.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Lp(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),r=`Player.${String(e)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(t){var e,i;return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=null===(e=t.meta)||void 0===e?void 0:e.videoId,this.providerContainer=new yp({screenFormatsPriority:[...Bp[_.SCREEN].live,...Bp[_.SCREEN].vod],chromecastFormatsPriority:[...Bp[_.CHROMECAST].live,...Bp[_.CHROMECAST].vod],sources:t.sources,meta:null!==(i=t.meta)&&void 0!==i?i:{},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.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:C.Requested,position:1e3*t,forcePrecise:e}),this}seekPercent(t){const e=this.info.duration$.getValue();return isFinite(e)&&this.seekTime(Math.abs(e)*t),this}setVolume(t){return this.chromecastInitializer.castState$.getValue()===R.CONNECTED?this.chromecastInitializer.setVolume(t):this.desiredState.volume.startTransitionTo({volume:t,muted:this.desiredState.volume.getState().muted}),this}setMuted(t){return this.chromecastInitializer.castState$.getValue()===R.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){l(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>Object.assign({type:'external'},t)))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){l(this.providerContainer);const t=this.providerContainer.providerOutput.element$.getValue();if(r(t))return this.info.position$.getValue();const e=this.desiredState.seekState.getState(),i=e.state===C.None?void 0:e.position;return s(i)?i/1e3:t.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(o(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(u((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.autoQualityLimits$));const t=new i;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(m((t=>t.to===P.PLAYING)),m((()=>!this.isPlaybackStarted))).subscribe((()=>{this.initedAt=g(),this.events.inited$.next(),t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(m((t=>t.to===P.PLAYING||t.to===P.PAUSED)),p(0),b()).subscribe((t=>{const e=t.to===P.PLAYING,i=this.info.muted$.getValue(),s=e?i?I.SuccessWithoutSound:I.SuccessWithSound:I.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(m((t=>t.to===P.PLAYING))).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case P.PAUSED:this.events.willPause$.next();break;case P.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===C.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},t),{state:C.Applying})):this.events.managedError$.next({id:`WillSeekIn${t.state}`,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===C.Applying&&(this.desiredState.seekState.setState({state:C.None}),this.events.seeked$.next())}))).add(e.current$.pipe(u((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(u((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(u((t=>t.map((({quality:t})=>t)).sort(((t,e)=>Pd(t)?1:Pd(e)?-1:wd(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).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(u((t=>t?{start:t.from,end:t.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(u((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(u((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekState:t,position$:e})=>o(t.stateChangeEnded$.pipe(u((({to:t})=>{var e;return t.state===C.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),m(s)),e.pipe(m((()=>t.getState().state===C.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(v(!0)),e.providerOutput.seekedEvent$.pipe(v(!1))).pipe(c()).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(u((t=>({id:'NoProviders',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(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.pipe(b(),u((()=>g()-this.initedAt))).subscribe(this.events.firstFrame$)).add(e.providerOutput.canplay$.pipe(b(),u((()=>g()-this.initedAt))).subscribe(this.events.canplay$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const r=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>r.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>r.next(!0))));const n=new t(!0);this.subscription.add(e.current$.subscribe((()=>n.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(m((({to:t})=>t===P.PLAYING)),b()).subscribe((()=>n.next(!1))));let d=0;const h=o(e.providerOutput.isBuffering$,r,n).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=r.getValue()||n.getValue();return t&&!i})),c());this.subscription.add(h.subscribe((t=>{t?d=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(d),this.info.isStalled$.next(!1))})));const p=new i;this.subscription.add(p);const f=o(a(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(m((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),p.unsubscribe(),t){case!0:p.add(Np({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:f,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageLive$));break;case!1:p.add(Op({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:f,position$:this.providerContainer.providerOutput.position$}).pipe(u((({from:t,to:e})=>({start:t,end:e})))).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(u((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(m((t=>t.length>0)),b()).subscribe((t=>{this.setStartingVideoTrack(t)})))})))}setStartingVideoTrack(t){let e;this.explicitInitialQuality&&(e=t.find((({quality:t})=>t===this.explicitInitialQuality)),this.explicitInitialQuality=void 0),e||(e=pc(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(o(this.desiredState.videoTrack.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(u((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;const e=null===(t=this.providerContainer)||void 0===t?void 0:t.providerOutput;l(this.providerContainer),l(e),oc={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{nc=t})),this.providerContainer.current$.subscribe((({type:t})=>uc('provider',t))),e.duration$.subscribe((t=>uc('duration',t))),e.availableVideoTracks$.pipe(m((t=>!!t.length)),b()).subscribe((t=>uc('tracks',t))),this.events.fatalError$.subscribe(new hc('fatalError')),this.events.managedError$.subscribe(new hc('managedError')),e.position$.subscribe(new hc('position')),e.currentVideoTrack$.pipe(u((t=>null==t?void 0:t.quality))).subscribe(new hc('quality')),this.info.currentBuffer$.subscribe(new hc('buffer')),e.isBuffering$.subscribe(new hc('isBuffering'))].forEach((t=>this.subscription.add(t))),uc('codecs',Object.keys(op).filter((t=>op[t])))}}const Up='@vkontakte/videoplayer-core@2.0.67';export{R as ChromecastState,L as HttpConnectionType,P as PlaybackState,Mp as Player,Up as SDK_VERSION,I as StartStatus,D as VideoFormat,bd as VideoQuality};