@vkontakte/videoplayer-core 2.0.60 → 2.0.61
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/es2015.cjs.js +4 -4
- package/es2015.esm.js +4 -4
- package/es2018.cjs.js +4 -4
- package/es2018.esm.js +4 -4
- package/esnext.cjs.js +4 -4
- package/esnext.esm.js +4 -4
- package/package.json +1 -1
- package/packages/sdk/src/providers/DashIFProvider/dashjsTypes.d.ts +8 -2
- package/packages/sdk/src/providers/DashVKProvider/lib/sourceBufferTaskQueue.d.ts +1 -0
- package/providers/DashIFProvider/observableManifestLoader.d.ts +3 -0
- package/providers/ProviderContainer/utils/playbackHangup.d.ts +1 -1
- package/utils/buffer/isPositionBuffered.d.ts +3 -0
package/es2015.cjs.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* @vkontakte/videoplayer-core v2.0.
|
|
3
|
-
*
|
|
4
|
-
* https://st.mycdn.me/static/playersdk/2-0-
|
|
2
|
+
* @vkontakte/videoplayer-core v2.0.61
|
|
3
|
+
* Mon, 08 Aug 2022 13:15:46 GMT
|
|
4
|
+
* https://st.mycdn.me/static/playersdk/2-0-61/doc/
|
|
5
5
|
*/
|
|
6
|
-
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2015.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce'));var r,a,n,o,u,d,l;exports.PlaybackState=void 0,(r=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',r.PLAYING='playing',r.PAUSED='paused',exports.VideoFormat=void 0,(a=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',a.DASH='DASH',a.DASH_SEP='DASH_SEP',a.DASH_SEP_VK='DASH_SEP_VK',a.DASH_WEBM='DASH_WEBM',a.DASH_WEBM_VK='DASH_WEBM_VK',a.DASH_ONDEMAND='DASH_ONDEMAND',a.DASH_LIVE='DASH_LIVE',a.DASH_LIVE_WEBM='DASH_LIVE_WEBM',a.HLS='HLS',a.HLS_ONDEMAND='HLS_ONDEMAND',a.HLS_JS='HLS_JS',a.HLS_LIVE='HLS_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(n||(n={})),exports.ChromecastState=void 0,(o=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',o.AVAILABLE='AVAILABLE',o.CONNECTING='CONNECTING',o.CONNECTED='CONNECTED',exports.StartStatus=void 0,(u=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',u.SuccessWithoutSound='success_without_sound',u.Failed='failed',exports.HttpConnectionType=void 0,(d=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',d.HTTP2='http2',d.QUIC='quic',function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(l||(l={}));class c{constructor(e){var i;this.connection$=new t.ValueSubject(void 0),this.castState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new t.Subject,this.realCastState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const s='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;var r;t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(r='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',r),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(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,r;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(r=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===r?void 0:r.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 t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(h),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{var a;const n=r===exports.ChromecastState.CONNECTED,o=t.isNonNullable(this.connection$.getValue());if(n&&!o){const r=s.getCurrentSession();t.assertNonNullable(r);const n=r.getCastDevice(),o=null===(a=r.getMediaSession())||void 0===a?void 0:a.media.contentId;(t.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:r,castDevice:n}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)})))}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 h=e=>{switch(e){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return t.assertNever(e)}};var p='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},m=function(t){return t&&t.Math==Math&&t},f=m('object'==typeof globalThis&&globalThis)||m('object'==typeof window&&window)||m('object'==typeof self&&self)||m('object'==typeof p&&p)||function(){return this}()||Function('return this')(),v=function(t){try{return!!t()}catch(t){return!0}},S=!v((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),b=S,g=Function.prototype,y=g.apply,T=g.call,E='object'==typeof Reflect&&Reflect.apply||(b?T.bind(y):function(){return T.apply(y,arguments)}),k=S,w=Function.prototype,P=w.bind,$=w.call,A=k&&P.bind($,$),x=k?function(t){return t&&A(t)}:function(t){return t&&function(){return $.apply(t,arguments)}},N=function(t){return'function'==typeof t},D={},_=!v((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),R=S,I=Function.prototype.call,C=R?I.bind(I):function(){return I.apply(I,arguments)},L={},O={}.propertyIsEnumerable,B=Object.getOwnPropertyDescriptor,M=B&&!O.call({1:2},1);L.f=M?function(t){var e=B(this,t);return!!e&&e.enumerable}:O;var V,F,U=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},q=x,j=q({}.toString),H=q(''.slice),G=function(t){return H(j(t),8,-1)},Y=x,Q=v,z=G,W=f.Object,J=Y(''.split),K=Q((function(){return!W('z').propertyIsEnumerable(0)}))?function(t){return'String'==z(t)?J(t,''):W(t)}:W,X=f.TypeError,Z=function(t){if(null==t)throw X('Can\'t call method on '+t);return t},tt=K,et=Z,it=function(t){return tt(et(t))},st=N,rt=function(t){return'object'==typeof t?null!==t:st(t)},at={},nt=at,ot=f,ut=N,dt=function(t){return ut(t)?t:void 0},lt=function(t,e){return arguments.length<2?dt(nt[t])||dt(ot[t]):nt[t]&&nt[t][e]||ot[t]&&ot[t][e]},ct=x({}.isPrototypeOf),ht=lt('navigator','userAgent')||'',pt=f,mt=ht,ft=pt.process,vt=pt.Deno,St=ft&&ft.versions||vt&&vt.version,bt=St&&St.v8;bt&&(F=(V=bt.split('.'))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!F&&mt&&(!(V=mt.match(/Edge\/(\d+)/))||V[1]>=74)&&(V=mt.match(/Chrome\/(\d+)/))&&(F=+V[1]);var gt=F,yt=gt,Tt=v,Et=!!Object.getOwnPropertySymbols&&!Tt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&yt&&yt<41})),kt=Et&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,wt=lt,Pt=N,$t=ct,At=kt,xt=f.Object,Nt=At?function(t){return'symbol'==typeof t}:function(t){var e=wt('Symbol');return Pt(e)&&$t(e.prototype,xt(t))},Dt=f.String,_t=function(t){try{return Dt(t)}catch(t){return'Object'}},Rt=N,It=_t,Ct=f.TypeError,Lt=function(t){if(Rt(t))return t;throw Ct(It(t)+' is not a function')},Ot=Lt,Bt=function(t,e){var i=t[e];return null==i?void 0:Ot(i)},Mt=C,Vt=N,Ft=rt,Ut=f.TypeError,qt={exports:{}},jt=f,Ht=Object.defineProperty,Gt=function(t,e){try{Ht(jt,t,{value:e,configurable:!0,writable:!0})}catch(i){jt[t]=e}return e},Yt=f['__core-js_shared__']||Gt('__core-js_shared__',{}),Qt=Yt;(qt.exports=function(t,e){return Qt[t]||(Qt[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 zt=Z,Wt=f.Object,Jt=function(t){return Wt(zt(t))},Kt=Jt,Xt=x({}.hasOwnProperty),Zt=Object.hasOwn||function(t,e){return Xt(Kt(t),e)},te=x,ee=0,ie=Math.random(),se=te(1..toString),re=function(t){return'Symbol('+(void 0===t?'':t)+')_'+se(++ee+ie,36)},ae=f,ne=qt.exports,oe=Zt,ue=re,de=Et,le=kt,ce=ne('wks'),he=ae.Symbol,pe=he&&he.for,me=le?he:he&&he.withoutSetter||ue,fe=function(t){if(!oe(ce,t)||!de&&'string'!=typeof ce[t]){var e='Symbol.'+t;de&&oe(he,t)?ce[t]=he[t]:ce[t]=le&&pe?pe(e):me(e)}return ce[t]},ve=C,Se=rt,be=Nt,ge=Bt,ye=function(t,e){var i,s;if('string'===e&&Vt(i=t.toString)&&!Ft(s=Mt(i,t)))return s;if(Vt(i=t.valueOf)&&!Ft(s=Mt(i,t)))return s;if('string'!==e&&Vt(i=t.toString)&&!Ft(s=Mt(i,t)))return s;throw Ut('Can\'t convert object to primitive value')},Te=fe,Ee=f.TypeError,ke=Te('toPrimitive'),we=function(t,e){if(!Se(t)||be(t))return t;var i,s=ge(t,ke);if(s){if(void 0===e&&(e='default'),i=ve(s,t,e),!Se(i)||be(i))return i;throw Ee('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),ye(t,e)},Pe=Nt,$e=function(t){var e=we(t,'string');return Pe(e)?e:e+''},Ae=rt,xe=f.document,Ne=Ae(xe)&&Ae(xe.createElement),De=function(t){return Ne?xe.createElement(t):{}},_e=De,Re=!_&&!v((function(){return 7!=Object.defineProperty(_e('div'),'a',{get:function(){return 7}}).a})),Ie=_,Ce=C,Le=L,Oe=U,Be=it,Me=$e,Ve=Zt,Fe=Re,Ue=Object.getOwnPropertyDescriptor;D.f=Ie?Ue:function(t,e){if(t=Be(t),e=Me(e),Fe)try{return Ue(t,e)}catch(t){}if(Ve(t,e))return Oe(!Ce(Le.f,t,e),t[e])};var qe=v,je=N,He=/#|\.prototype\./,Ge=function(t,e){var i=Qe[Ye(t)];return i==We||i!=ze&&(je(e)?qe(e):!!e)},Ye=Ge.normalize=function(t){return String(t).replace(He,'.').toLowerCase()},Qe=Ge.data={},ze=Ge.NATIVE='N',We=Ge.POLYFILL='P',Je=Ge,Ke=Lt,Xe=S,Ze=x(x.bind),ti=function(t,e){return Ke(t),void 0===e?t:Xe?Ze(t,e):function(){return t.apply(e,arguments)}},ei={},ii=_&&v((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),si=f,ri=rt,ai=si.String,ni=si.TypeError,oi=function(t){if(ri(t))return t;throw ni(ai(t)+' is not an object')},ui=_,di=Re,li=ii,ci=oi,hi=$e,pi=f.TypeError,mi=Object.defineProperty,fi=Object.getOwnPropertyDescriptor;ei.f=ui?li?function(t,e,i){if(ci(t),e=hi(e),ci(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=fi(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 mi(t,e,i)}:mi:function(t,e,i){if(ci(t),e=hi(e),ci(i),di)try{return mi(t,e,i)}catch(t){}if('get'in i||'set'in i)throw pi('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var vi=ei,Si=U,bi=_?function(t,e,i){return vi.f(t,e,Si(1,i))}:function(t,e,i){return t[e]=i,t},gi=f,yi=E,Ti=x,Ei=N,ki=D.f,wi=Je,Pi=at,$i=ti,Ai=bi,xi=Zt,Ni=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 yi(t,this,arguments)};return e.prototype=t.prototype,e},Di=function(t,e){var i,s,r,a,n,o,u,d,l=t.target,c=t.global,h=t.stat,p=t.proto,m=c?gi:h?gi[l]:(gi[l]||{}).prototype,f=c?Pi:Pi[l]||Ai(Pi,l,{})[l],v=f.prototype;for(r in e)i=!wi(c?r:l+(h?'.':'#')+r,t.forced)&&m&&xi(m,r),n=f[r],i&&(o=t.noTargetGet?(d=ki(m,r))&&d.value:m[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(u=t.bind&&i?$i(a,gi):t.wrap&&i?Ni(a):p&&Ei(a)?Ti(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Ai(u,'sham',!0),Ai(f,r,u),p&&(xi(Pi,s=l+'Prototype')||Ai(Pi,s,{}),Ai(Pi[s],r,a),t.real&&v&&!v[r]&&Ai(v,r,a)))},_i=f.Promise,Ri=bi,Ii=function(t,e,i,s){s&&s.enumerable?t[e]=i:Ri(t,e,i)},Ci=Ii,Li=f,Oi=(Li.String,Li.TypeError,x);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Oi(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Bi={};Bi[fe('toStringTag')]='z';var Mi='[object z]'===String(Bi),Vi=f,Fi=Mi,Ui=N,qi=G,ji=fe('toStringTag'),Hi=Vi.Object,Gi='Arguments'==qi(function(){return arguments}()),Yi=Fi?qi: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=Hi(t),ji))?i:Gi?qi(e):'Object'==(s=qi(e))&&Ui(e.callee)?'Arguments':s},Qi=Yi,zi=Mi?{}.toString:function(){return'[object '+Qi(this)+']'},Wi=Mi,Ji=ei.f,Ki=bi,Xi=Zt,Zi=zi,ts=fe('toStringTag'),es=function(t,e,i,s){if(t){var r=i?t:t.prototype;Xi(r,ts)||Ji(r,ts,{configurable:!0,value:e}),s&&!Wi&&Ki(r,'toString',Zi)}},is=lt,ss=ei,rs=_,as=fe('species'),ns=ct,os=f.TypeError,us=N,ds=Yt,ls=x(Function.toString);us(ds.inspectSource)||(ds.inspectSource=function(t){return ls(t)});var cs=ds.inspectSource,hs={},ps=hs,ms=fe('iterator'),fs=Array.prototype,vs=Math.ceil,Ss=Math.floor,bs=function(t){var e=+t;return e!=e||0===e?0:(e>0?Ss:vs)(e)},gs=bs,ys=Math.min,Ts=function(t){return t>0?ys(gs(t),9007199254740991):0},Es=function(t){return Ts(t.length)},ks=Yi,ws=Bt,Ps=hs,$s=fe('iterator'),As=function(t){if(null!=t)return ws(t,$s)||ws(t,'@@iterator')||Ps[ks(t)]},xs=C,Ns=Lt,Ds=oi,_s=_t,Rs=As,Is=f.TypeError,Cs=C,Ls=oi,Os=Bt,Bs=ti,Ms=C,Vs=oi,Fs=_t,Us=function(t){return void 0!==t&&(ps.Array===t||fs[ms]===t)},qs=Es,js=ct,Hs=function(t,e){var i=arguments.length<2?Rs(t):e;if(Ns(i))return Ds(xs(i,t));throw Is(_s(t)+' is not iterable')},Gs=As,Ys=function(t,e,i){var s,r;Ls(t);try{if(!(s=Os(t,'return'))){if('throw'===e)throw i;return i}s=Cs(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return Ls(s),i},Qs=f.TypeError,zs=function(t,e){this.stopped=t,this.result=e},Ws=zs.prototype,Js=function(t,e,i){var s,r,a,n,o,u,d,l=i&&i.that,c=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),m=Bs(e,l),f=function(t){return s&&Ys(s,'normal',t),new zs(!0,t)},v=function(t){return c?(Vs(t),p?m(t[0],t[1],f):m(t[0],t[1])):p?m(t,f):m(t)};if(h)s=t;else{if(!(r=Gs(t)))throw Qs(Fs(t)+' is not iterable');if(Us(r)){for(a=0,n=qs(t);n>a;a++)if((o=v(t[a]))&&js(Ws,o))return o;return new zs(!1)}s=Hs(t,r)}for(u=s.next;!(d=Ms(u,s)).done;){try{o=v(d.value)}catch(t){Ys(s,'throw',t)}if('object'==typeof o&&o&&js(Ws,o))return o}return new zs(!1)},Ks=fe('iterator'),Xs=!1;try{var Zs=0,tr={next:function(){return{done:!!Zs++}},return:function(){Xs=!0}};tr[Ks]=function(){return this},Array.from(tr,(function(){throw 2}))}catch(t){}var er=x,ir=v,sr=N,rr=Yi,ar=cs,nr=function(){},or=[],ur=lt('Reflect','construct'),dr=/^\s*(?:class|function)\b/,lr=er(dr.exec),cr=!dr.exec(nr),hr=function(t){if(!sr(t))return!1;try{return ur(nr,or,t),!0}catch(t){return!1}},pr=function(t){if(!sr(t))return!1;switch(rr(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return cr||!!lr(dr,ar(t))}catch(t){return!0}};pr.sham=!0;var mr,fr,vr,Sr,br=!ur||ir((function(){var t;return hr(hr.call)||!hr(Object)||!hr((function(){t=!0}))||t}))?pr:hr,gr=_t,yr=f.TypeError,Tr=oi,Er=function(t){if(br(t))return t;throw yr(gr(t)+' is not a constructor')},kr=fe('species'),wr=function(t,e){var i,s=Tr(t).constructor;return void 0===s||null==(i=Tr(s)[kr])?e:Er(i)},Pr=lt('document','documentElement'),$r=x([].slice),Ar=f.TypeError,xr=/(?:ipad|iphone|ipod).*applewebkit/i.test(ht),Nr='process'==G(f.process),Dr=f,_r=E,Rr=ti,Ir=N,Cr=Zt,Lr=v,Or=Pr,Br=$r,Mr=De,Vr=function(t,e){if(t<e)throw Ar('Not enough arguments');return t},Fr=xr,Ur=Nr,qr=Dr.setImmediate,jr=Dr.clearImmediate,Hr=Dr.process,Gr=Dr.Dispatch,Yr=Dr.Function,Qr=Dr.MessageChannel,zr=Dr.String,Wr=0,Jr={};try{mr=Dr.location}catch(t){}var Kr=function(t){if(Cr(Jr,t)){var e=Jr[t];delete Jr[t],e()}},Xr=function(t){return function(){Kr(t)}},Zr=function(t){Kr(t.data)},ta=function(t){Dr.postMessage(zr(t),mr.protocol+'//'+mr.host)};qr&&jr||(qr=function(t){Vr(arguments.length,1);var e=Ir(t)?t:Yr(t),i=Br(arguments,1);return Jr[++Wr]=function(){_r(e,void 0,i)},fr(Wr),Wr},jr=function(t){delete Jr[t]},Ur?fr=function(t){Hr.nextTick(Xr(t))}:Gr&&Gr.now?fr=function(t){Gr.now(Xr(t))}:Qr&&!Fr?(Sr=(vr=new Qr).port2,vr.port1.onmessage=Zr,fr=Rr(Sr.postMessage,Sr)):Dr.addEventListener&&Ir(Dr.postMessage)&&!Dr.importScripts&&mr&&'file:'!==mr.protocol&&!Lr(ta)?(fr=ta,Dr.addEventListener('message',Zr,!1)):fr='onreadystatechange'in Mr('script')?function(t){Or.appendChild(Mr('script')).onreadystatechange=function(){Or.removeChild(this),Kr(t)}}:function(t){setTimeout(Xr(t),0)});var ea,ia,sa,ra,aa,na,oa,ua,da={set:qr,clear:jr},la=f,ca=/ipad|iphone|ipod/i.test(ht)&&void 0!==la.Pebble,ha=/web0s(?!.*chrome)/i.test(ht),pa=f,ma=ti,fa=D.f,va=da.set,Sa=xr,ba=ca,ga=ha,ya=Nr,Ta=pa.MutationObserver||pa.WebKitMutationObserver,Ea=pa.document,ka=pa.process,wa=pa.Promise,Pa=fa(pa,'queueMicrotask'),$a=Pa&&Pa.value;$a||(ea=function(){var t,e;for(ya&&(t=ka.domain)&&t.exit();ia;){e=ia.fn,ia=ia.next;try{e()}catch(t){throw ia?ra():sa=void 0,t}}sa=void 0,t&&t.enter()},Sa||ya||ga||!Ta||!Ea?!ba&&wa&&wa.resolve?((oa=wa.resolve(void 0)).constructor=wa,ua=ma(oa.then,oa),ra=function(){ua(ea)}):ya?ra=function(){ka.nextTick(ea)}:(va=ma(va,pa),ra=function(){va(ea)}):(aa=!0,na=Ea.createTextNode(''),new Ta(ea).observe(na,{characterData:!0}),ra=function(){na.data=aa=!aa}));var Aa=$a||function(t){var e={fn:t,next:void 0};sa&&(sa.next=e),ia||(ia=e,ra()),sa=e},xa={},Na=Lt,Da=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=Na(e),this.reject=Na(i)};xa.f=function(t){return new Da(t)};var _a=oi,Ra=rt,Ia=xa,Ca=function(t,e){if(_a(t),Ra(e)&&e.constructor===t)return e;var i=Ia.f(t);return(0,i.resolve)(e),i.promise},La=f,Oa=function(){this.head=null,this.tail=null};Oa.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 Ba,Ma,Va,Fa=Oa,Ua=N,qa=cs,ja=f.WeakMap,Ha=Ua(ja)&&/native code/.test(qa(ja)),Ga=qt.exports,Ya=re,Qa=Ga('keys'),za=function(t){return Qa[t]||(Qa[t]=Ya(t))},Wa={},Ja=Ha,Ka=f,Xa=x,Za=rt,tn=bi,en=Zt,sn=Yt,rn=za,an=Wa,nn=Ka.TypeError,on=Ka.WeakMap;if(Ja||sn.state){var un=sn.state||(sn.state=new on),dn=Xa(un.get),ln=Xa(un.has),cn=Xa(un.set);Ba=function(t,e){if(ln(un,t))throw new nn('Object already initialized');return e.facade=t,cn(un,t,e),e},Ma=function(t){return dn(un,t)||{}},Va=function(t){return ln(un,t)}}else{var hn=rn('state');an[hn]=!0,Ba=function(t,e){if(en(t,hn))throw new nn('Object already initialized');return e.facade=t,tn(t,hn,e),e},Ma=function(t){return en(t,hn)?t[hn]:{}},Va=function(t){return en(t,hn)}}var pn,mn,fn,vn={set:Ba,get:Ma,has:Va,enforce:function(t){return Va(t)?Ma(t):Ba(t,{})},getterFor:function(t){return function(e){var i;if(!Za(e)||(i=Ma(e)).type!==t)throw nn('Incompatible receiver, '+t+' required');return i}}},Sn='object'==typeof window,bn=Di,gn=f,yn=lt,Tn=C,En=_i,kn=function(t,e,i){for(var s in e)i&&i.unsafe&&t[s]?t[s]=e[s]:Ci(t,s,e[s],i);return t},wn=es,Pn=function(t){var e=is(t),i=ss.f;rs&&e&&!e[as]&&i(e,as,{configurable:!0,get:function(){return this}})},$n=Lt,An=N,xn=rt,Nn=function(t,e){if(ns(e,t))return t;throw os('Incorrect invocation')},Dn=cs,_n=Js,Rn=function(t,e){if(!e&&!Xs)return!1;var i=!1;try{var s={};s[Ks]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i},In=wr,Cn=da.set,Ln=Aa,On=Ca,Bn=function(t,e){var i=La.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},Mn=xa,Vn=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},Fn=Fa,Un=vn,qn=Je,jn=Sn,Hn=Nr,Gn=gt,Yn=fe('species'),Qn='Promise',zn=Un.getterFor(Qn),Wn=Un.set,Jn=Un.getterFor(Qn),Kn=En&&En.prototype,Xn=En,Zn=Kn,to=gn.TypeError,eo=gn.document,io=gn.process,so=Mn.f,ro=so,ao=!!(eo&&eo.createEvent&&gn.dispatchEvent),no=An(gn.PromiseRejectionEvent),oo=qn(Qn,(function(){var t=Dn(Xn),e=t!==String(Xn);if(!e&&66===Gn)return!0;if(!Zn.finally)return!0;if(Gn>=51&&/native code/.test(t))return!1;var i=new Xn((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};return(i.constructor={})[Yn]=s,!(i.then((function(){}))instanceof s)||!e&&jn&&!no})),uo=oo||!Rn((function(t){Xn.all(t).catch((function(){}))})),lo=function(t){var e;return!(!xn(t)||!An(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,u=t.resolve,d=t.reject,l=t.domain;try{o?(n||(2===e.rejection&&vo(e),e.rejection=1),!0===o?i=a:(l&&l.enter(),i=o(a),l&&(l.exit(),r=!0)),i===t.promise?d(to('Promise-chain cycle')):(s=lo(i))?Tn(s,i,u,d):u(i)):d(a)}catch(t){l&&!r&&l.exit(),d(t)}},ho=function(t,e){t.notified||(t.notified=!0,Ln((function(){for(var i,s=t.reactions;i=s.get();)co(i,t);t.notified=!1,e&&!t.rejection&&mo(t)})))},po=function(t,e,i){var s,r;ao?((s=eo.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),gn.dispatchEvent(s)):s={promise:e,reason:i},!no&&(r=gn['on'+t])?r(s):'unhandledrejection'===t&&Bn('Unhandled promise rejection',i)},mo=function(t){Tn(Cn,gn,(function(){var e,i=t.facade,s=t.value;if(fo(t)&&(e=Vn((function(){Hn?io.emit('unhandledRejection',s,i):po('unhandledrejection',i,s)})),t.rejection=Hn||fo(t)?2:1,e.error))throw e.value}))},fo=function(t){return 1!==t.rejection&&!t.parent},vo=function(t){Tn(Cn,gn,(function(){var e=t.facade;Hn?io.emit('rejectionHandled',e):po('rejectionhandled',e,t.value)}))},So=function(t,e,i){return function(s){t(e,s,i)}},bo=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,ho(t,!0))},go=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw to('Promise can\'t be resolved itself');var s=lo(e);s?Ln((function(){var i={done:!1};try{Tn(s,e,So(go,i,t),So(bo,i,t))}catch(e){bo(i,e,t)}})):(t.value=e,t.state=1,ho(t,!1))}catch(e){bo({done:!1},e,t)}}};oo&&(Zn=(Xn=function(t){Nn(this,Zn),$n(t),Tn(pn,this);var e=zn(this);try{t(So(go,e),So(bo,e))}catch(t){bo(e,t)}}).prototype,(pn=function(t){Wn(this,{type:Qn,done:!1,notified:!1,parent:!1,reactions:new Fn,rejection:!1,state:0,value:void 0})}).prototype=kn(Zn,{then:function(t,e){var i=Jn(this),s=so(In(this,Xn));return i.parent=!0,s.ok=!An(t)||t,s.fail=An(e)&&e,s.domain=Hn?io.domain:void 0,0==i.state?i.reactions.add(s):Ln((function(){co(s,i)})),s.promise},catch:function(t){return this.then(void 0,t)}}),mn=function(){var t=new pn,e=zn(t);this.promise=t,this.resolve=So(go,e),this.reject=So(bo,e)},Mn.f=so=function(t){return t===Xn||t===fn?new mn(t):ro(t)}),bn({global:!0,wrap:!0,forced:oo},{Promise:Xn}),wn(Xn,Qn,!1,!0),Pn(Qn),fn=yn(Qn),bn({target:Qn,stat:!0,forced:oo},{reject:function(t){var e=so(this);return Tn(e.reject,void 0,t),e.promise}}),bn({target:Qn,stat:!0,forced:true},{resolve:function(t){return On(this===fn?Xn:this,t)}}),bn({target:Qn,stat:!0,forced:uo},{all:function(t){var e=this,i=so(e),s=i.resolve,r=i.reject,a=Vn((function(){var i=$n(e.resolve),a=[],n=0,o=1;_n(t,(function(t){var u=n++,d=!1;o++,Tn(i,e,t).then((function(t){d||(d=!0,a[u]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise},race:function(t){var e=this,i=so(e),s=i.reject,r=Vn((function(){var r=$n(e.resolve);_n(t,(function(t){Tn(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var yo=_i,To=lt,Eo=N,ko=wr,wo=Ca;Di({target:'Promise',proto:!0,real:!0,forced:!!yo&&v((function(){yo.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=ko(this,To('Promise')),i=Eo(t);return this.then(i?function(i){return wo(e,t()).then((function(){return i}))}:t,i?function(i){return wo(e,t()).then((function(){throw i}))}:t)}});var Po,$o=lt,Ao=$o('Promise','finally');!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Po||(Po={}));var xo,No=(e,i=0,s=Po.OFFSET_P)=>{switch(s){case Po.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case Po.PLAYBACK_SHIFT:{if(0===i)return e;const t=new URL(e);return t.searchParams.append('playback_shift',i.toFixed(0)),t.toString()}default:t.assertNever(s)}return e},Do=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};exports.VideoQuality=void 0,(xo=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',xo.Q_144P='144p',xo.Q_240P='240p',xo.Q_360P='360p',xo.Q_480P='480p',xo.Q_720P='720p',xo.Q_1080P='1080p',xo.Q_1440P='1440p',xo.Q_2160P='2160p',xo.Q_4320P='4320p';const _o={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Ro=(t,e)=>_o[t].height>_o[e].height,Io=(t,e)=>_o[t].height<_o[e].height,Co=Object.keys(_o).sort(((t,e)=>Io(t,e)?-1:1)),Lo=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return Co.find((t=>{const e=_o[t];return e.width>=s&&e.height>=i}))},Oo=t=>t===exports.VideoQuality.INVARIANT;class Bo{constructor(e){this.transitionStarted$=new t.Subject,this.transitionEnded$=new t.Subject,this.transitionUpdated$=new t.Subject,this.forceChanged$=new t.Subject,this.stateChangeStarted$=t.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=t.merge(this.transitionEnded$,this.forceChanged$),this.state=e}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(e){const i=this.transition,s=this.state;s===e||t.isNonNullable(i)&&i.to===e||(this.state=e,i?(this.transition={from:i.from,to:e,canceledTransition:i},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var Mo;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Mo||(Mo={}));class Vo{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new Bo(Mo.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),s!==exports.PlaybackState.STOPPED){if(!i)if((null==r?void 0:r.to)===exports.PlaybackState.PAUSED||a.state!==l.Requested||e===Mo.STOPPED)switch(s){case exports.PlaybackState.PLAYING:switch(e){case Mo.PLAYING:break;case Mo.PAUSED:case Mo.READY:this.videoState.startTransitionTo(Mo.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Mo.STOPPED:this.videoState.startTransitionTo(Mo.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Mo.PLAYING:this.videoState.startTransitionTo(Mo.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Mo.PAUSED:break;case Mo.READY:this.videoState.startTransitionTo(Mo.PAUSED),this.videoState.setState(Mo.PAUSED);break;case Mo.STOPPED:this.videoState.startTransitionTo(Mo.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}else this.seek(a.position)}else e!==Mo.STOPPED&&(this.videoState.startTransitionTo(Mo.STOPPED),this.stop())},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next((e=>{switch(e){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(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 t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(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===l.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,r=this.params.output.isBuffering$.getValue(),a=s===chrome.cast.media.PlayerState.BUFFERING;switch(r!==a&&this.params.output.isBuffering$.next(a),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:t.assertNever(s)}})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));i(t.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(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(Mo.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(Mo.PLAYING),Do(this.params.desiredState.playbackState,exports.PlaybackState.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:l.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)!==Mo.PAUSED&&t!==Mo.PLAYING||(this.videoState.setState(Mo.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Mo.PLAYING&&t!==Mo.PAUSED||(this.videoState.setState(Mo.PLAYING),Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Mo.READY&&this.videoState.setState(Mo.READY)}handleRemoteStop(){this.videoState.getState()!==Mo.STOPPED&&this.videoState.setState(Mo.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(e){var i;const s=this.params.source;let r,a,n;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const o=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:Io(t,e)?1:-1))[0];t.assertNonNullable(o);const u=i[o];t.assertNonNullable(u),r=u,a='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),r=No(i.url),a='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.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 t.assertNever(e)}const o=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return t.isNonNullable(u)&&(o.metadata.title=u),t.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===l.Applying||i.state===l.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(e){const i=this.params.connection.session.loadMedia(e),s=new Promise(((e,i)=>{this.loadMediaTimeoutSubscription.add(t.timeout(7e3).subscribe((()=>i('timeout(7000)'))))}));Ao(Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===l.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 Fo(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{u(s.next(t))}catch(t){a(t)}}function o(t){try{u(s.throw(t))}catch(t){a(t)}}function u(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}u((s=s.apply(t,e||[])).next())}))}function Uo(t){return this instanceof Uo?(this.v=t,this):new Uo(t)}function qo(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 Uo?Promise.resolve(i.value.v).then(u,d):l(a[0][2],i)}catch(t){l(a[0][3],t)}var i}function u(t){o('next',t)}function d(t){o('throw',t)}function l(t,e){t(e),a.shift(),a.length&&o(a[0][0],a[0][1])}}class jo{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 Ho extends jo{constructor(){super(),this.listeners||jo.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 Go{constructor(){Object.defineProperty(this,'signal',{value:new Ho,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 Yo(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&&(Go.prototype[Symbol.toStringTag]='AbortController',Ho.prototype[Symbol.toStringTag]='AbortSignal');const Qo=Yo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zo=Qo?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(!Yo({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,Wo=Qo?zo.fetch:window.fetch;Qo?zo.Request:window.Request;const Jo=Qo?Go:window.AbortController,Ko=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Xo{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 Fo(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]=Ko(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(Ko),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 Jo,u=o.signal,d={url:t,from:s,to:r,loaded:0,data:null,abortController:o};u.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const l=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 Wo(n,{signal:u}).then((t=>{var e,i,a;if(!t.ok||!t.body)return void this.onBigRequestError(d);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const u=n.getReader(),c=parseInt(null!==(a=t.headers.get('Content-Length'))&&void 0!==a?a:'',10)||r-s+1;d.data=new ArrayBuffer(c);const h=new Uint8Array(d.data),p=({done:t,value:e})=>Fo(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(d):e&&(h.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),yield null==u?void 0:u.read().then(p,Xo.suppressStreamErrors).catch(l))}));null==u||u.read().then(p,Xo.suppressStreamErrors).catch(l)}),Xo.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r}){var a,n,o,u,d,l,c;if(!this.activeRequests.has(t)||!r)return;const h=null!==(a=this.dashJsRequestQueue.get(t))&&void 0!==a?a:[];for(const a of h){const{request:h}=a,[p,m]=Ko(h),f=p>=e&&m<=e+s,v=e>=p&&e+s<m,S=r.slice(p-e,Math.min(m-e+1,s));(f||v)&&(h.requestStartDate=null!==(n=h.requestStartDate)&&void 0!==n?n:new Date,h.firstByteDate=null!==(o=h.firstByteDate)&&void 0!==o?o:new Date,h.bytesLoaded=S.byteLength,h.bytesTotal=i-e),f?(h.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(u=this.dashJsRequestQueue.get(t))&&void 0!==u?u:[]).filter((t=>t!==a))),null===(d=a.success)||void 0===d||d.call(a,S,'',t),null===(l=this.dashMetrics)||void 0===l||l.addHttpRequest(h,t,200,{},[])):v&&(null===(c=a.progress)||void 0===c||c.call(a,{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 u=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of u){const[r,a]=Ko(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]=Ko(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 Zo{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(Zo.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;Zo.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const tu=(t,e)=>{const i=new Xo(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 Zo(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var eu=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)},iu=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject;let r=NaN,a=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,n=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const n=e.onload,o=e.progress;e.onload=function(...e){return(e=>{var s,r,a;if(!e.getAllResponseHeaders().includes('x-playback-duration'))return;const n=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),o=parseInt(null!==(r=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==r?r:'',10),u=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)})(this),n(...e)},e.progress=function(...t){return this.readyState>=2&&!a&&(a=!0,s.next(Date.now()-r)),o(...t)},r=Date.now(),a=!1}return n(e)}}}),!0),{playbackDuration$:i,ping$:s}},su=t=>{const e=new URL(t);return e.searchParams.append('quic','1'),e.toString()},ru=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 au=(e,i,s,{equal:r=((t,e)=>t===e),changed$:a,onError:n}={})=>{const o=e.getState(),u=i(),d=t.isNullable(a),l=new t.Subscription;return a&&l.add(a.subscribe((t=>{const i=e.getState();r(t,i)&&e.setState(t)}),n)),r(u,o)||(s(o),d&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),d&&e.setState(t.to)}),n)),l},nu=(e,i,s)=>au(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),ou=(e,i,s,r)=>au(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.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$:s,onError:r}),uu=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class du{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(au(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(au(i.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(au(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=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(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);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(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter(du.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(e){t.assertNonNullable(this.video);for(const i of this.htmlTextTracksAsArray(!0))t.isNonNullable(e)&&uu(i,e)?i.mode='showing':i.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(e){t.assertNonNullable(this.video);const i=document.createElement('track');i.setAttribute('src',e.url),i.setAttribute('id',e.id),e.label&&i.setAttribute('label',e.label),e.language&&i.setAttribute('srclang',e.language),this.externalTracks.set(e.id,e),this.video.appendChild(i)}detach(e){t.assertNonNullable(this.video);const i=Array.prototype.find.call(this.video.getElementsByTagName('track'),(t=>t.getAttribute('id')===e));i&&this.video.removeChild(i),this.externalTracks.delete(e)}}var lu=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class cu{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}}var hu=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadeddata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());class pu{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({start:i,end:s,i:e})}return this._buffer.sort((function(t,e){return t.start-e.start})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.start&&t<e.end))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.start-t.end<(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((({start:s,end: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 mu=(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{start:s,end: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{start:s,end:r}},fu=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadedmetadata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());const vu=e=>{const i=(i,s=(()=>{}))=>t.fromEvent(e,i).pipe(t.map(s)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((()=>e.readyState<3)),t.filterChanged()),r=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>mu(e.buffered,e.currentTime)))),a=t.fromEvent(e,'volumechange').pipe(t.debounce(0),t.map((()=>({muted:e.muted,volume:e.volume})))),n=t.fromEvent(e,'error').pipe(t.map((()=>{const t=e.error;return{id:t?`MediaError#${t.code}`:'HtmlVideoError',message:t?t.message:'Error event from HTML video element'}}))),o=i('timeupdate',(()=>e.currentTime)),u=new t.Subject;let d;return o.subscribe((i=>{e.loop&&t.isNonNullable(d)&&t.isNonNullable(i)&&d>=e.duration-.3&&i<=.3&&u.next(d),d=i})),{playing$:i('playing'),pause$:i('pause').pipe(t.filter((()=>!e.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:u,error$:n,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:o,durationChange$:i('durationchange',(()=>e.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:a,firstBytes$:fu(e),firstFrame$:hu(e)}},Su=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var bu=Jt,gu=Es,yu=bs;Di({target:'Array',proto:!0},{at:function(t){var e=bu(this),i=gu(e),s=yu(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var Tu=$o('Array','at');let Eu=!1,ku={};const wu=t=>{t(ku)},Pu=(t,e)=>{var i;Eu&&(ku.meta=null!==(i=ku.meta)&&void 0!==i?i:{},ku.meta[t]=e)};class $u{constructor(t){this.name=t}next(t){var e,i;if(!Eu)return;ku.series=null!==(e=ku.series)&&void 0!==e?e:{};const s=null!==(i=ku.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),ku.series[this.name]=s}}const Au=new $u('best_bitrate');class xu{constructor(){this.history={}}recordSelection(e){this.history[e.id]=t.now()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const Nu=(e,{container:i,throughput:s,tuning:r,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:l})=>{var c,h,p,m;const f=r.usePixelRatio&&null!==(c=window.devicePixelRatio)&&void 0!==c?c:1,v=r.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*f*r.containerSizeFactor,height:i.height*f*r.containerSizeFactor},S=v&&Lo(v),b=r.considerPlaybackRate&&t.isNonNullable(u)?u:1,g=e.filter((t=>!Oo(t.quality))).sort(((t,e)=>Ro(t.quality,e.quality)?-1:1)),y=null===(h=Tu(g,-1))||void 0===h?void 0:h.quality,T=null===(p=Tu(g,0))||void 0===p?void 0:p.quality,E=t.isNullable(a)||t.isNonNullable(a.min)&&t.isNonNullable(a.max)&&Io(a.max,a.min)||t.isNonNullable(a.min)&&T&&Ro(a.min,T)||t.isNonNullable(a.max)&&y&&Io(a.max,y),k=b*(w=null!=o?o:.5,P=r.bitrateFactorAtEmptyBuffer,$=r.bitrateFactorAtFullBuffer,(P-$)*Math.pow(2,-10*w)+$);var w,P,$;const A=g.filter((e=>{const i=!S||Io(e.quality,S),u=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s-n>=e.bitrate*k,l=r.lazyQualitySwitch&&t.isNonNullable(r.minBufferToSwitchUp)&&d&&!Oo(d.quality)&&(null!=o?o:0)<r.minBufferToSwitchUp&&Ro(e.quality,d.quality),c=E||(t.isNullable(a.max)||(h=e.quality,p=a.max,_o[h].height<=_o[p].height))&&(t.isNullable(a.min)||((t,e)=>_o[t].height>=_o[e].height)(e.quality,a.min));var h,p;return i&&u&&!l&&c}))[0];A&&A.bitrate&&Au.next(A.bitrate);const x=null!==(m=null!=A?A:g[Math.ceil((g.length-1)/2)])&&void 0!==m?m:e[0],N=x&&l&&l.history[x.id]&&t.now()-l.history[x.id]<=r.trackCooldown&&(!l.last||x.id!==l.last.id);if((null==x?void 0:x.id)&&l&&!N&&l.recordSelection(x),N&&(null==l?void 0:l.last)){const t=l.last;return null==l||l.recordSwitch(t),t}return null==l||l.recordSwitch(x),x};var Du=t=>new URL(t).hostname;const _u=(e,i=300)=>new t.Observable((r=>{const{width:a,height:n}=e.getBoundingClientRect();if(r.next({width:a,height:n}),!window.ResizeObserver)return;const o=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,a;i.contentBoxSize&&i.contentBoxSize[0]?(a=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,a=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(a)&&r.next({width:s,height:a})}),i));return o.observe(e),()=>o.disconnect()})),Ru={};var Iu;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Iu||(Iu={}));const Cu=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class Lu{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Iu.DOWNLOADING_LIB),this.textTracksManager=new du,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t.ValueSubject(void 0),this.maxSeekBackTime$=new t.ValueSubject(1/0),this.availableFrom$=new t.ValueSubject(void 0),this.elementSize$=new t.ValueSubject(void 0),this.liveOffset=new cu,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&e!==Iu.DOWNLOADING_LIB&&e!==Iu.STREAM_INITIALIZED)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&e!==Iu.STOPPED&&i!==exports.PlaybackState.STOPPED&&(a?this.seek(r.position-this.liveOffset.getTotalPausedTime()):this.seek(r.position)),i){case exports.PlaybackState.STOPPED:switch(e){case Iu.STOPPED:break;case Iu.PLAYING:case Iu.PAUSED:case Iu.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Iu.PLAYING:break;case Iu.PAUSED:a&&(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 Iu.READY:this.play();break;case Iu.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Iu.PLAYING:this.pause(),this.liveOffset.pause();break;case Iu.PAUSED:break;case Iu.READY:this.videoState.setState(Iu.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Iu.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=lu(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Du(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},s=window.setTimeout((()=>e('timeout')),5e3);Ao(Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((e=>{t||(Ru.MediaPlayer=e.MediaPlayer,Ru.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(Ru.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(Ru.Debug,'dashjs not loaded'),this.player=Ru.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?Su(t.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=tu(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&&ru(this.player),eu(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:su})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Iu.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:t})},r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(_u(this.video),this.elementSize$),r(Cu(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),r(Cu(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const a=Cu(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));a.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===Iu.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(au(i.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}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:a.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(au(i.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:s})),r(Cu(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),r(Cu(this.player,'fragmentLoadingStarted').pipe(t.map((t=>Du(t.request.url)))),e.hostname$),r(Cu(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),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=Lo(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===r&&(a=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&e.currentVideoTrack$.next(a),this.videoState.setState(Iu.STREAM_INITIALIZED),this.videoState.startTransitionTo(Iu.READY)})),r(Cu(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)})),r(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=Nu(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),r(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const n=Cu(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));r(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:n}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(n.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),r(Cu(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),r(Cu(this.player,'playbackEnded'),e.endedEvent$),r(Cu(this.player,'playbackProgress').pipe(t.map((()=>mu(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),r(Cu(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Iu.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)})),r(Cu(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Iu.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(Cu(this.player,'playbackPaused'),(()=>{this.videoState.setState(Iu.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)})),r(Cu(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Iu.READY&&this.videoState.setState(Iu.READY)})),r(this.isLive$,e.isLive$),r(_u(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:o,ping$:u}=iu(this.player);r(o,this.maxSeekBackTime$),r(u.pipe(t.once()),e.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&r(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),r(n.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(Cu(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{const i=Date.now();this.subscription.add(Cu(this.player,'playbackPlaying').pipe(t.once()).subscribe((()=>e.firstFrameEvent$.next(Date.now()-i)),s))}),s)),this.subscription.add(nu(this.video,i.isLooped,s));const{volumeState$:d,looped$:l}=vu(this.video);this.subscription.add(ou(this.video,i.volume,d,s)),this.subscription.add(d.subscribe(e.volume$,s)),this.subscription.add(l.subscribe(e.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(Iu.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Iu.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=No(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Po.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Iu.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Iu.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 Ou=t=>{switch(t){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}},Bu=t=>Fo(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 Mu(){return t.now()}function Vu(t){return Mu()-t}function Fu(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 Uu(e,i,s,r){const a=window.XMLHttpRequest;let n,o,u,d,l,c=!1,h=0,p=!1,m='arraybuffer',f=7e3,v=2e3,S=()=>{if(c)return;t.assertNonNullable(d);const e=Vu(d);let i;if(e<v)return i=v-e,void setTimeout(S,i);v*=2,v>f&&(v=f),o&&o.abort(),o=new a,g()};const b=()=>{if(!c){if(--h>=0)return S(),void(r&&r());c=!0,l&&l(),s&&s()}},g=()=>{d=Mu(),o=new a,o.open('get',e);let s,r=0,h=0;const f=()=>(t.assertNonNullable(d),Math.max(d,Math.max(s||0,h||0)));if(n&&o.addEventListener('progress',(t=>{const e=Mu();n.updateChunk&&t.loaded>r&&(n.updateChunk(f(),t.loaded-r),r=t.loaded,s=e)})),u&&(o.timeout=u,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(c)return;t.assertNonNullable(o);const e=o.status;if(e>=200&&e<300){if(o.response.byteLength&&n){const t=o.response.byteLength-r;t&&n.updateChunk&&n.updateChunk(f(),t)}l&&l(),o&&i(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),p){const e=()=>{t.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(h=Mu(),o.removeEventListener('readystatechange',e))};o.addEventListener('readystatechange',e)}return o.responseType=m,o.send(),y},y={withBitrateReporting:t=>(n=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(h=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(v=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(l=t,y),send:g,abort:()=>{o&&(o.abort(),o=void 0),c=!0,l&&l()}};return y}class qu{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 ju{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=Mu(),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=Uu(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Mu()-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=Mu()}_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=Mu();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 Hu{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 qu(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Fu(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=Fu(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 e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>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 ju(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const t=a&&(!l||l===this.rep);return t||i('Not running!'),t},h=(t,e,i)=>{u&&u.abort(),u=Uu(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==o||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{o=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),v()},v=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=Mu()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const r=this.bufferStates[i];t=Math.min(t,r.buf),r.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,m(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else m(1)},S=e=>{let s;const a=()=>s&&s.start?s.start.length:0,n=t=>s.start[t]/1e3,o=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,l=(t,e)=>({chunkIdx:u(t),startTS:n(t),dur:o(t),discontinuity:e}),h=()=>{let t=0;if(s&&s.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,i=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=s.dur.length-1;for(;a>=0&&(r-=s.dur[a],!(r<=0));--a);t=Math.min(a,s.dur.length-1-i),t=Math.max(t,0)}return l(t,!0)},p=(t,e,i)=>{d&&d.abort(),d=Uu(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{d=null})).withJSONResponse().send()};return{seek:(i,o)=>{p(e,(e=>{if(!c())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let d=0;for(let t=0;t<s.dur.length;++t)d+=s.dur[t];d>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(d/s.dur.length)),r({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=a();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(n(t)>e)return l(t);return h()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=a(),r=t?t.chunkIdx+1:0,n=r-s.fragIndex;if(!(e<=0)){if(!t||n<0||n-e>10)return i(`Resync: offset=${n} bChunks=${e} chunk=`+JSON.stringify(t)),h();if(!(n>=e))return l(r-s.fragIndex,!1)}}}},b=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:i=>{const{videoElement:s,logger:r}=this.params;let o,u,l,m,f,g,y,T=S(e.jidxUrl),E=0;const k=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=Mu(),s=Math.min(1e4,e-i);E=i;const r=()=>{d||c()&&T.seek((()=>{c()&&(E=Mu(),w(),k())}))};s>0?f=window.setTimeout((()=>{this.paused?k():r()}),s):r()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(l);if(i){if(l&&i.discontinuity)return r('Detected discontinuity; restarting playback'),void(this.paused?k():(b(),this._initPlayerWith(e)));x(i)}else k()},P=(t,e)=>{if(!c()||!this.sourceBuffer)return;let i,a,n;const o=i=>{window.setTimeout((()=>{c()&&P(t,e)}),i)};if(this.sourceBuffer.updating)r('Source buffer is updating; delaying appendBuffer'),o(100);else{const u=Mu(),d=s.currentTime;!this.paused&&s.buffered.length>1&&g===d&&u-y>500&&(r('Stall suspected; trying to fix'),this._fixupStall()),g!==d&&(g=d,y=u);const l=this._getBufferSizeSec();if(l>30)r(`Buffered ${l} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:l}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;r('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(i=this.sourceBuffer.buffered.start(0),a=d,a-i>4&&this.sourceBuffer.remove(i,a-3)),o(1e3)}}},$=()=>{u&&o&&(r([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(l)]),P(u,(function(){u=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{c()&&p(A(t),((e,i)=>{if(c()){if(i/=1e3,u=e,l=t,n=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{c()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},D=t=>{c()&&(e.cachedHeader=t,P(t,(()=>{o=!0,$()})))};a=!0,T.seek((e=>{c()&&(E=Mu(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(l=e,w())):k())}),i),e.cachedHeader?D(e.cachedHeader):h(e.headerUrl,D,(()=>this._handleNetworkError()))},stop:b,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),t.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_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=Mu();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&&Vu(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=Mu();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=Uu(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;Bu(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 Gu;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Gu||(Gu={}));const Yu=[Gu.PAUSED,Gu.PLAYING,Gu.READY],Qu=[Gu.PAUSED,Gu.PLAYING,Gu.READY];class zu{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Gu.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new du,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new cu,this._dashCb=e=>{var i,s,r,a;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,a=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),r=null!==(s=Ou(e.name))&&void 0!==s?s:Lo(e.video),n=e.bitrate/1e3,o=Object.assign({},e.video);if(!r)continue;const u={id:t,quality:r,bitrate:n,size:o};a.push({track:u,representation:e})}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)===Gu.MANIFEST_READY&&this.videoState.setState(Gu.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(a=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===a?void 0:a.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r!==exports.PlaybackState.STOPPED){if(!s){if(Qu.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested&&Yu.includes(i))this.seek(n.position-this.liveOffset.getTotalPausedTime());else switch(i){case Gu.STOPPED:return this.videoState.startTransitionTo(Gu.MANIFEST_READY),void this.dash.attachSource(No(this.params.source.url));case Gu.MANIFEST_READY:this.videoState.startTransitionTo(Gu.READY),this.prepare();break;case Gu.READY:return void(r===exports.PlaybackState.PAUSED?this.videoState.setState(Gu.PAUSED):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Gu.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Gu.PAUSED)}))));case Gu.PLAYING:return void(r===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(Gu.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Gu.PAUSED:return void(r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Gu.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(Gu.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return t.assertNever(i)}}}else i!==Gu.STOPPED&&(this.videoState.startTransitionTo(Gu.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Gu.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=lu(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(Du(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=vu(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Gu.READY&&this.videoState.setState(Gu.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(Gu.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===l.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Gu.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(t.combine({zeroTime:this.zeroTime$.pipe(t.filter(t.isNonNullable)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)).add(nu(this.video,this.params.desiredState.isLooped,i)).add(ou(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(fu(this.video).subscribe(this.params.output.firstBytesEvent$)).add(hu(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&_o[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case Gu.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case Gu.MANIFEST_READY:case Gu.READY:break;case Gu.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case Gu.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(e.to)}}),i)).add(t.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Hu({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 e,i,s,r,a,n;const o=this.representations$.getValue(),u=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),d=null!==(r=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&t.isNonNullable(u)?u:null===(a=Nu(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===l)))||void 0===n?void 0:n.representation;t.assertNonNullable(c,'Representations missing'),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var i;const s=null===(i=this.representations$.getValue().find((({track:t})=>t.id===e)))||void 0===i?void 0:i.representation;t.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}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(No(this.params.source.url,i))}}var Wu=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.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}},Ju=(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)};var Ku=_,Xu=Zt,Zu=Function.prototype,td=Ku&&Object.getOwnPropertyDescriptor,ed=Xu(Zu,'name'),id={EXISTS:ed,PROPER:ed&&'something'===function(){}.name,CONFIGURABLE:ed&&(!Ku||Ku&&td(Zu,'name').configurable)},sd={},rd=bs,ad=Math.max,nd=Math.min,od=it,ud=function(t,e){var i=rd(t);return i<0?ad(i+e,0):nd(i,e)},dd=Es,ld=function(t){return function(e,i,s){var r,a=od(e),n=dd(a),o=ud(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}},cd={includes:ld(!0),indexOf:ld(!1)},hd=Zt,pd=it,md=cd.indexOf,fd=Wa,vd=x([].push),Sd=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],bd=function(t,e){var i,s=pd(t),r=0,a=[];for(i in s)!hd(fd,i)&&hd(s,i)&&vd(a,i);for(;e.length>r;)hd(s,i=e[r++])&&(~md(a,i)||vd(a,i));return a},gd=Sd,yd=Object.keys||function(t){return bd(t,gd)},Td=_,Ed=ii,kd=ei,wd=oi,Pd=it,$d=yd;sd.f=Td&&!Ed?Object.defineProperties:function(t,e){wd(t);for(var i,s=Pd(e),r=$d(e),a=r.length,n=0;a>n;)kd.f(t,i=r[n++],s[i]);return t};var Ad,xd=oi,Nd=sd,Dd=Sd,_d=Wa,Rd=Pr,Id=De,Cd=za('IE_PROTO'),Ld=function(){},Od=function(t){return'<script>'+t+'<\/script>'},Bd=function(t){t.write(Od('')),t.close();var e=t.parentWindow.Object;return t=null,e},Md=function(){try{Ad=new ActiveXObject('htmlfile')}catch(t){}var t,e;Md='undefined'!=typeof document?document.domain&&Ad?Bd(Ad):((e=Id('iframe')).style.display='none',Rd.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Od('document.F=Object')),t.close(),t.F):Bd(Ad);for(var i=Dd.length;i--;)delete Md.prototype[Dd[i]];return Md()};_d[Cd]=!0;var Vd,Fd,Ud,qd=Object.create||function(t,e){var i;return null!==t?(Ld.prototype=xd(t),i=new Ld,Ld.prototype=null,i[Cd]=t):i=Md(),void 0===e?i:Nd.f(i,e)},jd=!v((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),Hd=f,Gd=Zt,Yd=N,Qd=Jt,zd=jd,Wd=za('IE_PROTO'),Jd=Hd.Object,Kd=Jd.prototype,Xd=zd?Jd.getPrototypeOf:function(t){var e=Qd(t);if(Gd(e,Wd))return e[Wd];var i=e.constructor;return Yd(i)&&e instanceof i?i.prototype:e instanceof Jd?Kd:null},Zd=v,tl=N,el=qd,il=Xd,sl=Ii,rl=fe('iterator'),al=!1;[].keys&&('next'in(Ud=[].keys())?(Fd=il(il(Ud)))!==Object.prototype&&(Vd=Fd):al=!0);var nl=null==Vd||Zd((function(){var t={};return Vd[rl].call(t)!==t}));tl((Vd=nl?{}:el(Vd))[rl])||sl(Vd,rl,(function(){return this}));var ol={IteratorPrototype:Vd,BUGGY_SAFARI_ITERATORS:al},ul=ol.IteratorPrototype,dl=qd,ll=U,cl=es,hl=hs,pl=function(){return this},ml=Di,fl=C,vl=function(t,e,i,s){var r=e+' Iterator';return t.prototype=dl(ul,{next:ll(+!s,i)}),cl(t,r,!1,!0),hl[r]=pl,t},Sl=Xd,bl=es,gl=Ii,yl=hs,Tl=id.PROPER,El=ol.BUGGY_SAFARI_ITERATORS,kl=fe('iterator'),wl=function(){return this},Pl=it,$l=hs,Al=vn;ei.f;var xl=function(t,e,i,s,r,a,n){vl(i,e,s);var o,u,d,l=function(t){if(t===r&&f)return f;if(!El&&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',h=!1,p=t.prototype,m=p[kl]||p['@@iterator']||r&&p[r],f=!El&&m||l(r),v='Array'==e&&p.entries||m;if(v&&(o=Sl(v.call(new t)))!==Object.prototype&&o.next&&(bl(o,c,!0,!0),yl[c]=wl),Tl&&'values'==r&&m&&'values'!==m.name&&(h=!0,f=function(){return fl(m,this)}),r)if(u={values:l('values'),keys:a?f:l('keys'),entries:l('entries')},n)for(d in u)(El||h||!(d in p))&&gl(p,d,u[d]);else ml({target:e,proto:!0,forced:El||h},u);return n&&p[kl]!==f&&gl(p,kl,f,{name:r}),yl[e]=f,u},Nl=Al.set,Dl=Al.getterFor('Array Iterator');xl(Array,'Array',(function(t,e){Nl(this,{type:'Array Iterator',target:Pl(t),index:0,kind:e})}),(function(){var t=Dl(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'),$l.Arguments=$l.Array;var _l=$e,Rl=ei,Il=U,Cl=Js,Ll=function(t,e,i){var s=_l(e);s in t?Rl.f(t,s,Il(0,i)):t[s]=i};Di({target:'Object',stat:!0},{fromEntries:function(t){var e={};return Cl(t,(function(t,i){Ll(e,t,i)}),{AS_ENTRIES:!0}),e}});var Ol=at.Object.fromEntries,Bl={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},Ml=f,Vl=Yi,Fl=bi,Ul=hs,ql=fe('toStringTag');for(var jl in Bl){var Hl=Ml[jl],Gl=Hl&&Hl.prototype;Gl&&Vl(Gl)!==ql&&Fl(Gl,ql,jl),Ul[jl]=Ul.Array}var Yl,Ql=Ol;class zl{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 e=!1;this._xhr.onreadystatechange=()=>{var i,s,r,a,n,o,u,d;if(t.assertNonNullable(this._xhr),(null===(i=this._xhr)||void 0===i?void 0:i.status)>=400)return null===(s=this._errorCb)||void 0===s||s.call(this,`Http${null===(r=this._xhr)||void 0===r?void 0:r.status}`,`XHR response code ${null===(a=this._xhr)||void 0===a?void 0:a.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Ql(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(n=this._headersCb)||void 0===n||n.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(o=this._completeCb)||void 0===o||o.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(u=this._progressCb)||void 0===u||u.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 Wl{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 u=Date.now();let d=0,l=0,c=0;const h=t=>{s(Wl._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=su(p)),this._lastXhr=new zl(p,t.failoverHosts,(t=>{this._lastXhr=void 0,h(t);const e=Date.now()-u;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&&h(t),0===l)return void(l=Date.now());c=t.length-d;const e=Date.now()-l;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,d=t.length,l=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=Wl._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 Jl{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=su(i)),new zl(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,u,d,l,c,h,p,m,f,v,S,b,g,y,T,E,k,w;const P=t.getElementsByTagName('SegmentBase')[0],$=P&&r(P,'indexRange').split('-'),A=P&&P.getElementsByTagName('Initialization')[0],x=A&&r(A,'range').split('-');if(!x||!$){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===(l=null===(d=null===(u=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===u?void 0:u.childNodes)||void 0===d?void 0:d[0])||void 0===l?void 0:l.data),h=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:h})}return}const N=Number(null===(h=t.attributes.getNamedItem('bandwidth'))||void 0===h?void 0:h.value),D=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let _;const R=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;_=R?Su(R):void 0,a.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:N,baseURL:D,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(b=null===(S=t.attributes.getNamedItem('codecs'))||void 0===S?void 0:S.value)&&void 0!==b?b:void 0,mimeType:null!==(y=null===(g=t.attributes.getNamedItem('mimeType'))||void 0===g?void 0:g.value)&&void 0!==y?y:void 0,fps:_,bufferSize:.1*N/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!==(w=null===(k=t.attributes.getNamedItem('id'))||void 0===k?void 0:k.value)&&void 0!==w?w: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 u=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;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 d=t.refs[t.refs.length-1];d.toTime-d.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.end-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.end&&(r=e.end,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.start)}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 Wl({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.end+r){const e=this._findRef(s.toTime);e&&e.toTime<i.end+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 e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!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}}!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'}(Yl||(Yl={}));const Kl=[Yl.PAUSED,Yl.PLAYING];class Xl{constructor(e){this.videoState=new Bo(Yl.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new du,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},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&&Ou(a.name))&&void 0!==s?s:Lo(a),o=a.bandwidth/1e3,u={width:a.width,height:a.height},d=a.fps;if(!n)continue;const l={id:t,quality:n,bitrate:o,size:u,fps:d};r.push({track:l,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(Yl.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 e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(a)};`}),s!==exports.PlaybackState.STOPPED){if(!i)switch((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&Kl.includes(e)&&this.seek(a.position,a.forcePrecise),e){case Yl.STOPPED:return this.videoState.startTransitionTo(Yl.MANIFEST_LOADED),void this.prepare();case Yl.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Yl.INITIAL_REPRESENTATION_SELECTED);case Yl.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Yl.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Yl.METADATA_LOADED:return this.videoState.startTransitionTo(Yl.READY),void this.dash.updateRefsForCurrentTime();case Yl.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Yl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Yl.PLAYING),this.playIfAllowed()));case Yl.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Yl.PAUSED),this.video.pause()):(null==r?void 0:r.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Yl.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Yl.PLAYING),this.playIfAllowed()):(null==r?void 0:r.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Yl.STOPPED&&(this.videoState.startTransitionTo(Yl.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(Yl.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=lu(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(Du(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new pu(this.video),this.dash=new Jl({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:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:t})},r=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},a=vu(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,s));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.firstFrame$,e.firstFrameEvent$),this.subscription.add(a.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekState.getState().state!==l.Applying)&&(this.videoState.getState()===Yl.PLAYING||this.videoState.getState()===Yl.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(nu(this.video,i.isLooped,s)),this.subscription.add(ou(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,i,e),n(_u(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Yl.READY&&this.videoState.setState(Yl.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Yl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(a.playing$.subscribe((()=>{this.videoState.setState(Yl.PLAYING),Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.loadedMetadata$.subscribe((()=>{this.videoState.setState(Yl.METADATA_LOADED)}),s)).add(a.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(t.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i,s;const a=this.currentRepresentation$.getValue(),n=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.videoTrack.getState(),d=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),c=r();let h;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!c&&t.isNonNullable(u))h=u;else{const t=Ju(this.video.buffered,1e3*this.video.currentTime),s=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,r=Math.min(t/s,1);h=null===(i=Nu(n.map((({track:t})=>t)),{container:l,throughput:d,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:r,playbackRate:this.video.playbackRate,current:null===(e=n.find((({representation:t})=>t===a)))||void 0===e?void 0:e.track}))||void 0===i?void 0:i.id}return t.isNonNullable(h)?null===(s=n.find((({track:t})=>t.id===h)))||void 0===s?void 0:s.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===Yl.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(Yl.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?t.height<=e.height:t===e))).subscribe((t=>{const e=Ju(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!r())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Du(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Wu(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(t.filter(t.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case'url':this.dash.attachSource(e.url);break;case'raw':this.dash.attachManifest(e.raw);break;default:return t.assertNever(e)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Bu(this.video).then((t=>{t||(this.videoState.setState(Yl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Zl,tc,ec,ic;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(Zl||(Zl={})),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.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(ec||(ec={})),function(t){t.MP4='mp4',t.WEBM='webm'}(ic||(ic={}));var sc=(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};class rc{constructor(e){this.bufferFull$=new t.Subject,this.error$=new t.Subject,this.queue=[],this.currentTask=null,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=e,this.buffer.addEventListener('updateend',this.completeTask)}append(t,e){return Fo(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 Fo(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 Fo(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.buffer.removeEventListener('updateend',this.completeTask)}pull(){var t;if(this.buffer.updating||this.currentTask)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;try{this.execute(this.currentTask)}catch(t){this.currentTask.callback(!1),this.currentTask=null,this.error$.next({id:'BufferTaskQueueOperation',message:'Buffer appending or removal failed',thrown:t})}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(e){const{operation:i}=e;switch(i){case'append':try{this.buffer.appendBuffer(e.data)}catch(t){throw t instanceof DOMException&&'QuotaExceededError'===t.name&&this.bufferFull$.next(e.data.byteLength),t}break;case'remove':this.buffer.remove(e.from/1e3,e.to/1e3);break;case'abort':this.buffer.abort();break;default:t.assertNever(i)}}}var ac;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(ac||(ac={}));class nc{constructor({throughputEstimator:e,requestQuic:i}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new Jo,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,function(t){return qo(this,arguments,(function*(){let e=t;this.requestQuic&&(e=su(e));const i=yield yield Uo(Wo(e,{signal:this.abortAllController.signal}).catch(oc));return i?(this.onHeadersReceived(i.headers),yield Uo(i.text())):yield Uo(null)}))}.bind(this)),this.fetchRange=t.abortable(this.abortAllController.signal,function(e,i,s,{method:r=ac.HEADER,onProgress:a,priority:n='auto',signal:o,measureThroughput:u=!0}={}){var d,l,c;return qo(this,arguments,(function*(){let h=e;const p=new Headers;switch(r){case ac.HEADER:p.append('Range',`${i}-${s}`);break;case ac.PARAM:{const t=new URL(h,location.href);t.searchParams.append('bytes',`${i}-${s}`),h=t.toString();break}default:t.assertNever(r)}this.requestQuic&&(h=su(h));let m=this.abortAllController.signal;if(o){const e=new Jo;this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(o,'abort')).subscribe((()=>{e.abort()}))),(this.abortAllController.signal.aborted||o.aborted)&&e.abort(),m=e.signal}const f=t.now(),v=yield yield Uo(Wo(h,{priority:n,headers:p,signal:m}).catch(oc));if(null===(d=this.throughputEstimator)||void 0===d||d.addRawRtt(t.now()-f),!v)return yield Uo(null);if(!v.ok||!v.body)return yield Uo(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));this.onHeadersReceived(v.headers);const[S,b]=v.body.tee(),g=S.getReader();u&&(null===(l=this.throughputEstimator)||void 0===l||l.trackStream(b));const y=parseInt(null!==(c=v.headers.get('Content-Length'))&&void 0!==c?c:'',10)||s-i+1;let T=0;const E=new ArrayBuffer(y),k=new Uint8Array(E),w=new DataView(E);let P=!1;const $=t=>{P=!0,oc(t)},A=t.abortable(m,function({done:e,value:i}){return qo(this,arguments,(function*(){if(0===T&&this.lastRequestFirstBytes$.next(t.now()-f),m.aborted)return yield Uo(void 0);e?null==a||a(w,T):i&&(k.set(i,T),T+=i.byteLength,null==a||a(w,T),yield yield Uo(null==g?void 0:g.read().then(A,$)))}))}.bind(this));return yield yield Uo(null==g?void 0:g.read().then(A,$)),yield Uo(P?null:E)}))}.bind(this)),this.fetchRepresentation=t.abortable(this.abortAllController.signal,function(t,e,i='auto',s=0){return qo(this,arguments,(function*(){const{from:r,to:a}=t.initRange;let n,o,u=r,d=a,l=!1;t.indexRange&&(n=t.indexRange.from,o=t.indexRange.to,l=a+1===n,l&&(u=Math.min(n,r),d=Math.max(o,a))),u=Math.min(u,0),d+=s;const c=yield yield Uo(this.fetchRange(t.url,u,d,{method:ac.PARAM,priority:i,measureThroughput:!1}));if(!c)return yield Uo(null);const h=new DataView(c,r-u,a-u+1);if(!e.validateData(h))throw new Error('Invalid media file');const p=e.parseInit(h);let m;if(l&&void 0!==n&&void 0!==o)m=new DataView(c,n-u,o-n+1);else{const s=e.getIndexRange(p);if(s){const e=yield yield Uo(this.fetchRange(t.url,s.from,s.to,{method:ac.PARAM,priority:i,measureThroughput:!1}));if(!e)return yield Uo(null);m=new DataView(e)}}if(!m)throw new ReferenceError('No way to load representation index');const f=e.parseSegments(m,p);return yield Uo({dataView:new DataView(c),segments:f})}))}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=Wu(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const oc=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},uc=new TextDecoder('ascii'),dc=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=uc.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)}},lc={validateData:t=>'ftyp'===uc.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=dc(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(),u=4294967295&r();let d=n/a*1e3,l=t.byteOffset+t.byteLength+o;for(let t=0;t<u;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:ec.NONE,time:{from:d,to:d+o},byte:{from:l,to:l+s-1}}),d+=o,l+=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=dc(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 cc,hc;!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'}(cc||(cc={})),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'}(hc||(hc={}));const pc={[cc.EBML]:{type:hc.Master},[cc.EBMLVersion]:{type:hc.UnsignedInteger},[cc.EBMLReadVersion]:{type:hc.UnsignedInteger},[cc.EBMLMaxIDLength]:{type:hc.UnsignedInteger},[cc.EBMLMaxSizeLength]:{type:hc.UnsignedInteger},[cc.DocType]:{type:hc.String},[cc.DocTypeVersion]:{type:hc.UnsignedInteger},[cc.DocTypeReadVersion]:{type:hc.UnsignedInteger},[cc.Void]:{type:hc.Binary},[cc.Segment]:{type:hc.Master},[cc.SeekHead]:{type:hc.Master},[cc.Seek]:{type:hc.Master},[cc.SeekID]:{type:hc.Binary},[cc.SeekPosition]:{type:hc.UnsignedInteger},[cc.Info]:{type:hc.Master},[cc.TimestampScale]:{type:hc.UnsignedInteger},[cc.Duration]:{type:hc.Float},[cc.Tracks]:{type:hc.Master},[cc.Chapters]:{type:hc.Master},[cc.Cluster]:{type:hc.Master},[cc.Timestamp]:{type:hc.UnsignedInteger},[cc.SilentTracks]:{type:hc.Master},[cc.SilentTrackNumber]:{type:hc.UnsignedInteger},[cc.Position]:{type:hc.UnsignedInteger},[cc.PrevSize]:{type:hc.UnsignedInteger},[cc.SimpleBlock]:{type:hc.Binary},[cc.BlockGroup]:{type:hc.Master},[cc.EncryptedBlock]:{type:hc.Binary},[cc.Attachments]:{type:hc.Master},[cc.Tags]:{type:hc.Master},[cc.Cues]:{type:hc.Master},[cc.CuePoint]:{type:hc.Master},[cc.CueTime]:{type:hc.UnsignedInteger},[cc.CueTrackPositions]:{type:hc.Master},[cc.CueTrack]:{type:hc.UnsignedInteger},[cc.CueClusterPosition]:{type:hc.UnsignedInteger},[cc.CueRelativePosition]:{type:hc.UnsignedInteger},[cc.CueDuration]:{type:hc.UnsignedInteger},[cc.CueBlockNumber]:{type:hc.UnsignedInteger},[cc.CueCodecState]:{type:hc.UnsignedInteger},[cc.CueReference]:{type:hc.Master},[cc.CueRefTime]:{type:hc.UnsignedInteger}},mc=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 pc,a=r?pc[s].type:hc.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 u=new DataView(t.buffer,t.byteOffset+i+1,o-1),d=((n&255>>o)<<8*(o-1))+fc(u),l=i+o;let c;return c=l+d>t.byteLength?new DataView(t.buffer,t.byteOffset+l):new DataView(t.buffer,t.byteOffset+l,d),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+d,value:c,valueSize:d}},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},vc=(e,i)=>{switch(i){case hc.SignedInteger:return e.getInt8(0);case hc.UnsignedInteger:return fc(e);case hc.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case hc.String:return new TextDecoder('ascii').decode(e);case hc.UTF8:return new TextDecoder('utf-8').decode(e);case hc.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case hc.Master:case hc.Binary:return e;default:t.assertNever(i)}},Sc=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=mc(s);if(!e(r))return;r.type===hc.Master&&Sc(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},bc=[cc.Info,cc.SeekHead,cc.Tracks,cc.Chapters,cc.Cluster,cc.Cues,cc.Attachments,cc.Tags],gc=[cc.Timestamp,cc.SilentTracks,cc.SilentTrackNumber,cc.Position,cc.PrevSize,cc.SimpleBlock,cc.BlockGroup,cc.EncryptedBlock],yc={validateData:t=>{if(t.getUint32(0)!==cc.EBML)return!1;let e,i,s;const r=mc(t);return Sc(r.value,(({tag:t,type:r,value:a})=>(t===cc.EBMLReadVersion?e=vc(a,r):t===cc.DocType?i=vc(a,r):t===cc.DocTypeReadVersion&&(s=vc(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,r,a,n,o,u=!1,d=!1,l=!1;return Sc(e,(({tag:t,type:e,value:c,valueSize:h})=>{if(t===cc.SeekID){const t=vc(c,e);o=fc(t)}else t!==cc.SeekPosition&&(o=void 0);return t===cc.Segment?(i=c.byteOffset,s=c.byteOffset+h):t===cc.Info?u=!0:t===cc.SeekHead?d=!0:t===cc.TimestampScale?r=vc(c,e):t===cc.Duration?a=vc(c,e):t===cc.SeekPosition&&o===cc.Cues?n=vc(c,e):u&&d&&bc.includes(t)&&(l=!0),!l})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(a,'Failed to parse webm Segment duration'),r=null!=r?r:1e6,{segmentStart:Math.round(i/1e9*r*1e3),segmentEnd:Math.round(s/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:n}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,r=!1;const a=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),n=[];let o;return Sc(e,(({tag:t,type:e,value:i})=>{switch(t){case cc.Cues:s=!0;break;case cc.CuePoint:o&&a(o)&&n.push(o),o={};break;case cc.CueTime:o&&(o.time=vc(i,e));break;case cc.CueTrackPositions:break;case cc.CueClusterPosition:o&&(o.position=vc(i,e));break;default:s&&bc.includes(t)&&(r=!0)}return!(s&&r)})),o&&a(o)&&n.push(o),n.map(((t,e)=>{const{time:s,position:r}=t,a=n[e+1];return{status:ec.NONE,time:{from:s,to:a?a.time:i.segmentDuration},byte:{from:i.segmentStart+r,to:a?i.segmentStart+a.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Sc(t,(s=>s.tag===cc.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!gc.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[cc.SimpleBlock,cc.BlockGroup,cc.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class Tc{constructor(e,i,s,r,{fetcher:a,tuning:n,getCurrentPosition:o}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Jo,this.destroyAbortController=new Jo,this.bufferLimit=1/0,this.startWith=t.abortable(this.destroyAbortController.signal,function(e){return qo(this,arguments,(function*(){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.sourceBufferTaskQueue=new rc(this.sourceBuffer),this.subscription.add(t.fromEvent(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(t.fromEvent(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t})))),this.subscription.add(this.sourceBufferTaskQueue.bufferFull$.subscribe((t=>this.pruneBuffer(t)))),this.subscription.add(this.sourceBufferTaskQueue.error$.subscribe((t=>this.error$.next(t))));const s=this.tuning.useFetchPriorityHints?'high':'auto';yield yield Uo(this.loadInit(i,s));const r=this.initData.get(i.id),a=this.segments.get(i.id);if(t.assertNonNullable(r,'No init buffer for starting representation'),t.assertNonNullable(a,'No segments for starting representation'),!(r instanceof ArrayBuffer))return yield Uo(void 0);let n=0;for(const t of a)t.time.from-n>=300&&this.gaps.push({representation:i.id,from:n,to:t.time.from}),n=t.time.to;t.isNonNullable(i.duration)&&i.duration-n>=300&&this.gaps.push({representation:i.id,from:n,to:i.duration}),yield yield Uo(this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)}))}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,function(e){return qo(this,arguments,(function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return yield Uo(void 0);this.switchingToRepresentationId=e;const i=this.representations.get(e);t.assertNonNullable(i,`No such representation ${e}`);let s=this.initData.get(e);if(t.isNullable(s)){const t=this.tuning.useFetchPriorityHints?'high':'auto';yield yield Uo(this.loadInit(i,t))}else s instanceof Promise&&(yield yield Uo(s));if(s=this.initData.get(e),!(s&&s instanceof ArrayBuffer&&this.sourceBuffer))return yield Uo(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield yield Uo(this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal));const r=this.getCurrentPosition();t.isNonNullable(r)&&this.maintain(r)}))}.bind(this)),this.fetcher=a,this.tuning=n,this.forwardBufferTarget=n.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case ic.MP4:this.containerParser=lc;break;case ic.WEBM:this.containerParser=yc;break;default:t.assertNever(s)}this.initData=new Map(r.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(r.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Jo,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer))return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(t.assertNonNullable(i,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find((t=>e>=t.time.from&&e<t.time.to));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=100,i=Ju(this.sourceBuffer.buffered,e),s=r?r.time.to+t:-1/0;r&&i>=r.time.to-e+t&&(a=s)}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(s,a),n.length)){let t='auto';if(this.tuning.useFetchPriorityHints&&r)if(n.includes(r))t='high';else{const e=Tu(n,0);e&&e.time.from-r.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,i,t)}!this.allInitsLoaded&&r&&r.status===ec.FED&&!n.length&&Ju(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const o=Tu(s,-1);o&&o.status===ec.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===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){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===ec.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.forwardBufferTarget));if(-1===i)return[];let s=0;const r=[];for(let e=i;e<t.length&&s<=this.tuning.segmentRequestSize;e++){const i=t[e];if(s+=i.byte.to+1-i.byte.from,i.status!==ec.NONE)break;r.push(i)}return r}loadSegments(t,e,i='auto'){return Fo(this,void 0,void 0,(function*(){if(!t.length)return;const s=Tu(t,0).byte.from,r=Tu(t,-1).byte.to;for(const i of t)i.status=ec.DOWNLOADING,this.activeSegments.add({segment:i,loadedBytes:0,fedBytes:0,representationId:e.id});const{signal:a}=this.downloadAbortController;this.fetcher.fetchRange(e.url,s,r,{method:ac.PARAM,onProgress:(t,i)=>{if(!a.aborted)try{this.onSomeDataLoaded(t,e.id,s,i,a)}catch(t){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:t})}},signal:a,priority:i}).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})))}))}onSomeDataLoaded(t,e,i,s,r){var a;if(!this.activeSegments.size)return;const n=t=>{this.abortSegment(t.segment)},o=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=ec.FED;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===ec.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=ec.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])};for(const u of this.activeSegments){const{segment:d}=u,l=d.byte.to-d.byte.from+1;if(r.aborted){n(u);continue}if(u.representationId!==e)continue;const c=d.byte.from>=i,h=d.byte.from<i+s,p=d.byte.to<=i+s;if(d.status===ec.DOWNLOADING&&c&&h&&p){d.status=ec.DOWNLOADED,this.activeSegments.delete(u);const e=new DataView(t.buffer,t.byteOffset+d.byte.from-i,Math.min(l,i+s-d.byte.from));this.sourceBufferTaskQueue.append(e,r).then((t=>t&&!r.aborted?o(u):n(u)))}else if(this.tuning.enableSubSegmentBufferFeeding&&c&&h){const e=Math.min(l,s-(d.byte.from-i));u.buffer=null!==(a=u.buffer)&&void 0!==a?a:new ArrayBuffer(l);const c=new DataView(u.buffer);for(let s=u.loadedBytes;s<e;s++)c.setUint8(s,t.getUint8(d.byte.from-i+s));u.loadedBytes=e;const h=new DataView(u.buffer,u.fedBytes,u.loadedBytes-u.fedBytes);if(l===u.loadedBytes&&u.fedBytes!==u.loadedBytes)d.status=ec.DOWNLOADED,u.fedBytes=u.loadedBytes,this.sourceBufferTaskQueue.append(h,r).then((t=>t&&!r.aborted?o(u):n(u)));else if(u.loadedBytes>u.fedBytes){const t=this.containerParser.parseFeedableSegmentChunk(h);t&&(d.status=ec.PARTIALLY_FED,u.fedBytes+=t.byteLength,this.sourceBufferTaskQueue.append(t,r).then((t=>{t&&!r.aborted||n(u)})))}}}}abortSegment(t){t.status===ec.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=ec.NONE)),t.status=ec.NONE):t.status=ec.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);if(!i)return;const s=this.tuning.useFetchPriorityHints?'low':'auto';this.initLoadIdleCallback=requestIdleCallback((()=>Ao(this.loadInit(i,s),(()=>this.initLoadIdleCallback=null))))}loadInit(t,e){return Fo(this,void 0,void 0,(function*(){const i=this.fetcher.fetchRepresentation(t,this.containerParser,e).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)})).catch((e=>{this.initData.set(t.id,null),this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,i),i}))}pruneBuffer(e){return Fo(this,void 0,void 0,(function*(){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let r=0,a=1/0,n=-1/0,o=!1;for(const t of s){if(t.time.to>=i||r>=e)break;t.status===ec.FED&&(a=Math.min(a,t.time.from),n=Math.max(n,t.time.to),r+=t.byte.to-t.byte.from)}if(o=isFinite(a)&&isFinite(n)&&(r>=e||e===1/0),!o){r=0,a=1/0,n=-1/0;for(const t of s)t.status===ec.FED&&t.time.from>i+this.forwardBufferTarget&&(a=Math.min(a,t.time.from),n=Math.max(n,t.time.to),r+=t.byte.to-t.byte.from)}return o=isFinite(a)&&isFinite(n)&&(r>=e||e===1/0),!!o&&(yield this.sourceBufferTaskQueue.remove(a,n/1e3),!0)}))}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=requestIdleCallback((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=1e3*this.sourceBuffer.buffered.start(t),s=1e3*this.sourceBuffer.buffered.end(t);e.push({from:i,to:s})}const i=this.tuning.segmentTimelineTolerance;for(const t of this.segments.values())for(const s of t){const t=e.some((t=>t.from-i<=s.time.from&&t.to+i>=s.time.to));s.status!==ec.FED||t||(s.status=ec.NONE)}}}const Ec=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)},kc=(e,i)=>{var s,r,a,n,o,u,d,l,c,h,p,m,f,v,S,b,g,y,T,E,k,w,P,$;const A={video:[],audio:[],text:[]},x=(new DOMParser).parseFromString(e,'application/xml').children[0],N=x.getElementsByTagName('Period')[0],D=N.children;let _;const R=x.getAttribute('mediaPresentationDuration'),I=N.getAttribute('duration');if(R)_=Ec(R);else if(I){const e=Ec(I);t.isNonNullable(e)&&(_=e)}let C=0;const L=null!==(r=null===(s=x.getAttribute('profiles'))||void 0===s?void 0:s.split(','))&&void 0!==r?r:[],O=L.includes(tc.WEBM_AS_IN_FFMPEG)||L.includes(tc.WEBM_AS_IN_SPEC)?ic.WEBM:ic.MP4;for(const t of D){const e=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==e?void 0:e.split('/')[0],x=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],N=t.querySelectorAll('Representation');for(const a of N){const n=null!==(u=a.getAttribute('mimeType'))&&void 0!==u?u:e,o=null!==(l=null!==(d=a.getAttribute('codecs'))&&void 0!==d?d:s)&&void 0!==l?l:'',N=null!==(h=null!==(c=a.getAttribute('contentType'))&&void 0!==c?c:null==n?void 0:n.split('/')[0])&&void 0!==h?h:r,D=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],R=parseInt(null!==(f=a.getAttribute('width'))&&void 0!==f?f:'',10),I=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),O=parseInt(null!==(S=a.getAttribute('bandwidth'))&&void 0!==S?S:'',10)/1e3,B=null!==(b=a.getAttribute('frameRate'))&&void 0!==b?b:'',M=null!==(g=a.getAttribute('quality'))&&void 0!==g?g:void 0,V=B?Su(B):void 0,F=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(C++).toString(10)}@${'video'===N?`${I}p`:'audio'===N?`${O}Kbps`:o}`,U=null!==(k=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==k?k:'',q=new URL(U,i).toString(),j=[...L,...x,...D],H=null!==(P=null===(w=a.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==P?P:'',[G,Y]=H.split('-').map((t=>parseInt(t,10))),Q={from:G,to:Y},z=null===($=a.querySelector('SegmentBase'))||void 0===$?void 0:$.getAttribute('indexRange'),[W,J]=z?z.split('-').map((t=>parseInt(t,10))):[],K=z?{from:W,to:J}:void 0;if(!N||!n)continue;const X={video:Zl.VIDEO,audio:Zl.AUDIO,text:Zl.TEXT}[N];X&&A[X].push({id:F,kind:X,duration:_,profiles:j,initRange:Q,indexRange:K,bitrate:O,mime:n,codecs:o,width:R,height:I,fps:V,quality:M,url:q})}}return{container:O,representations:A}},wc=['timeupdate','progress','play','seeked','stalled'];var Pc,$c;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Pc||(Pc={}));class Ac{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new Bo(Pc.NONE),this.currentVideoRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.forceEnded$=new t.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Jo,this.initManifest=t.abortable(this.destroyController.signal,function(t,e){return qo(this,arguments,(function*(){this.element=t,this.state$.startTransitionTo(Pc.MANIFEST_LOADED);const i=yield yield Uo(this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:t}))));if(!i)return yield Uo(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 Uo(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:Ql(Object.entries(s.representations).map((([t,e])=>[t,e.filter(r)])))}),this.manifest.representations.video.length?this.state$.setState(Pc.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),yield Uo(this.manifest)}))}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,function(e,i){return qo(this,arguments,(function*(){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(Pc.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning.dash,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new Tc(Zl.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],t.isNonNullable(i)&&(this.audioBufferManager=new Tc(Zl.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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=t.merge(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(t.map((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),a=t.merge(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(t.map((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(t.merge(this.forceEnded$,t.combine({allBuffersFull:r,someBufferEnded:a}).pipe(t.filter((({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(t.merge(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield yield Uo(new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)})))),this.audioBufferManager&&t.isNonNullable(i)?yield yield Uo(Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)])):yield yield Uo(this.videoBufferManager.startWith(e)),this.state$.setState(Pc.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...wc.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&sc(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}))}.bind(this)),this.tick=()=>{var e,i;if(!this.element||!this.videoBufferManager)return;const s=1e3*this.element.currentTime;this.videoBufferManager.maintain(s),null===(e=this.audioBufferManager)||void 0===e||e.maintain(s),!this.videoBufferManager.gaps.length&&!(null===(i=this.audioBufferManager)||void 0===i?void 0:i.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(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=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new nc({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}switchRepresentation(t,e){return Fo(this,void 0,void 0,(function*(){const i={[Zl.VIDEO]:this.videoBufferManager,[Zl.AUDIO]:this.audioBufferManager,[Zl.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}))}seek(e,i){var s,r,a,n,o;let u;t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),u=i||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(null!==(s=this.videoBufferManager.findSegmentStartTime(e))&&void 0!==s?s:e,null!==(a=null===(r=this.audioBufferManager)||void 0===r?void 0:r.findSegmentStartTime(e))&&void 0!==a?a:e),sc(this.element.buffered,u)||(this.videoBufferManager.abort(),null===(n=this.audioBufferManager)||void 0===n||n.abort()),this.videoBufferManager.maintain(u),null===(o=this.audioBufferManager)||void 0===o||o.maintain(u),this.element.currentTime=u/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(Pc.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'}($c||($c={}));const xc=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?Ou(a):void 0)&&void 0!==n?n:Lo({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},Nc=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=Tu(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:Tu(t,-1)};class Dc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo($c.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new du,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new xu,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(r.state===l.Requested&&(null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&e!==$c.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(r.position,r.forcePrecise),i!==exports.PlaybackState.STOPPED){if(e===$c.STOPPED)return this.videoState.startTransitionTo($c.READY),void this.prepare();switch(e){case $c.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState($c.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($c.PLAYING),this.playIfAllowed()));case $c.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo($c.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case $c.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo($c.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==$c.STOPPED&&(this.videoState.startTransitionTo($c.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($c.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=lu(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Du(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ac({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=vu(this.video),r=t=>{e.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:t})},a=(t,e)=>this.subscription.add(t.subscribe(e,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.firstFrame$,e.firstFrameEvent$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(nu(this.video,i.isLooped,r)),this.subscription.add(ou(this.video,i.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),a(_u(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState($c.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),r)).add(s.pause$.subscribe((()=>{this.videoState.setState($c.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),r)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===$c.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===Pc.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState($c.READY)})));const n=t=>e.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:t});this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var s,r,a,o,u,d,l,c;const h=this.player.state$.getState(),p=this.player.state$.getTransition();if(h===Pc.NONE||!this.videoTracks.length)return;const m=h===Pc.MANIFEST_LOADED&&!p,f=h===Pc.REPRESENTATION_SELECTED&&!p,v=i.autoVideoTrackSwitching.getState(),S=i.videoTrack.getState(),b=null===(s=this.videoTracks.find((({track:{id:t}})=>t===S)))||void 0===s?void 0:s.track,g=e.currentVideoTrack$.getValue(),y=Ju(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),k=Math.max(b&&!v&&null!==(a=null===(r=this.audioRepresentations.get(b.id))||void 0===r?void 0:r.bitrate)&&void 0!==a?a:0,g&&null!==(u=null===(o=this.audioRepresentations.get(g.id))||void 0===o?void 0:o.bitrate)&&void 0!==u?u:0),w=Nu(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),reserve:k,forwardBufferHealth:E,current:g,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),P=v?null!=w?w:b:null!=b?b:w;if(i.autoVideoTrackSwitching.getTransition()&&(i.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),m){const e=P&&(null===(d=this.videoTracks.find((({track:t})=>t===P)))||void 0===d?void 0:d.representation);t.assertNonNullable(e),this.player.initRepresentations(e.id,null===(l=this.audioRepresentations.get(e.id))||void 0===l?void 0:l.id)}else if(f){const t=P&&(null===(c=this.videoTracks.find((({track:t})=>t===P)))||void 0===c?void 0:c.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(Zl.VIDEO,t.id).catch(n),e&&this.player.switchRepresentation(Zl.AUDIO,e.id).catch(n)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}prepare(){return Fo(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=xc(t);if(s){this.videoTracks.push({track:s,representation:t});const r=Nc(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(){Bu(this.video).then((t=>{t||(this.videoState.setState($c.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const _c={};var Rc;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Rc||(Rc={}));const Ic=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class Cc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Rc.INITIALIZING),this.textTracksManager=new du,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!==Rc.INITIALIZING)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&this.seek(r.position),i){case exports.PlaybackState.STOPPED:switch(e){case Rc.STOPPED:break;case Rc.READY:case Rc.PLAYING:case Rc.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Rc.PLAYING:break;case Rc.STOPPED:this.prepare();break;case Rc.READY:case Rc.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Rc.PAUSED:break;case Rc.STOPPED:this.prepare();break;case Rc.READY:this.videoState.setState(Rc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Rc.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=lu(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Du(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},s=window.setTimeout((()=>e('timeout')),5e3);Ao(Promise.resolve().then((function(){return i(require('hls.js'))})).then((e=>{t||(_c.Hls=e.default,_c.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(_c.Hls,'hls.js not loaded'),this.hls=new _c.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Rc.STOPPED)}subscribe(){t.assertNonNullable(_c.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=t=>{i.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},r=vu(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,i.position$),a(r.durationChange$,i.duration$),a(r.ended$,i.endedEvent$),a(r.looped$,i.loopedEvent$),a(r.error$,i.error$),a(r.isBuffering$,i.isBuffering$),a(r.currentBuffer$,i.currentBuffer$),a(r.firstBytes$,i.firstBytesEvent$),a(r.firstFrame$,i.firstFrameEvent$),a(r.seeked$,i.seekedEvent$),this.subscription.add(nu(this.video,e.isLooped,s)),this.subscription.add(ou(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ic(this.hls,_c.Events.ERROR).subscribe((t=>{var e;t.fatal&&i.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(e=t.err)||void 0===e?void 0:e.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Rc.PLAYING),Do(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Rc.PAUSED),Do(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Rc.READY&&this.videoState.setState(Rc.READY),this.videoState.getState()===Rc.PLAYING&&this.playIfAllowed()}),s)),a(Ic(this.hls,_c.Events.MANIFEST_PARSED).pipe(t.map((({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=Ou(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:Lo({width:a,height:n});if(!o)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,d={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:u};return this.trackLevels.set(r,{track:d,level:e}),t.push(d),t}),[])))),i.availableVideoTracks$),a(Ic(this.hls,_c.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>Du(t)))),i.hostname$),this.subscription.add(au(e.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const n=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},o=Ic(this.hls,_c.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>n(this.hls.levels[t]))));o.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(au(e.videoTrack,(()=>{var t;return null===(t=n(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const r=this.hls.levels.indexOf(s),a=this.hls.currentLevel,n=this.hls.levels[a];!n||s.bitrate>n.bitrate?this.hls.nextLevel=r:(this.hls.loadLevel=r,this.hls.loadLevel=r)}),{changed$:o.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),a(r.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(Rc.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return Fo(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(Rc.PLAYING);(yield Bu(this.video))||(this.videoState.setState(Rc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(Rc.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(Rc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Lc=t=>{let e=null;if(t.QUALITY&&(e=Ou(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=Lo({width:i,height:s})}return null!=e?e:null},Oc=(t,e=t)=>Fo(void 0,void 0,void 0,(function*(){var i;const s=yield Wo(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=Ql(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,u=Lc(n);let d;n.BANDWIDTH&&(d=parseInt(n.BANDWIDTH,10)/1e3||void 0),!d&&n['AVERAGE-BANDWIDTH']&&(d=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const l=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 h=new URL(r[++t],e).toString();u&&a.push({id:o,quality:u,url:h,bandwidth:d,size:c,fps:l})}return a}));var Bc,Mc,Vc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Bc||(Bc={}));class Fc{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new Bo(Bc.STOPPED),this.textTracksManager=new du,this.manifests$=new t.ValueSubject([]),this.liveOffset=new cu,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Bc.STOPPED&&(this.videoState.startTransitionTo(Bc.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(Bc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===Bc.STOPPED)return this.videoState.startTransitionTo(Bc.READY),void this.prepare();if(r||a){const t=this.videoState.getState();return this.videoState.setState(Bc.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(n.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested)return this.videoState.startTransitionTo(Bc.READY),this.seek(n.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(e){case Bc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Bc.PAUSED),this.liveOffset.pause(),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Bc.PLAYING),this.playIfAllowed()));case Bc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Bc.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Bc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Bc.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==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Bc.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=lu(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),Oc(No(this.params.source.url),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.params.output.isLive$.next(!0),this.params.output.hostname$.next(Du(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i: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 u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:t})},r=vu(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(ou(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Bc.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Bc.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Bc.READY&&this.videoState.setState(Bc.READY),this.videoState.getState()===Bc.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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(Du(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Bc.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&e.state===l.Requested&&this.seek(e.position)}),s)),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)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=No(e.url,this.liveOffset.getTotalOffset());var s;this.video.setAttribute('src',i),this.video.load(),(s=i,Fo(void 0,void 0,void 0,(function*(){const t=yield Wo(s,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}playIfAllowed(){Bu(this.video).then((t=>{t||(this.videoState.setState(Bc.PAUSED),this.liveOffset.pause(),Do(this.params.desiredState.playbackState,exports.PlaybackState.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'}(Mc||(Mc={}));class Uc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Mc.STOPPED),this.textTracksManager=new du,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Mc.STOPPED&&(this.videoState.startTransitionTo(Mc.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(Mc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===Mc.STOPPED)return this.videoState.startTransitionTo(Mc.READY),void this.prepare();if(r||a){const t=this.videoState.getState();this.videoState.setState(Mc.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(n.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested&&this.seek(n.position),e){case Mc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Mc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Mc.PLAYING),this.playIfAllowed()));case Mc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Mc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Mc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Mc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Mc.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=lu(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Du(this.params.source.url)),Oc(this.params.source.url).then((t=>{this.manifests$.next([i,...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 u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:t})},r=vu(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(nu(this.video,i.isLooped,s)),this.subscription.add(ou(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Mc.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Mc.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Mc.READY&&this.videoState.setState(Mc.READY),this.videoState.getState()===Mc.PLAYING&&this.playIfAllowed()}),s).add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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(Du(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Mc.CHANGING_MANIFEST&&this.videoState.setState(i.to),e.state===l.Requested&&this.seek(e.position)}),s))),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){Bu(this.video).then((t=>{t||(this.videoState.setState(Mc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.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'}(Vc||(Vc={}));class qc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Vc.STOPPED),this.trackUrls={},this.textTracksManager=new du,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Vc.STOPPED&&(this.videoState.startTransitionTo(Vc.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(Vc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(e===Vc.STOPPED)return this.videoState.startTransitionTo(Vc.READY),void this.prepare();if(r){const{currentTime:t}=this.video;return this.prepare(),void(a.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&this.seek(a.position),e){case Vc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Vc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Vc.PLAYING),this.playIfAllowed()));case Vc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Vc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Vc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Vc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=lu(e.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:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:t})},r=vu(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(nu(this.video,i.isLooped,s)),this.subscription.add(ou(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Vc.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Vc.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===Vc.READY&&this.videoState.setState(Vc.READY);const i=this.params.desiredState.videoTrack.getTransition();i&&t.isNonNullable(i.to)&&(this.params.desiredState.videoTrack.setState(i.to),this.params.output.currentVideoTrack$.next(this.trackUrls[i.to].track)),this.videoState.getState()===Vc.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:r}=this.trackUrls[s];t.assertNonNullable(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=su(r)),this.video.setAttribute('src',r),this.video.load(),this.params.output.hostname$.next(Du(r))}playIfAllowed(){Bu(this.video).then((t=>{t||(this.videoState.setState(Vc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}class jc{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)}}var Hc,Gc,Yc,Qc,zc,Wc,Jc,Kc,Xc,Zc,th,eh,ih,sh,rh,ah,nh;const oh=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),uh=(null===(Hc=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Hc?void 0:Hc.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),dh=document.createElement('video'),lh={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Yc=null===(Gc=window.SourceBuffer)||void 0===Gc?void 0:Gc.prototype)||void 0===Yc?void 0:Yc.appendBuffer)),hls:Boolean((null===(Qc=dh.canPlayType)||void 0===Qc?void 0:Qc.call(dh,'application/x-mpegurl'))||(null===(zc=dh.canPlayType)||void 0===zc?void 0:zc.call(dh,'vnd.apple.mpegURL')))},ch={mp4:Boolean(null===(Wc=dh.canPlayType)||void 0===Wc?void 0:Wc.call(dh,'video/mp4')),webm:Boolean(null===(Jc=dh.canPlayType)||void 0===Jc?void 0:Jc.call(dh,'video/webm'))},hh={h264:Boolean(null===(Xc=null===(Kc=window.MediaSource)||void 0===Kc?void 0:Kc.isTypeSupported)||void 0===Xc?void 0:Xc.call(Kc,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(th=null===(Zc=window.MediaSource)||void 0===Zc?void 0:Zc.isTypeSupported)||void 0===th?void 0:th.call(Zc,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(ih=null===(eh=window.MediaSource)||void 0===eh?void 0:eh.isTypeSupported)||void 0===ih?void 0:ih.call(eh,'video/webm; codecs="vp9"')),aac:Boolean(null===(rh=null===(sh=window.MediaSource)||void 0===sh?void 0:sh.isTypeSupported)||void 0===rh?void 0:rh.call(sh,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(nh=null===(ah=window.MediaSource)||void 0===ah?void 0:ah.isTypeSupported)||void 0===nh?void 0:nh.call(ah,'audio/webm; codecs="opus"'))},ph=(hh.h264||hh.h265)&&hh.aac,mh=!oh,fh=uh||oh,vh=!lh.hls||!fh;const Sh=3e4,bh=18e4,gh=3,yh=100,Th={cacheDuration:12e4},Eh={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},kh={maxPausedTime:3e4},wh={maxPausedTime:3e4};class Ph{constructor(e){this.current$=new t.ValueSubject({type:void 0}),this.providerError$=new t.Subject,this.noAvailableProvidersError$=new t.Subject,this.providerOutput={position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),volume$:new t.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new t.ValueSubject(void 0),availableVideoTracks$:new t.ValueSubject([]),autoVideoTrackLimitingAvailable$:new t.ValueSubject(!1),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),error$:new t.Subject,willSeekEvent$:new t.Subject,seekedEvent$:new t.Subject,loopedEvent$:new t.Subject,endedEvent$:new t.Subject,firstBytesEvent$:new t.Subject,firstFrameEvent$:new t.Subject,isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),element$:new t.ValueSubject(void 0)},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:i}=this.params.tuning,s=i.length?[...e.screenFormatsPriority.filter((t=>!i.includes(t))),...e.screenFormatsPriority.filter((t=>i.includes(t)))]:e.screenFormatsPriority;this.screenFormatsIterator=new jc(s.filter((i=>t.isNonNullable(e.sources[i]))).filter((e=>{switch(e){case exports.VideoFormat.DASH:return lh.mse&&ch.mp4&&ph&&mh;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return lh.mse&&ch.mp4&&ph;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return lh.mse&&ch.webm&&hh.vp9&&hh.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return lh.mse&&ch.mp4&&ph;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return lh.hls&&ch.mp4&&fh;case exports.VideoFormat.HLS_JS:return lh.mse&&ch.mp4&&ph&&vh;case exports.VideoFormat.MPEG:return ch.mp4;default:return t.assertNever(e)}}))),this.chromecastFormatsIterator=new jc(e.chromecastFormatsPriority.filter((i=>t.isNonNullable(e.sources[i]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),i=this.chooseFormat(e);if(t.isNullable(i))return void this.handleNoFormatsError(e);let s;try{s=this.createProvider(e,i)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const e=this.current$.getValue().destination;t.assertNonNullable(e,'No current provider'),this.skipFormat(e),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!==l.None;this.params.desiredState.seekState.setState({state:l.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case n.SCREEN:return this.createScreenProvider(i);case n.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:r}=this.params,a=this.providerOutput;switch(e){case exports.VideoFormat.DASH:{const n=i[e];return t.assertNonNullable(n),new Xl({container:s,source:n,desiredState:r,output:a,config:Th,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const n=i[e];return t.assertNonNullable(n),new Dc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const n=i[e];return t.assertNonNullable(n),new Lu({container:s,source:n,desiredState:r,output:a,format:e,config:wh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const n=i[e];return t.assertNonNullable(n),new Uc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const n=i[e];return t.assertNonNullable(n),new Fc({container:s,source:n,desiredState:r,output:a,config:kh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const n=i[e];return t.assertNonNullable(n),new Cc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const n=i[e];return t.assertNonNullable(n),new qc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const n=i[e];return t.assertNonNullable(n),new zu({container:s,source:n,desiredState:r,output:a,config:Eh,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(o),new Vo({connection:o,meta:a,container:s,source:i,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?n.CHROMECAST:n.SCREEN}chooseFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case n.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.next();case n.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case n.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case n.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}initProviderErrorHandling(){let e=[],i=0;const s=new t.Subscription;var r;return s.add(t.merge(this.providerOutput.error$,(r={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Sh,position$:this.providerOutput.position$,providerChanged$:this.current$},new t.Observable((e=>{const i=new t.Subscription,s=t.timeout(r.maxTransitionInterval),a=new t.ValueSubject(void 0);t.merge(r.desiredPlaybackState$.stateChangeStarted$.pipe(t.mapTo(s)),r.desiredPlaybackState$.stateChangeEnded$.pipe(t.mapTo(void 0)),r.providerChanged$.pipe(t.map((()=>a.getValue())))).subscribe(a);const n=new t.Subscription;return i.add(n),i.add(a.subscribe((t=>{n.unsubscribe(),t&&n.add(t.subscribe(e))}))),i}))).pipe(t.mapTo({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),s.add(this.providerError$.pipe(t.throttle(yh,{leading:!1,trailing:!0})).subscribe((()=>{const s=Date.now();this.current$.getValue().destination===n.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):t.isNonNullable(e[i])&&s<e[i]+bh?(e=[],this.switchToNextProvider()):(e[i]=s,this.reinitProvider()),i=(i+1)%gh}))),s}}const $h=(t,e,i)=>i*e+(1-i)*t;class Ah{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.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new $u(`raw_${s}`),this.smoothedSeries$=new $u(`smoothed_${s}`),this.reportedSeries$=new $u(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let i=0,s=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(i+=Math.pow(this.pastMeasures[t]-this.smoothed,2),s++);i/=s;const r=Math.sqrt(i),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=$h(this.slow,e,this.params.emaAlphaSlow),this.fast=$h(this.fast,e,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||(t.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}var xh;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(xh||(xh={}));const Nh=new Map;let Dh=xh.RUNTIME;const _h=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(_h,'test'),localStorage.removeItem(_h),Dh=xh.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(_h),Dh=xh.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Dh=xh.RUNTIME}}})();const Rh=(e,i)=>{switch(Dh){case xh.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case xh.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case xh.RUNTIME:return void Nh.set(e,i);default:t.assertNever(Dh)}},Ih=window.navigator.connection,Ch=()=>{const e=null==Ih?void 0:Ih.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},Lh=()=>{const e=null==Ih?void 0:Ih.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},Oh=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Bh{constructor(e){var i,s;this.subscription=new t.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Bh.load('one_video_throughput')||(e.useBrowserEstimation?Ch():void 0)||5e3,a=null!==(s=null!==(i=Bh.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?Lh():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(r),this.rtt$=new t.ValueSubject(a),this.rttAdjustedThroughput$=new t.ValueSubject(Oh(r,a,e.rttPenaltyRequestSize)),this.throughput=new Ah({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Ah({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=Ch();e&&this.throughput.next(e);const i=Lh();t.isNonNullable(i)&&this.rtt.next(i)};Ih&&'onchange'in Ih&&this.subscription.add(t.fromEvent(Ih,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Rh('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Rh('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(t.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(t.map((({throughput:t,rtt:i})=>Oh(t,i,e.rttPenaltyRequestSize))),t.filter((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(e){let i=0,s=t.now();const r=new t.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:r.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}r.add(t.fromEvent(e,'loadend').subscribe((a=>{if(200===e.status){const e=a.loaded,r=t.now(),n=e-i,o=r-s;this.addRawSpeed(n,o,1)}this.concurrentDownloads.delete(e),r.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const r=t.now();let a=0,n=t.now();const o=t=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=({done:d,value:l})=>Fo(this,void 0,void 0,(function*(){d?(this.addRawSpeed(s,t.now()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&t.now()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,t.now()-n,this.concurrentDownloads.size),a=0,n=t.now()),yield null==i?void 0:i.read().then(u,o))}));this.concurrentDownloads.add(e),null==i||i.read().then(u,o)}addRawSpeed(t,e,i=1){if(Bh.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(e){var i;const s=(e=>{var i,s;switch(Dh){case xh.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case xh.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case xh.RUNTIME:return Nh.get(e);default:t.assertNever(Dh)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const Mh={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},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.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 Vh=(e=(t=>t))=>({playbackState:i,seekState:s,playbackAbort$:r,looped$:a,position$:n})=>new t.Observable((o=>{let u;const d=i.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),c=i.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),h=s.stateChangeEnded$.pipe(t.filter((({to:t})=>{var e,s;return t.state===l.Requested&&(null!==(s=null===(e=i.getTransition())||void 0===e?void 0:e.from)&&void 0!==s?s:i.getState())===exports.PlaybackState.PLAYING}))),p=s.stateChangeEnded$.pipe(t.filter((({from:t,to:e})=>{var s,r;return t.state===l.Applying&&e.state===l.None&&(null!==(r=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:i.getState())===exports.PlaybackState.PLAYING}))),m=t.merge(d,p).pipe(t.map((()=>e(n.getValue())))),f=t.merge(t.merge(c,h,r).pipe(t.map((()=>e(n.getValue())))),a.pipe(t.map(e)));return(new t.Subscription).add(m.subscribe((t=>{u=e(t)}))).add(f.subscribe((i=>{const s=e(i);if(t.isNullable(u)||u===s)return;const r={start:u,end:s};u=void 0,o.next(r)})))})),Fh=Vh((t=>t)),Uh=Vh((t=>Math.round(1e3*t)+Date.now())),qh={[n.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[n.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return t.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return t.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return t.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return t.ValueSubject}}),exports.Player=class{constructor(e={}){if(this.subscription=new t.Subscription,this.logger=new t.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Bo(exports.PlaybackState.STOPPED),seekState:new Bo({state:l.None}),volume:new Bo({volume:1,muted:!1}),videoTrack:new Bo(void 0),autoVideoTrackSwitching:new Bo(!0),autoVideoTrackLimits:new Bo({}),isLooped:new Bo(!1),externalTextTracks:new Bo([]),currentTextTrack:new Bo(void 0),textTrackCuesSettings:new Bo({})},this.info={playbackState$:new t.ValueSubject(exports.PlaybackState.STOPPED),position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),muted$:new t.ValueSubject(!1),volume$:new t.ValueSubject(1),availableQualities$:new t.ValueSubject([]),availableQualitiesFps$:new t.ValueSubject({}),currentQuality$:new t.ValueSubject(void 0),isAutoQualityEnabled$:new t.ValueSubject(!0),autoQualityLimitingAvailable$:new t.ValueSubject(!1),autoQualityLimits$:new t.ValueSubject({}),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),isStalled$:new t.ValueSubject(!1),isEnded$:new t.ValueSubject(!1),isLooped$:new t.ValueSubject(!1),isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),currentFormat$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),throughputEstimation$:new t.ValueSubject(void 0),rttEstimation$:new t.ValueSubject(void 0),videoBitrate$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),chromecastState$:new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new t.ValueSubject(void 0),intrinsicVideoSize$:new t.ValueSubject(void 0)},this.events={started$:new t.Subject,startAttempt$:new t.Subject,willPause$:new t.Subject,willResume$:new t.Subject,willDestruct$:new t.Subject,watchCoverageRecord$:new t.Subject,watchCoverageLive$:new t.Subject,managedError$:new t.Subject,fatalError$:new t.Subject,ended$:new t.Subject,looped$:new t.Subject,seeked$:new t.Subject,willSeek$:new t.Subject,firstBytes$:new t.Subject,firstFrame$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:wu},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Mh)){const s=Mh[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})(e),this.chromecastInitializer=new c({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bh(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(e){var i,s;return this.config=e,this.domContainer=(e=>{const i='string'==typeof e.container?document.getElementById(e.container):e.container;return t.assertNonNullable(i,`Wrong container or containerId {${e.container}}`),i})(e),this.chromecastInitializer.contentId=null===(i=e.meta)||void 0===i?void 0:i.videoId,this.providerContainer=new Ph({screenFormatsPriority:[...qh[n.SCREEN].live,...qh[n.SCREEN].vod],chromecastFormatsPriority:[...qh[n.CHROMECAST].live,...qh[n.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},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()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PAUSED&&t.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.STOPPED&&t.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:l.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()===exports.ChromecastState.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()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.availableVideoTracks$.getValue();i.length||(this.explicitInitialQuality=e);const s=i.find((t=>t.quality===e));return s&&this.desiredState.videoTrack.startTransitionTo(s.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(){t.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(e))return this.info.position$.getValue();const i=this.desiredState.seekState.getState(),s=i.state===l.None?void 0:i.position;return t.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.autoQualityLimits$));const e=new t.Subscription;this.subscription.add(e),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{e.unsubscribe(),e.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING||t.to===exports.PlaybackState.PAUSED)),t.debounce(0),t.once()).subscribe((t=>{const e=t.to===exports.PlaybackState.PLAYING,i=this.info.muted$.getValue(),s=e?i?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.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 exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===l.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},t),{state:l.Applying})):this.events.managedError$.next({id:`WillSeekIn${t.state}`,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===l.Applying&&(this.desiredState.seekState.setState({state:l.None}),this.events.seeked$.next())}))).add(e.current$.pipe(t.map((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(t.map((t=>t.destination)),t.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(t.map((t=>t.map((({quality:t})=>t)).sort(((t,e)=>Oo(t)?1:Oo(e)?-1:Ro(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(t.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.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(t.map((t=>t.muted)),t.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.volume)),t.filterChanged()).subscribe(this.info.volume$)).add((({seekState:e,position$:i})=>t.merge(e.stateChangeEnded$.pipe(t.map((({to:t})=>{var e;return t.state===l.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>e.getState().state===l.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(t.merge(e.providerOutput.endedEvent$.pipe(t.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(t.mapTo(!1))).pipe(t.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(t.map((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$.subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let r=0;const a=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),r=i.getValue()||s.getValue();return t&&!r})),t.filterChanged());this.subscription.add(a.subscribe((t=>{t?r=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})));const n=new t.Subscription;this.subscription.add(n);const o=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),n.unsubscribe(),e){case!0:n.add(Uh({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:n.add(Fh({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(t.map((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const i=new t.Subscription;this.subscription.add(i),this.subscription.add(e.current$.pipe(t.filterChanged(((t,e)=>t.provider===e.provider))).subscribe((()=>{i.unsubscribe(),i.add(e.providerOutput.availableVideoTracks$.pipe(t.filter((t=>t.length>0)),t.once()).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=Nu(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(t.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(t.map((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 e;const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput;t.assertNonNullable(this.providerContainer),t.assertNonNullable(i),ku={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Eu=t})),this.providerContainer.current$.subscribe((({type:t})=>Pu('provider',t))),i.duration$.subscribe((t=>Pu('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>Pu('tracks',t))),this.events.fatalError$.subscribe(new $u('fatalError')),this.events.managedError$.subscribe(new $u('managedError')),i.position$.subscribe(new $u('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new $u('quality')),i.currentBuffer$.subscribe(new $u('buffer')),i.isBuffering$.subscribe(new $u('isBuffering'))].forEach((t=>this.subscription.add(t))),Pu('codecs',Object.keys(hh).filter((t=>hh[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.60';
|
|
6
|
+
'use strict';Object.defineProperty(exports,'__esModule',{value:!0});var t=require('@vkontakte/videoplayer-shared/es2015.cjs.js');function e(t){return t&&'object'==typeof t&&'default'in t?t:{default:t}}function i(t){if(t&&t.__esModule)return t;var e=Object.create(null);return t&&Object.keys(t).forEach((function(i){if('default'!==i){var s=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,s.get?s:{enumerable:!0,get:function(){return t[i]}})}})),e.default=t,Object.freeze(e)}var s=e(require('lodash/debounce'));var r,a,n,o,u,d,l;exports.PlaybackState=void 0,(r=exports.PlaybackState||(exports.PlaybackState={})).STOPPED='stopped',r.PLAYING='playing',r.PAUSED='paused',exports.VideoFormat=void 0,(a=exports.VideoFormat||(exports.VideoFormat={})).MPEG='MPEG',a.DASH='DASH',a.DASH_SEP='DASH_SEP',a.DASH_SEP_VK='DASH_SEP_VK',a.DASH_WEBM='DASH_WEBM',a.DASH_WEBM_VK='DASH_WEBM_VK',a.DASH_ONDEMAND='DASH_ONDEMAND',a.DASH_LIVE='DASH_LIVE',a.DASH_LIVE_WEBM='DASH_LIVE_WEBM',a.HLS='HLS',a.HLS_ONDEMAND='HLS_ONDEMAND',a.HLS_JS='HLS_JS',a.HLS_LIVE='HLS_LIVE',function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(n||(n={})),exports.ChromecastState=void 0,(o=exports.ChromecastState||(exports.ChromecastState={})).NOT_AVAILABLE='NOT_AVAILABLE',o.AVAILABLE='AVAILABLE',o.CONNECTING='CONNECTING',o.CONNECTED='CONNECTED',exports.StartStatus=void 0,(u=exports.StartStatus||(exports.StartStatus={})).SuccessWithSound='success_with_sound',u.SuccessWithoutSound='success_without_sound',u.Failed='failed',exports.HttpConnectionType=void 0,(d=exports.HttpConnectionType||(exports.HttpConnectionType={})).HTTP1='http1',d.HTTP2='http2',d.QUIC='quic',function(t){t.None='none',t.Requested='requested',t.Applying='applying'}(l||(l={}));class c{constructor(e){var i;this.connection$=new t.ValueSubject(void 0),this.castState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.errorEvent$=new t.Subject,this.realCastState$=new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const s='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${s}`}),e.isDisabled||!s)return;var r;t.isNonNullable(null===(i=window.chrome)||void 0===i?void 0:i.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(r='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',r),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(){t.isNonNullable(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(e){const i=this.connection$.getValue();t.isNullable(i)||(i.remotePlayer.volumeLevel=e,i.remotePlayerController.setVolumeLevel())}setMuted(e){const i=this.connection$.getValue();t.isNullable(i)||e!==i.remotePlayer.isMuted&&i.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const e=new cast.framework.RemotePlayer,i=new cast.framework.RemotePlayerController(e),s=cast.framework.CastContext.getInstance();this.subscription.add(t.fromEvent(s,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((e=>{var i,r;switch(e.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(r=null===(i=s.getCurrentSession())||void 0===i?void 0:i.getMediaSession())||void 0===r?void 0:r.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 t.assertNever(e.sessionState)}}))).add(t.merge(t.fromEvent(s,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(t.tap((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),t.map((t=>t.castState))),t.observableFrom([s.getCastState()])).pipe(t.filterChanged(),t.map(h),t.tap((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((r=>{var a;const n=r===exports.ChromecastState.CONNECTED,o=t.isNonNullable(this.connection$.getValue());if(n&&!o){const r=s.getCurrentSession();t.assertNonNullable(r);const n=r.getCastDevice(),o=null===(a=r.getMediaSession())||void 0===a?void 0:a.media.contentId;(t.isNullable(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:e,remotePlayerController:i,session:r,castDevice:n}))}else!n&&o&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(r===exports.ChromecastState.CONNECTED?t.isNonNullable(this.connection$.getValue())?exports.ChromecastState.CONNECTED:exports.ChromecastState.AVAILABLE:r)})))}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 h=e=>{switch(e){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return exports.ChromecastState.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return exports.ChromecastState.AVAILABLE;case cast.framework.CastState.CONNECTING:return exports.ChromecastState.CONNECTING;case cast.framework.CastState.CONNECTED:return exports.ChromecastState.CONNECTED;default:return t.assertNever(e)}};var p='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},m=function(t){return t&&t.Math==Math&&t},f=m('object'==typeof globalThis&&globalThis)||m('object'==typeof window&&window)||m('object'==typeof self&&self)||m('object'==typeof p&&p)||function(){return this}()||Function('return this')(),v=function(t){try{return!!t()}catch(t){return!0}},S=!v((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),b=S,g=Function.prototype,y=g.apply,T=g.call,E='object'==typeof Reflect&&Reflect.apply||(b?T.bind(y):function(){return T.apply(y,arguments)}),k=S,w=Function.prototype,P=w.bind,$=w.call,A=k&&P.bind($,$),x=k?function(t){return t&&A(t)}:function(t){return t&&function(){return $.apply(t,arguments)}},N=function(t){return'function'==typeof t},D={},_=!v((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),R=S,I=Function.prototype.call,C=R?I.bind(I):function(){return I.apply(I,arguments)},L={},O={}.propertyIsEnumerable,B=Object.getOwnPropertyDescriptor,M=B&&!O.call({1:2},1);L.f=M?function(t){var e=B(this,t);return!!e&&e.enumerable}:O;var V,F,U=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},j=x,q=j({}.toString),H=j(''.slice),G=function(t){return H(q(t),8,-1)},Y=x,Q=v,z=G,W=f.Object,J=Y(''.split),K=Q((function(){return!W('z').propertyIsEnumerable(0)}))?function(t){return'String'==z(t)?J(t,''):W(t)}:W,X=f.TypeError,Z=function(t){if(null==t)throw X('Can\'t call method on '+t);return t},tt=K,et=Z,it=function(t){return tt(et(t))},st=N,rt=function(t){return'object'==typeof t?null!==t:st(t)},at={},nt=at,ot=f,ut=N,dt=function(t){return ut(t)?t:void 0},lt=function(t,e){return arguments.length<2?dt(nt[t])||dt(ot[t]):nt[t]&&nt[t][e]||ot[t]&&ot[t][e]},ct=x({}.isPrototypeOf),ht=lt('navigator','userAgent')||'',pt=f,mt=ht,ft=pt.process,vt=pt.Deno,St=ft&&ft.versions||vt&&vt.version,bt=St&&St.v8;bt&&(F=(V=bt.split('.'))[0]>0&&V[0]<4?1:+(V[0]+V[1])),!F&&mt&&(!(V=mt.match(/Edge\/(\d+)/))||V[1]>=74)&&(V=mt.match(/Chrome\/(\d+)/))&&(F=+V[1]);var gt=F,yt=gt,Tt=v,Et=!!Object.getOwnPropertySymbols&&!Tt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&yt&&yt<41})),kt=Et&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,wt=lt,Pt=N,$t=ct,At=kt,xt=f.Object,Nt=At?function(t){return'symbol'==typeof t}:function(t){var e=wt('Symbol');return Pt(e)&&$t(e.prototype,xt(t))},Dt=f.String,_t=function(t){try{return Dt(t)}catch(t){return'Object'}},Rt=N,It=_t,Ct=f.TypeError,Lt=function(t){if(Rt(t))return t;throw Ct(It(t)+' is not a function')},Ot=Lt,Bt=function(t,e){var i=t[e];return null==i?void 0:Ot(i)},Mt=C,Vt=N,Ft=rt,Ut=f.TypeError,jt={exports:{}},qt=f,Ht=Object.defineProperty,Gt=function(t,e){try{Ht(qt,t,{value:e,configurable:!0,writable:!0})}catch(i){qt[t]=e}return e},Yt=f['__core-js_shared__']||Gt('__core-js_shared__',{}),Qt=Yt;(jt.exports=function(t,e){return Qt[t]||(Qt[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 zt=Z,Wt=f.Object,Jt=function(t){return Wt(zt(t))},Kt=Jt,Xt=x({}.hasOwnProperty),Zt=Object.hasOwn||function(t,e){return Xt(Kt(t),e)},te=x,ee=0,ie=Math.random(),se=te(1..toString),re=function(t){return'Symbol('+(void 0===t?'':t)+')_'+se(++ee+ie,36)},ae=f,ne=jt.exports,oe=Zt,ue=re,de=Et,le=kt,ce=ne('wks'),he=ae.Symbol,pe=he&&he.for,me=le?he:he&&he.withoutSetter||ue,fe=function(t){if(!oe(ce,t)||!de&&'string'!=typeof ce[t]){var e='Symbol.'+t;de&&oe(he,t)?ce[t]=he[t]:ce[t]=le&&pe?pe(e):me(e)}return ce[t]},ve=C,Se=rt,be=Nt,ge=Bt,ye=function(t,e){var i,s;if('string'===e&&Vt(i=t.toString)&&!Ft(s=Mt(i,t)))return s;if(Vt(i=t.valueOf)&&!Ft(s=Mt(i,t)))return s;if('string'!==e&&Vt(i=t.toString)&&!Ft(s=Mt(i,t)))return s;throw Ut('Can\'t convert object to primitive value')},Te=fe,Ee=f.TypeError,ke=Te('toPrimitive'),we=function(t,e){if(!Se(t)||be(t))return t;var i,s=ge(t,ke);if(s){if(void 0===e&&(e='default'),i=ve(s,t,e),!Se(i)||be(i))return i;throw Ee('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),ye(t,e)},Pe=Nt,$e=function(t){var e=we(t,'string');return Pe(e)?e:e+''},Ae=rt,xe=f.document,Ne=Ae(xe)&&Ae(xe.createElement),De=function(t){return Ne?xe.createElement(t):{}},_e=De,Re=!_&&!v((function(){return 7!=Object.defineProperty(_e('div'),'a',{get:function(){return 7}}).a})),Ie=_,Ce=C,Le=L,Oe=U,Be=it,Me=$e,Ve=Zt,Fe=Re,Ue=Object.getOwnPropertyDescriptor;D.f=Ie?Ue:function(t,e){if(t=Be(t),e=Me(e),Fe)try{return Ue(t,e)}catch(t){}if(Ve(t,e))return Oe(!Ce(Le.f,t,e),t[e])};var je=v,qe=N,He=/#|\.prototype\./,Ge=function(t,e){var i=Qe[Ye(t)];return i==We||i!=ze&&(qe(e)?je(e):!!e)},Ye=Ge.normalize=function(t){return String(t).replace(He,'.').toLowerCase()},Qe=Ge.data={},ze=Ge.NATIVE='N',We=Ge.POLYFILL='P',Je=Ge,Ke=Lt,Xe=S,Ze=x(x.bind),ti=function(t,e){return Ke(t),void 0===e?t:Xe?Ze(t,e):function(){return t.apply(e,arguments)}},ei={},ii=_&&v((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),si=f,ri=rt,ai=si.String,ni=si.TypeError,oi=function(t){if(ri(t))return t;throw ni(ai(t)+' is not an object')},ui=_,di=Re,li=ii,ci=oi,hi=$e,pi=f.TypeError,mi=Object.defineProperty,fi=Object.getOwnPropertyDescriptor;ei.f=ui?li?function(t,e,i){if(ci(t),e=hi(e),ci(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=fi(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 mi(t,e,i)}:mi:function(t,e,i){if(ci(t),e=hi(e),ci(i),di)try{return mi(t,e,i)}catch(t){}if('get'in i||'set'in i)throw pi('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var vi=ei,Si=U,bi=_?function(t,e,i){return vi.f(t,e,Si(1,i))}:function(t,e,i){return t[e]=i,t},gi=f,yi=E,Ti=x,Ei=N,ki=D.f,wi=Je,Pi=at,$i=ti,Ai=bi,xi=Zt,Ni=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 yi(t,this,arguments)};return e.prototype=t.prototype,e},Di=function(t,e){var i,s,r,a,n,o,u,d,l=t.target,c=t.global,h=t.stat,p=t.proto,m=c?gi:h?gi[l]:(gi[l]||{}).prototype,f=c?Pi:Pi[l]||Ai(Pi,l,{})[l],v=f.prototype;for(r in e)i=!wi(c?r:l+(h?'.':'#')+r,t.forced)&&m&&xi(m,r),n=f[r],i&&(o=t.noTargetGet?(d=ki(m,r))&&d.value:m[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(u=t.bind&&i?$i(a,gi):t.wrap&&i?Ni(a):p&&Ei(a)?Ti(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Ai(u,'sham',!0),Ai(f,r,u),p&&(xi(Pi,s=l+'Prototype')||Ai(Pi,s,{}),Ai(Pi[s],r,a),t.real&&v&&!v[r]&&Ai(v,r,a)))},_i=f.Promise,Ri=bi,Ii=function(t,e,i,s){s&&s.enumerable?t[e]=i:Ri(t,e,i)},Ci=Ii,Li=f,Oi=(Li.String,Li.TypeError,x);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=Oi(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var Bi={};Bi[fe('toStringTag')]='z';var Mi='[object z]'===String(Bi),Vi=f,Fi=Mi,Ui=N,ji=G,qi=fe('toStringTag'),Hi=Vi.Object,Gi='Arguments'==ji(function(){return arguments}()),Yi=Fi?ji: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=Hi(t),qi))?i:Gi?ji(e):'Object'==(s=ji(e))&&Ui(e.callee)?'Arguments':s},Qi=Yi,zi=Mi?{}.toString:function(){return'[object '+Qi(this)+']'},Wi=Mi,Ji=ei.f,Ki=bi,Xi=Zt,Zi=zi,ts=fe('toStringTag'),es=function(t,e,i,s){if(t){var r=i?t:t.prototype;Xi(r,ts)||Ji(r,ts,{configurable:!0,value:e}),s&&!Wi&&Ki(r,'toString',Zi)}},is=lt,ss=ei,rs=_,as=fe('species'),ns=ct,os=f.TypeError,us=N,ds=Yt,ls=x(Function.toString);us(ds.inspectSource)||(ds.inspectSource=function(t){return ls(t)});var cs=ds.inspectSource,hs={},ps=hs,ms=fe('iterator'),fs=Array.prototype,vs=Math.ceil,Ss=Math.floor,bs=function(t){var e=+t;return e!=e||0===e?0:(e>0?Ss:vs)(e)},gs=bs,ys=Math.min,Ts=function(t){return t>0?ys(gs(t),9007199254740991):0},Es=function(t){return Ts(t.length)},ks=Yi,ws=Bt,Ps=hs,$s=fe('iterator'),As=function(t){if(null!=t)return ws(t,$s)||ws(t,'@@iterator')||Ps[ks(t)]},xs=C,Ns=Lt,Ds=oi,_s=_t,Rs=As,Is=f.TypeError,Cs=C,Ls=oi,Os=Bt,Bs=ti,Ms=C,Vs=oi,Fs=_t,Us=function(t){return void 0!==t&&(ps.Array===t||fs[ms]===t)},js=Es,qs=ct,Hs=function(t,e){var i=arguments.length<2?Rs(t):e;if(Ns(i))return Ds(xs(i,t));throw Is(_s(t)+' is not iterable')},Gs=As,Ys=function(t,e,i){var s,r;Ls(t);try{if(!(s=Os(t,'return'))){if('throw'===e)throw i;return i}s=Cs(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return Ls(s),i},Qs=f.TypeError,zs=function(t,e){this.stopped=t,this.result=e},Ws=zs.prototype,Js=function(t,e,i){var s,r,a,n,o,u,d,l=i&&i.that,c=!(!i||!i.AS_ENTRIES),h=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),m=Bs(e,l),f=function(t){return s&&Ys(s,'normal',t),new zs(!0,t)},v=function(t){return c?(Vs(t),p?m(t[0],t[1],f):m(t[0],t[1])):p?m(t,f):m(t)};if(h)s=t;else{if(!(r=Gs(t)))throw Qs(Fs(t)+' is not iterable');if(Us(r)){for(a=0,n=js(t);n>a;a++)if((o=v(t[a]))&&qs(Ws,o))return o;return new zs(!1)}s=Hs(t,r)}for(u=s.next;!(d=Ms(u,s)).done;){try{o=v(d.value)}catch(t){Ys(s,'throw',t)}if('object'==typeof o&&o&&qs(Ws,o))return o}return new zs(!1)},Ks=fe('iterator'),Xs=!1;try{var Zs=0,tr={next:function(){return{done:!!Zs++}},return:function(){Xs=!0}};tr[Ks]=function(){return this},Array.from(tr,(function(){throw 2}))}catch(t){}var er=x,ir=v,sr=N,rr=Yi,ar=cs,nr=function(){},or=[],ur=lt('Reflect','construct'),dr=/^\s*(?:class|function)\b/,lr=er(dr.exec),cr=!dr.exec(nr),hr=function(t){if(!sr(t))return!1;try{return ur(nr,or,t),!0}catch(t){return!1}},pr=function(t){if(!sr(t))return!1;switch(rr(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return cr||!!lr(dr,ar(t))}catch(t){return!0}};pr.sham=!0;var mr,fr,vr,Sr,br=!ur||ir((function(){var t;return hr(hr.call)||!hr(Object)||!hr((function(){t=!0}))||t}))?pr:hr,gr=_t,yr=f.TypeError,Tr=oi,Er=function(t){if(br(t))return t;throw yr(gr(t)+' is not a constructor')},kr=fe('species'),wr=function(t,e){var i,s=Tr(t).constructor;return void 0===s||null==(i=Tr(s)[kr])?e:Er(i)},Pr=lt('document','documentElement'),$r=x([].slice),Ar=f.TypeError,xr=/(?:ipad|iphone|ipod).*applewebkit/i.test(ht),Nr='process'==G(f.process),Dr=f,_r=E,Rr=ti,Ir=N,Cr=Zt,Lr=v,Or=Pr,Br=$r,Mr=De,Vr=function(t,e){if(t<e)throw Ar('Not enough arguments');return t},Fr=xr,Ur=Nr,jr=Dr.setImmediate,qr=Dr.clearImmediate,Hr=Dr.process,Gr=Dr.Dispatch,Yr=Dr.Function,Qr=Dr.MessageChannel,zr=Dr.String,Wr=0,Jr={};try{mr=Dr.location}catch(t){}var Kr=function(t){if(Cr(Jr,t)){var e=Jr[t];delete Jr[t],e()}},Xr=function(t){return function(){Kr(t)}},Zr=function(t){Kr(t.data)},ta=function(t){Dr.postMessage(zr(t),mr.protocol+'//'+mr.host)};jr&&qr||(jr=function(t){Vr(arguments.length,1);var e=Ir(t)?t:Yr(t),i=Br(arguments,1);return Jr[++Wr]=function(){_r(e,void 0,i)},fr(Wr),Wr},qr=function(t){delete Jr[t]},Ur?fr=function(t){Hr.nextTick(Xr(t))}:Gr&&Gr.now?fr=function(t){Gr.now(Xr(t))}:Qr&&!Fr?(Sr=(vr=new Qr).port2,vr.port1.onmessage=Zr,fr=Rr(Sr.postMessage,Sr)):Dr.addEventListener&&Ir(Dr.postMessage)&&!Dr.importScripts&&mr&&'file:'!==mr.protocol&&!Lr(ta)?(fr=ta,Dr.addEventListener('message',Zr,!1)):fr='onreadystatechange'in Mr('script')?function(t){Or.appendChild(Mr('script')).onreadystatechange=function(){Or.removeChild(this),Kr(t)}}:function(t){setTimeout(Xr(t),0)});var ea,ia,sa,ra,aa,na,oa,ua,da={set:jr,clear:qr},la=f,ca=/ipad|iphone|ipod/i.test(ht)&&void 0!==la.Pebble,ha=/web0s(?!.*chrome)/i.test(ht),pa=f,ma=ti,fa=D.f,va=da.set,Sa=xr,ba=ca,ga=ha,ya=Nr,Ta=pa.MutationObserver||pa.WebKitMutationObserver,Ea=pa.document,ka=pa.process,wa=pa.Promise,Pa=fa(pa,'queueMicrotask'),$a=Pa&&Pa.value;$a||(ea=function(){var t,e;for(ya&&(t=ka.domain)&&t.exit();ia;){e=ia.fn,ia=ia.next;try{e()}catch(t){throw ia?ra():sa=void 0,t}}sa=void 0,t&&t.enter()},Sa||ya||ga||!Ta||!Ea?!ba&&wa&&wa.resolve?((oa=wa.resolve(void 0)).constructor=wa,ua=ma(oa.then,oa),ra=function(){ua(ea)}):ya?ra=function(){ka.nextTick(ea)}:(va=ma(va,pa),ra=function(){va(ea)}):(aa=!0,na=Ea.createTextNode(''),new Ta(ea).observe(na,{characterData:!0}),ra=function(){na.data=aa=!aa}));var Aa=$a||function(t){var e={fn:t,next:void 0};sa&&(sa.next=e),ia||(ia=e,ra()),sa=e},xa={},Na=Lt,Da=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=Na(e),this.reject=Na(i)};xa.f=function(t){return new Da(t)};var _a=oi,Ra=rt,Ia=xa,Ca=function(t,e){if(_a(t),Ra(e)&&e.constructor===t)return e;var i=Ia.f(t);return(0,i.resolve)(e),i.promise},La=f,Oa=function(){this.head=null,this.tail=null};Oa.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 Ba,Ma,Va,Fa=Oa,Ua=N,ja=cs,qa=f.WeakMap,Ha=Ua(qa)&&/native code/.test(ja(qa)),Ga=jt.exports,Ya=re,Qa=Ga('keys'),za=function(t){return Qa[t]||(Qa[t]=Ya(t))},Wa={},Ja=Ha,Ka=f,Xa=x,Za=rt,tn=bi,en=Zt,sn=Yt,rn=za,an=Wa,nn=Ka.TypeError,on=Ka.WeakMap;if(Ja||sn.state){var un=sn.state||(sn.state=new on),dn=Xa(un.get),ln=Xa(un.has),cn=Xa(un.set);Ba=function(t,e){if(ln(un,t))throw new nn('Object already initialized');return e.facade=t,cn(un,t,e),e},Ma=function(t){return dn(un,t)||{}},Va=function(t){return ln(un,t)}}else{var hn=rn('state');an[hn]=!0,Ba=function(t,e){if(en(t,hn))throw new nn('Object already initialized');return e.facade=t,tn(t,hn,e),e},Ma=function(t){return en(t,hn)?t[hn]:{}},Va=function(t){return en(t,hn)}}var pn,mn,fn,vn={set:Ba,get:Ma,has:Va,enforce:function(t){return Va(t)?Ma(t):Ba(t,{})},getterFor:function(t){return function(e){var i;if(!Za(e)||(i=Ma(e)).type!==t)throw nn('Incompatible receiver, '+t+' required');return i}}},Sn='object'==typeof window,bn=Di,gn=f,yn=lt,Tn=C,En=_i,kn=function(t,e,i){for(var s in e)i&&i.unsafe&&t[s]?t[s]=e[s]:Ci(t,s,e[s],i);return t},wn=es,Pn=function(t){var e=is(t),i=ss.f;rs&&e&&!e[as]&&i(e,as,{configurable:!0,get:function(){return this}})},$n=Lt,An=N,xn=rt,Nn=function(t,e){if(ns(e,t))return t;throw os('Incorrect invocation')},Dn=cs,_n=Js,Rn=function(t,e){if(!e&&!Xs)return!1;var i=!1;try{var s={};s[Ks]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i},In=wr,Cn=da.set,Ln=Aa,On=Ca,Bn=function(t,e){var i=La.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},Mn=xa,Vn=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},Fn=Fa,Un=vn,jn=Je,qn=Sn,Hn=Nr,Gn=gt,Yn=fe('species'),Qn='Promise',zn=Un.getterFor(Qn),Wn=Un.set,Jn=Un.getterFor(Qn),Kn=En&&En.prototype,Xn=En,Zn=Kn,to=gn.TypeError,eo=gn.document,io=gn.process,so=Mn.f,ro=so,ao=!!(eo&&eo.createEvent&&gn.dispatchEvent),no=An(gn.PromiseRejectionEvent),oo=jn(Qn,(function(){var t=Dn(Xn),e=t!==String(Xn);if(!e&&66===Gn)return!0;if(!Zn.finally)return!0;if(Gn>=51&&/native code/.test(t))return!1;var i=new Xn((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};return(i.constructor={})[Yn]=s,!(i.then((function(){}))instanceof s)||!e&&qn&&!no})),uo=oo||!Rn((function(t){Xn.all(t).catch((function(){}))})),lo=function(t){var e;return!(!xn(t)||!An(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,u=t.resolve,d=t.reject,l=t.domain;try{o?(n||(2===e.rejection&&vo(e),e.rejection=1),!0===o?i=a:(l&&l.enter(),i=o(a),l&&(l.exit(),r=!0)),i===t.promise?d(to('Promise-chain cycle')):(s=lo(i))?Tn(s,i,u,d):u(i)):d(a)}catch(t){l&&!r&&l.exit(),d(t)}},ho=function(t,e){t.notified||(t.notified=!0,Ln((function(){for(var i,s=t.reactions;i=s.get();)co(i,t);t.notified=!1,e&&!t.rejection&&mo(t)})))},po=function(t,e,i){var s,r;ao?((s=eo.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),gn.dispatchEvent(s)):s={promise:e,reason:i},!no&&(r=gn['on'+t])?r(s):'unhandledrejection'===t&&Bn('Unhandled promise rejection',i)},mo=function(t){Tn(Cn,gn,(function(){var e,i=t.facade,s=t.value;if(fo(t)&&(e=Vn((function(){Hn?io.emit('unhandledRejection',s,i):po('unhandledrejection',i,s)})),t.rejection=Hn||fo(t)?2:1,e.error))throw e.value}))},fo=function(t){return 1!==t.rejection&&!t.parent},vo=function(t){Tn(Cn,gn,(function(){var e=t.facade;Hn?io.emit('rejectionHandled',e):po('rejectionhandled',e,t.value)}))},So=function(t,e,i){return function(s){t(e,s,i)}},bo=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,ho(t,!0))},go=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw to('Promise can\'t be resolved itself');var s=lo(e);s?Ln((function(){var i={done:!1};try{Tn(s,e,So(go,i,t),So(bo,i,t))}catch(e){bo(i,e,t)}})):(t.value=e,t.state=1,ho(t,!1))}catch(e){bo({done:!1},e,t)}}};oo&&(Zn=(Xn=function(t){Nn(this,Zn),$n(t),Tn(pn,this);var e=zn(this);try{t(So(go,e),So(bo,e))}catch(t){bo(e,t)}}).prototype,(pn=function(t){Wn(this,{type:Qn,done:!1,notified:!1,parent:!1,reactions:new Fn,rejection:!1,state:0,value:void 0})}).prototype=kn(Zn,{then:function(t,e){var i=Jn(this),s=so(In(this,Xn));return i.parent=!0,s.ok=!An(t)||t,s.fail=An(e)&&e,s.domain=Hn?io.domain:void 0,0==i.state?i.reactions.add(s):Ln((function(){co(s,i)})),s.promise},catch:function(t){return this.then(void 0,t)}}),mn=function(){var t=new pn,e=zn(t);this.promise=t,this.resolve=So(go,e),this.reject=So(bo,e)},Mn.f=so=function(t){return t===Xn||t===fn?new mn(t):ro(t)}),bn({global:!0,wrap:!0,forced:oo},{Promise:Xn}),wn(Xn,Qn,!1,!0),Pn(Qn),fn=yn(Qn),bn({target:Qn,stat:!0,forced:oo},{reject:function(t){var e=so(this);return Tn(e.reject,void 0,t),e.promise}}),bn({target:Qn,stat:!0,forced:true},{resolve:function(t){return On(this===fn?Xn:this,t)}}),bn({target:Qn,stat:!0,forced:uo},{all:function(t){var e=this,i=so(e),s=i.resolve,r=i.reject,a=Vn((function(){var i=$n(e.resolve),a=[],n=0,o=1;_n(t,(function(t){var u=n++,d=!1;o++,Tn(i,e,t).then((function(t){d||(d=!0,a[u]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise},race:function(t){var e=this,i=so(e),s=i.reject,r=Vn((function(){var r=$n(e.resolve);_n(t,(function(t){Tn(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var yo=_i,To=lt,Eo=N,ko=wr,wo=Ca;Di({target:'Promise',proto:!0,real:!0,forced:!!yo&&v((function(){yo.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=ko(this,To('Promise')),i=Eo(t);return this.then(i?function(i){return wo(e,t()).then((function(){return i}))}:t,i?function(i){return wo(e,t()).then((function(){throw i}))}:t)}});var Po,$o=lt,Ao=$o('Promise','finally');!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(Po||(Po={}));var xo,No=(e,i=0,s=Po.OFFSET_P)=>{switch(s){case Po.OFFSET_P:return e.replace('_offset_p',0===i?'':'_'+i.toFixed(0));case Po.PLAYBACK_SHIFT:{if(0===i)return e;const t=new URL(e);return t.searchParams.append('playback_shift',i.toFixed(0)),t.toString()}default:t.assertNever(s)}return e},Do=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};exports.VideoQuality=void 0,(xo=exports.VideoQuality||(exports.VideoQuality={})).INVARIANT='Invariant quality',xo.Q_144P='144p',xo.Q_240P='240p',xo.Q_360P='360p',xo.Q_480P='480p',xo.Q_720P='720p',xo.Q_1080P='1080p',xo.Q_1440P='1440p',xo.Q_2160P='2160p',xo.Q_4320P='4320p';const _o={[exports.VideoQuality.Q_144P]:{width:256,height:144},[exports.VideoQuality.Q_240P]:{width:428,height:240},[exports.VideoQuality.Q_360P]:{width:640,height:360},[exports.VideoQuality.Q_480P]:{width:856,height:480},[exports.VideoQuality.Q_720P]:{width:1280,height:720},[exports.VideoQuality.Q_1080P]:{width:1920,height:1080},[exports.VideoQuality.Q_1440P]:{width:2560,height:1440},[exports.VideoQuality.Q_2160P]:{width:3840,height:2160},[exports.VideoQuality.Q_4320P]:{width:7680,height:4320}},Ro=(t,e)=>_o[t].height>_o[e].height,Io=(t,e)=>_o[t].height<_o[e].height,Co=Object.keys(_o).sort(((t,e)=>Io(t,e)?-1:1)),Lo=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return Co.find((t=>{const e=_o[t];return e.width>=s&&e.height>=i}))},Oo=t=>t===exports.VideoQuality.INVARIANT;class Bo{constructor(e){this.transitionStarted$=new t.Subject,this.transitionEnded$=new t.Subject,this.transitionUpdated$=new t.Subject,this.forceChanged$=new t.Subject,this.stateChangeStarted$=t.merge(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=t.merge(this.transitionEnded$,this.forceChanged$),this.state=e}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(e){const i=this.transition,s=this.state;s===e||t.isNonNullable(i)&&i.to===e||(this.state=e,i?(this.transition={from:i.from,to:e,canceledTransition:i},this.transitionUpdated$.next(this.transition)):(this.transition={from:s,to:e},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var Mo;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Mo||(Mo={}));class Vo{constructor(e){this.subscription=new t.Subscription,this.loadMediaTimeoutSubscription=new t.Subscription,this.videoState=new Bo(Mo.STOPPED),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekState: ${JSON.stringify(a)};`}),s!==exports.PlaybackState.STOPPED){if(!i)if((null==r?void 0:r.to)===exports.PlaybackState.PAUSED||a.state!==l.Requested||e===Mo.STOPPED)switch(s){case exports.PlaybackState.PLAYING:switch(e){case Mo.PLAYING:break;case Mo.PAUSED:case Mo.READY:this.videoState.startTransitionTo(Mo.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case Mo.STOPPED:this.videoState.startTransitionTo(Mo.READY),this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Mo.PLAYING:this.videoState.startTransitionTo(Mo.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case Mo.PAUSED:break;case Mo.READY:this.videoState.startTransitionTo(Mo.PAUSED),this.videoState.setState(Mo.PAUSED);break;case Mo.STOPPED:this.videoState.startTransitionTo(Mo.READY),this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(s)}else this.seek(a.position)}else e!==Mo.STOPPED&&(this.videoState.startTransitionTo(Mo.STOPPED),this.stop())},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${e.format}`}),this.params.output.isLive$.next((e=>{switch(e){case exports.VideoFormat.MPEG:case exports.VideoFormat.DASH:case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_JS:case exports.VideoFormat.HLS_ONDEMAND:return!1;case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_LIVE_WEBM:return!0;default:return t.assertNever(e)}})(e.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const i=this.params.connection.session.getMediaSession();i&&this.restoreSession(i),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const e=new t.Subscription;this.subscription.add(e),this.subscription.add(t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(t.map((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const i=(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 t.Subject;e.add(i.pipe(t.debounce(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let s=NaN;e.add(t.fromEvent(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===l.Applying||Math.abs(e-s)>5)&&i.next(e),s=e}))),e.add(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemoteReady():(this.handleRemoteStop(),e.unsubscribe())})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(e=>{this.logRemoteEvent(e);const{remotePlayer:i}=this.params.connection,s=e.value,r=this.params.output.isBuffering$.getValue(),a=s===chrome.cast.media.PlayerState.BUFFERING;switch(r!==a&&this.params.output.isBuffering$.next(a),s){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&i.duration-i.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:t.assertNever(s)}})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),i(t.fromEvent(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));i(t.merge(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(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(Mo.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):(this.videoState.setState(Mo.PLAYING),Do(this.params.desiredState.playbackState,exports.PlaybackState.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:l.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)!==Mo.PAUSED&&t!==Mo.PLAYING||(this.videoState.setState(Mo.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==Mo.PLAYING&&t!==Mo.PAUSED||(this.videoState.setState(Mo.PLAYING),Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===Mo.READY&&this.videoState.setState(Mo.READY)}handleRemoteStop(){this.videoState.getState()!==Mo.STOPPED&&this.videoState.setState(Mo.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(e){var i;const s=this.params.source;let r,a,n;switch(e){case exports.VideoFormat.MPEG:{const i=s[e];t.assertNonNullable(i);const o=Object.keys(i).sort(((t,e)=>t===e?0:t===exports.VideoQuality.INVARIANT?1:e===exports.VideoQuality.INVARIANT?-1:Io(t,e)?1:-1))[0];t.assertNonNullable(o);const u=i[o];t.assertNonNullable(u),r=u,a='video/mp4',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/x-mpegurl',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',n=chrome.cast.media.StreamType.BUFFERED;break}case exports.VideoFormat.HLS_LIVE:{const i=s[e];t.assertNonNullable(i),r=No(i.url),a='application/x-mpegurl',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.DASH_LIVE_WEBM:{const i=s[e];t.assertNonNullable(i),r=i.url,a='application/dash+xml',n=chrome.cast.media.StreamType.LIVE;break}case exports.VideoFormat.HLS_JS:case exports.VideoFormat.DASH:case exports.VideoFormat.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 t.assertNever(e)}const o=new chrome.cast.media.MediaInfo(null!==(i=this.params.meta.videoId)&&void 0!==i?i:r,a);o.contentUrl=r,o.streamType=n,o.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:d}=this.params.meta;return t.isNonNullable(u)&&(o.metadata.title=u),t.isNonNullable(d)&&(o.metadata.subtitle=d),o}createLoadRequest(t){const e=new chrome.cast.media.LoadRequest(t);e.autoplay=!1;const i=this.params.desiredState.seekState.getState();return i.state===l.Applying||i.state===l.Requested?e.currentTime=this.params.output.isLive$.getValue()?0:i.position/1e3:e.currentTime=0,e}loadMedia(e){const i=this.params.connection.session.loadMedia(e),s=new Promise(((e,i)=>{this.loadMediaTimeoutSubscription.add(t.timeout(7e3).subscribe((()=>i('timeout(7000)'))))}));Ao(Promise.race([i,s]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});this.params.desiredState.seekState.getState().state===l.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 Fo(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{u(s.next(t))}catch(t){a(t)}}function o(t){try{u(s.throw(t))}catch(t){a(t)}}function u(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}u((s=s.apply(t,e||[])).next())}))}function Uo(t){return this instanceof Uo?(this.v=t,this):new Uo(t)}function jo(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 Uo?Promise.resolve(i.value.v).then(u,d):l(a[0][2],i)}catch(t){l(a[0][3],t)}var i}function u(t){o('next',t)}function d(t){o('throw',t)}function l(t,e){t(e),a.shift(),a.length&&o(a[0][0],a[0][1])}}class qo{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 Ho extends qo{constructor(){super(),this.listeners||qo.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 Go{constructor(){Object.defineProperty(this,'signal',{value:new Ho,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 Yo(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&&(Go.prototype[Symbol.toStringTag]='AbortController',Ho.prototype[Symbol.toStringTag]='AbortSignal');const Qo=Yo({fetch:window.fetch,Request:window.Request,AbortController:window.AbortController}),zo=Qo?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(!Yo({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,Wo=Qo?zo.fetch:window.fetch;Qo?zo.Request:window.Request;const Jo=Qo?Go:window.AbortController,Ko=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Xo{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 Fo(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]=Ko(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(Ko),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 Jo,u=o.signal,d={url:t,from:s,to:r,loaded:0,data:null,abortController:o};u.addEventListener('abort',(()=>this.onBigRequestAbort(d)));const l=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 Wo(n,{signal:u}).then((t=>{var e,i,a;if(d.response=t,!t.ok||!t.body)return void this.onBigRequestError(d);const[n,o]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,o);const u=n.getReader(),c=parseInt(null!==(a=t.headers.get('Content-Length'))&&void 0!==a?a:'',10)||r-s+1;d.data=new ArrayBuffer(c);const h=new Uint8Array(d.data),p=({done:t,value:e})=>Fo(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(d):e&&(h.set(e,d.loaded),d.loaded+=e.byteLength,this.onBigRequestProgress(d),yield null==u?void 0:u.read().then(p,Xo.suppressStreamErrors).catch(l))}));null==u||u.read().then(p,Xo.suppressStreamErrors).catch(l)}),Xo.suppressAbort).catch((t=>this.onBigRequestError(d,t))),d}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r,response:a}){var n,o,u,d,l,c,h,p;if(!this.activeRequests.has(t)||!r)return;const m=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const n of m){const{request:m}=n,[f,v]=Ko(m),S=f>=e&&v<=e+s,b=e>=f&&e+s<v,g=r.slice(f-e,Math.min(v-e+1,s));if((S||b)&&(m.requestStartDate=null!==(o=m.requestStartDate)&&void 0!==o?o:new Date,m.firstByteDate=null!==(u=m.firstByteDate)&&void 0!==u?u:new Date,m.bytesLoaded=g.byteLength,m.bytesTotal=i-e),S){m.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(d=this.dashJsRequestQueue.get(t))&&void 0!==d?d:[]).filter((t=>t!==n))),null===(l=n.success)||void 0===l||l.call(n,g,'',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(m,t,null!==(h=null==a?void 0:a.status)&&void 0!==h?h:200,e,[])}else b&&(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 u=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of u){const[r,a]=Ko(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]=Ko(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 Zo{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(Zo.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;Zo.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const tu=(t,e)=>{const i=new Xo(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 Zo(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var eu=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)},iu=_,su=Zt,ru=Function.prototype,au=iu&&Object.getOwnPropertyDescriptor,nu=su(ru,'name'),ou={EXISTS:nu,PROPER:nu&&'something'===function(){}.name,CONFIGURABLE:nu&&(!iu||iu&&au(ru,'name').configurable)},uu={},du=bs,lu=Math.max,cu=Math.min,hu=it,pu=function(t,e){var i=du(t);return i<0?lu(i+e,0):cu(i,e)},mu=Es,fu=function(t){return function(e,i,s){var r,a=hu(e),n=mu(a),o=pu(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}},vu={includes:fu(!0),indexOf:fu(!1)},Su=Zt,bu=it,gu=vu.indexOf,yu=Wa,Tu=x([].push),Eu=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],ku=function(t,e){var i,s=bu(t),r=0,a=[];for(i in s)!Su(yu,i)&&Su(s,i)&&Tu(a,i);for(;e.length>r;)Su(s,i=e[r++])&&(~gu(a,i)||Tu(a,i));return a},wu=Eu,Pu=Object.keys||function(t){return ku(t,wu)},$u=_,Au=ii,xu=ei,Nu=oi,Du=it,_u=Pu;uu.f=$u&&!Au?Object.defineProperties:function(t,e){Nu(t);for(var i,s=Du(e),r=_u(e),a=r.length,n=0;a>n;)xu.f(t,i=r[n++],s[i]);return t};var Ru,Iu=oi,Cu=uu,Lu=Eu,Ou=Wa,Bu=Pr,Mu=De,Vu=za('IE_PROTO'),Fu=function(){},Uu=function(t){return'<script>'+t+'<\/script>'},ju=function(t){t.write(Uu('')),t.close();var e=t.parentWindow.Object;return t=null,e},qu=function(){try{Ru=new ActiveXObject('htmlfile')}catch(t){}var t,e;qu='undefined'!=typeof document?document.domain&&Ru?ju(Ru):((e=Mu('iframe')).style.display='none',Bu.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(Uu('document.F=Object')),t.close(),t.F):ju(Ru);for(var i=Lu.length;i--;)delete qu.prototype[Lu[i]];return qu()};Ou[Vu]=!0;var Hu,Gu,Yu,Qu=Object.create||function(t,e){var i;return null!==t?(Fu.prototype=Iu(t),i=new Fu,Fu.prototype=null,i[Vu]=t):i=qu(),void 0===e?i:Cu.f(i,e)},zu=!v((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),Wu=f,Ju=Zt,Ku=N,Xu=Jt,Zu=zu,td=za('IE_PROTO'),ed=Wu.Object,id=ed.prototype,sd=Zu?ed.getPrototypeOf:function(t){var e=Xu(t);if(Ju(e,td))return e[td];var i=e.constructor;return Ku(i)&&e instanceof i?i.prototype:e instanceof ed?id:null},rd=v,ad=N,nd=Qu,od=sd,ud=Ii,dd=fe('iterator'),ld=!1;[].keys&&('next'in(Yu=[].keys())?(Gu=od(od(Yu)))!==Object.prototype&&(Hu=Gu):ld=!0);var cd=null==Hu||rd((function(){var t={};return Hu[dd].call(t)!==t}));ad((Hu=cd?{}:nd(Hu))[dd])||ud(Hu,dd,(function(){return this}));var hd={IteratorPrototype:Hu,BUGGY_SAFARI_ITERATORS:ld},pd=hd.IteratorPrototype,md=Qu,fd=U,vd=es,Sd=hs,bd=function(){return this},gd=Di,yd=C,Td=function(t,e,i,s){var r=e+' Iterator';return t.prototype=md(pd,{next:fd(+!s,i)}),vd(t,r,!1,!0),Sd[r]=bd,t},Ed=sd,kd=es,wd=Ii,Pd=hs,$d=ou.PROPER,Ad=hd.BUGGY_SAFARI_ITERATORS,xd=fe('iterator'),Nd=function(){return this},Dd=it,_d=hs,Rd=vn;ei.f;var Id=function(t,e,i,s,r,a,n){Td(i,e,s);var o,u,d,l=function(t){if(t===r&&f)return f;if(!Ad&&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',h=!1,p=t.prototype,m=p[xd]||p['@@iterator']||r&&p[r],f=!Ad&&m||l(r),v='Array'==e&&p.entries||m;if(v&&(o=Ed(v.call(new t)))!==Object.prototype&&o.next&&(kd(o,c,!0,!0),Pd[c]=Nd),$d&&'values'==r&&m&&'values'!==m.name&&(h=!0,f=function(){return yd(m,this)}),r)if(u={values:l('values'),keys:a?f:l('keys'),entries:l('entries')},n)for(d in u)(Ad||h||!(d in p))&&wd(p,d,u[d]);else gd({target:e,proto:!0,forced:Ad||h},u);return n&&p[xd]!==f&&wd(p,xd,f,{name:r}),Pd[e]=f,u},Cd=Rd.set,Ld=Rd.getterFor('Array Iterator');Id(Array,'Array',(function(t,e){Cd(this,{type:'Array Iterator',target:Dd(t),index:0,kind:e})}),(function(){var t=Ld(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'),_d.Arguments=_d.Array;var Od=$e,Bd=ei,Md=U,Vd=Js,Fd=function(t,e,i){var s=Od(e);s in t?Bd.f(t,s,Md(0,i)):t[s]=i};Di({target:'Object',stat:!0},{fromEntries:function(t){var e={};return Vd(t,(function(t,i){Fd(e,t,i)}),{AS_ENTRIES:!0}),e}});var Ud=at.Object.fromEntries,jd={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},qd=f,Hd=Yi,Gd=bi,Yd=hs,Qd=fe('toStringTag');for(var zd in jd){var Wd=qd[zd],Jd=Wd&&Wd.prototype;Jd&&Hd(Jd)!==Qd&&Gd(Jd,Qd,zd),Yd[zd]=Yd.Array}var Kd=Ud,Xd=e=>{const i=new t.ValueSubject(1/0),s=new t.Subject,r=new t.ValueSubject(void 0),a=new t.ValueSubject(void 0);let n=NaN,o=!1;return e.extend('XHRLoader',(function(){const{parent:e}=this,u=e.load.bind(e);return{load:function(e){if('MPD'===e.request.type){const u=e.onload,d=e.progress;e.onload=function(...e){return(e=>{var s,n,o,u,d;const l=Kd(e.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(': '))));if('x-playback-duration'in l||'x-playback-duration-millis'in l){const r=parseInt(null!==(s=e.getResponseHeader('X-Playback-Duration'))&&void 0!==s?s:'',10),a=parseInt(null!==(n=e.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==n?n:'',10),u=null!==(o=null!=a?a:1e3*r)&&void 0!==o?o:NaN;t.isNonNullable(u)&&!isNaN(u)&&i.next(u)}const c=null!==(u=l['x-delivery-type'])&&void 0!==u?u:exports.HttpConnectionType.HTTP1,h=null!==(d={1:!0,0:!1}[l['x-reused']])&&void 0!==d?d:void 0;r.next(c),a.next(h)})(this),u(...e)},e.progress=function(...t){return this.readyState>=2&&!o&&(o=!0,s.next(Date.now()-n)),d(...t)},n=Date.now(),o=!1}return u(e)}}}),!0),{playbackDuration$:i,ping$:s,connectionReused$:a,connectionType$:r}},Zd=t=>{const e=new URL(t);return e.searchParams.append('quic','1'),e.toString()},tl=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 el=(e,i,s,{equal:r=((t,e)=>t===e),changed$:a,onError:n}={})=>{const o=e.getState(),u=i(),d=t.isNullable(a),l=new t.Subscription;return a&&l.add(a.subscribe((t=>{const i=e.getState();r(t,i)&&e.setState(t)}),n)),r(u,o)||(s(o),d&&e.setState(o)),l.add(e.stateChangeStarted$.subscribe((t=>{s(t.to),d&&e.setState(t.to)}),n)),l},il=(e,i,s)=>el(i,(()=>e.loop),(i=>{t.isNonNullable(i)&&(e.loop=i)}),{onError:s}),sl=(e,i,s,r)=>el(i,(()=>({muted:e.muted,volume:e.volume})),(i=>{t.isNonNullable(i)&&(e.muted=i.muted,e.volume=i.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$:s,onError:r}),rl=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class al{constructor(){this.available$=new t.Subject,this.current$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.subscription=new t.Subscription,this.externalTracks=new Map}connect(e,i,s){this.video=e,this.cueSettings=i.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(s.availableTextTracks$)),this.subscription.add(this.current$.subscribe(s.currentTextTrack$)),this.subscription.add(this.error$.subscribe(s.error$)),this.subscription.add(el(i.externalTextTracks,(()=>Object.values(this.externalTracks)),(e=>{t.isNonNullable(e)&&this.setExternal(e)}),{equal:(e,i)=>t.isNonNullable(e)&&t.isNonNullable(i)&&e.length===i.length&&e.every((({id:t},e)=>t===i[e].id)),changed$:this.available$.pipe(t.map((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(el(i.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(el(i.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){t.assertNonNullable(this.video);const{textTracks:e}=this.video;this.subscription.add(t.fromEvent(e,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(t.merge(t.fromEvent(e,'addtrack'),t.fromEvent(e,'removetrack'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),t.filterChanged(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(t.merge(t.fromEvent(e,'change'),t.observableFrom(['init'])).pipe(t.map((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),t.map((t=>t&&this.htmlTextTrackToITextTrack(t).id)),t.filterChanged()).subscribe(this.current$));const i=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(t.fromEvent(e,'addtrack').subscribe((t=>{var e,s;null===(e=t.track)||void 0===e||e.addEventListener('cuechange',i);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(t.fromEvent(e,'removetrack').subscribe((t=>{var e;null===(e=t.track)||void 0===e||e.removeEventListener('cuechange',i)})))}applyCueSettings(e){if(!e||!e.length)return;const i=this.cueSettings.getState();for(const s of Array.from(e)){const e=s;t.isNonNullable(i.align)&&(e.align=i.align),t.isNonNullable(i.position)&&(e.position=i.position),t.isNonNullable(i.size)&&(e.size=i.size),t.isNonNullable(i.line)&&(e.line=i.line)}}htmlTextTracksAsArray(e=!1){t.assertNonNullable(this.video);const i=[...this.video.textTracks];return e?i:i.filter(al.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(e){t.assertNonNullable(this.video);for(const i of this.htmlTextTracksAsArray(!0))t.isNonNullable(e)&&rl(i,e)?i.mode='showing':i.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(e){t.assertNonNullable(this.video);const i=document.createElement('track');i.setAttribute('src',e.url),i.setAttribute('id',e.id),e.label&&i.setAttribute('label',e.label),e.language&&i.setAttribute('srclang',e.language),this.externalTracks.set(e.id,e),this.video.appendChild(i)}detach(e){t.assertNonNullable(this.video);const i=Array.prototype.find.call(this.video.getElementsByTagName('track'),(t=>t.getAttribute('id')===e));i&&this.video.removeChild(i),this.externalTracks.delete(e)}}var nl=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e};class ol{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}}var ul=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadeddata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());class dl{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({start:i,end:s,i:e})}return this._buffer.sort((function(t,e){return t.start-e.start})),this._buffer}getByTime(t){return this._buffer.find((e=>t>=e.start&&t<e.end))}getNextWithGap(t,e){const i=this.getNext(t);if(i&&i.start-t.end<(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((({start:s,end: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 ll=(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{start:s,end: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{start:s,end:r}},cl=e=>new t.Observable((i=>{let s=0;return(new t.Subscription).add(t.fromEvent(e,'loadstart').subscribe((()=>{s=Date.now()}))).add(t.fromEvent(e,'loadedmetadata').subscribe((()=>{i.next(Date.now()-s)})))})).pipe(t.once());const hl=e=>{const i=(i,s=(()=>{}))=>t.fromEvent(e,i).pipe(t.map(s)),s=t.merge(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((i=>t.fromEvent(e,i)))).pipe(t.map((()=>e.readyState<3)),t.filterChanged()),r=t.merge(t.fromEvent(e,'progress'),t.fromEvent(e,'timeupdate')).pipe(t.map((()=>ll(e.buffered,e.currentTime)))),a=t.fromEvent(e,'volumechange').pipe(t.debounce(0),t.map((()=>({muted:e.muted,volume:e.volume})))),n=t.fromEvent(e,'error').pipe(t.map((()=>{const t=e.error;return{id:t?`MediaError#${t.code}`:'HtmlVideoError',message:t?t.message:'Error event from HTML video element'}}))),o=i('timeupdate',(()=>e.currentTime)),u=new t.Subject;let d;return o.subscribe((i=>{e.loop&&t.isNonNullable(d)&&t.isNonNullable(i)&&d>=e.duration-.3&&i<=.3&&u.next(d),d=i})),{playing$:i('playing'),pause$:i('pause').pipe(t.filter((()=>!e.error))),canplay$:i('canplay'),ended$:i('ended'),looped$:u,error$:n,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:o,durationChange$:i('durationchange',(()=>e.duration)),isBuffering$:s,currentBuffer$:r,volumeState$:a,firstBytes$:cl(e),firstFrame$:ul(e)}},pl=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)};var ml=Jt,fl=Es,vl=bs;Di({target:'Array',proto:!0},{at:function(t){var e=ml(this),i=fl(e),s=vl(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var Sl=$o('Array','at');let bl=!1,gl={};const yl=t=>{t(gl)},Tl=(t,e)=>{var i;bl&&(gl.meta=null!==(i=gl.meta)&&void 0!==i?i:{},gl.meta[t]=e)};class El{constructor(t){this.name=t}next(t){var e,i;if(!bl)return;gl.series=null!==(e=gl.series)&&void 0!==e?e:{};const s=null!==(i=gl.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),gl.series[this.name]=s}}const kl=new El('best_bitrate');class wl{constructor(){this.history={}}recordSelection(e){this.history[e.id]=t.now()}recordSwitch(t){this.last=t}clear(){this.last=void 0,this.history={}}}const Pl=(e,{container:i,throughput:s,tuning:r,limits:a,reserve:n=0,forwardBufferHealth:o,playbackRate:u,current:d,history:l})=>{var c,h,p,m;const f=r.usePixelRatio&&null!==(c=window.devicePixelRatio)&&void 0!==c?c:1,v=r.limitByContainer&&i&&i.width>0&&i.height>0&&{width:i.width*f*r.containerSizeFactor,height:i.height*f*r.containerSizeFactor},S=v&&Lo(v),b=r.considerPlaybackRate&&t.isNonNullable(u)?u:1,g=e.filter((t=>!Oo(t.quality))).sort(((t,e)=>Ro(t.quality,e.quality)?-1:1)),y=null===(h=Sl(g,-1))||void 0===h?void 0:h.quality,T=null===(p=Sl(g,0))||void 0===p?void 0:p.quality,E=t.isNullable(a)||t.isNonNullable(a.min)&&t.isNonNullable(a.max)&&Io(a.max,a.min)||t.isNonNullable(a.min)&&T&&Ro(a.min,T)||t.isNonNullable(a.max)&&y&&Io(a.max,y),k=b*(w=null!=o?o:.5,P=r.bitrateFactorAtEmptyBuffer,$=r.bitrateFactorAtFullBuffer,(P-$)*Math.pow(2,-10*w)+$);var w,P,$;const A=g.filter((e=>{const i=!S||Io(e.quality,S),u=!(t.isNonNullable(s)&&isFinite(s)&&t.isNonNullable(e.bitrate))||s-n>=e.bitrate*k,l=r.lazyQualitySwitch&&t.isNonNullable(r.minBufferToSwitchUp)&&d&&!Oo(d.quality)&&(null!=o?o:0)<r.minBufferToSwitchUp&&Ro(e.quality,d.quality),c=E||(t.isNullable(a.max)||(h=e.quality,p=a.max,_o[h].height<=_o[p].height))&&(t.isNullable(a.min)||((t,e)=>_o[t].height>=_o[e].height)(e.quality,a.min));var h,p;return i&&u&&!l&&c}))[0];A&&A.bitrate&&kl.next(A.bitrate);const x=null!==(m=null!=A?A:g[Math.ceil((g.length-1)/2)])&&void 0!==m?m:e[0],N=x&&l&&l.history[x.id]&&t.now()-l.history[x.id]<=r.trackCooldown&&(!l.last||x.id!==l.last.id);if((null==x?void 0:x.id)&&l&&!N&&l.recordSelection(x),N&&(null==l?void 0:l.last)){const t=l.last;return null==l||l.recordSwitch(t),t}return null==l||l.recordSwitch(x),x};var $l=t=>new URL(t).hostname;const Al=(e,i=300)=>new t.Observable((r=>{const{width:a,height:n}=e.getBoundingClientRect();if(r.next({width:a,height:n}),!window.ResizeObserver)return;const o=new ResizeObserver(s.default((e=>{const i=e[0];if(!i)return;let s,a;i.contentBoxSize&&i.contentBoxSize[0]?(a=i.contentBoxSize[0].blockSize,s=i.contentBoxSize[0].inlineSize):i.contentRect&&(s=i.contentRect.width,a=i.contentRect.height),t.isNonNullable(s)&&t.isNonNullable(a)&&r.next({width:s,height:a})}),i));return o.observe(e),()=>o.disconnect()})),xl={};var Nl;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Nl||(Nl={}));const Dl=(e,i)=>new t.Observable((t=>{const s=e=>t.next(e);return e.on(i,s),()=>e.off(i,s)}));class _l{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Nl.DOWNLOADING_LIB),this.textTracksManager=new al,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t.ValueSubject(void 0),this.maxSeekBackTime$=new t.ValueSubject(1/0),this.availableFrom$=new t.ValueSubject(void 0),this.elementSize$=new t.ValueSubject(void 0),this.liveOffset=new ol,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState(),a=this.isLive$.getValue();if(!this.videoState.getTransition()&&e!==Nl.DOWNLOADING_LIB&&e!==Nl.STREAM_INITIALIZED)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&e!==Nl.STOPPED&&i!==exports.PlaybackState.STOPPED&&(a?this.seek(r.position-this.liveOffset.getTotalPausedTime()):this.seek(r.position)),i){case exports.PlaybackState.STOPPED:switch(e){case Nl.STOPPED:break;case Nl.PLAYING:case Nl.PAUSED:case Nl.READY:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Nl.PLAYING:break;case Nl.PAUSED:a&&(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 Nl.READY:this.play();break;case Nl.STOPPED:this.prepare();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Nl.PLAYING:this.pause(),this.liveOffset.pause();break;case Nl.PAUSED:break;case Nl.READY:this.videoState.setState(Nl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Nl.STOPPED:this.prepare();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=nl(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next($l(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},s=window.setTimeout((()=>e('timeout')),5e3);Ao(Promise.resolve().then((function(){return i(require('dashjs/dist/dash.mediaplayer.min.js'))})).then((e=>{t||(xl.MediaPlayer=e.MediaPlayer,xl.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(xl.MediaPlayer,'dashjs not loaded'),t.assertNonNullable(xl.Debug,'dashjs not loaded'),this.player=xl.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?pl(t.frameRate+''):void 0),!0)));(this.params.format===exports.VideoFormat.DASH_WEBM||this.params.format===exports.VideoFormat.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=tu(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&&tl(this.player),eu(this.player),this.params.tuning.requestQuick&&this.player.extend('RequestModifier',(()=>({modifyRequestURL:Zd})),!0),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Nl.STOPPED)}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:t})},r=(t,e)=>this.subscription.add(t.subscribe(e,s));r(Al(this.video),this.elementSize$),r(Dl(this.player,'error').pipe(t.map((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),e.error$),r(Dl(this.player,'playbackError').pipe(t.map((t=>({id:'DashJSPlayback',message:t.error})))),e.error$);const a=Dl(this.player,'qualityChangeRendered').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));a.pipe(t.filter(t.isNonNullable)).subscribe(e.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(t.filter((({to:t})=>t===Nl.STREAM_INITIALIZED)),t.once()).subscribe((()=>{this.subscription.add(el(i.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}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.videoTracks.find((({track:t})=>t.id===e)))||void 0===i?void 0:i.bitrateInfo;s&&this.player.setQualityFor('video',s.qualityIndex)}),{changed$:a.pipe(t.map((t=>null==t?void 0:t.id))),onError:s}))}),s)),this.subscription.add(el(i.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:s})),r(Dl(this.player,'bufferStateChanged').pipe(t.filter((({mediaType:t})=>'video'===t)),t.map((({state:t})=>'bufferStalled'===t))),e.isBuffering$),r(Dl(this.player,'fragmentLoadingStarted'),(({mediaType:t,request:{url:i}})=>{var s,r;const a=this.player.getDashMetrics(),n=a.getLatestFragmentRequestHeaderValueByID(t,'X-Reused'),o=null!==(s=a.getLatestFragmentRequestHeaderValueByID(t,'X-Delivery-Type'))&&void 0!==s?s:exports.HttpConnectionType.HTTP1,u=null!==(r={1:!0,0:!1}[n])&&void 0!==r?r:void 0;this.params.output.httpConnectionType$.next(o),this.params.output.httpConnectionReused$.next(u),e.hostname$.next($l(i))})),r(Dl(this.player,'streamInitialized'),(({streamInfo:{duration:t,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||e.duration$.next(t),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=Lo(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const u={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:u,bitrateInfo:t}),t.qualityIndex===r&&(a=u)}}e.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&e.currentVideoTrack$.next(a),this.videoState.setState(Nl.STREAM_INITIALIZED),this.videoState.startTransitionTo(Nl.READY)})),r(Dl(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)})),r(t.merge(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,i.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),e=Pl(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===e));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),r(t.combine({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(t.filter(t.isNonNullable))}).pipe(t.filter((({isLive:t})=>t)),t.map((({maxSeekBackTime:t})=>-t/1e3))),this.params.output.duration$);const n=Dl(this.player,'playbackTimeUpdated').pipe(t.map((({time:t})=>null!=t?t:0)));r(t.combine({availableFrom:this.availableFrom$.pipe(t.filter(t.isNonNullable)),currentTime:n}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),r(n.pipe(t.filter((()=>!1===this.isLive$.getValue()))),e.position$),r(Dl(this.player,'playbackSeeked'),(()=>e.seekedEvent$.next())),r(Dl(this.player,'playbackEnded'),e.endedEvent$),r(Dl(this.player,'playbackProgress').pipe(t.map((()=>ll(this.video.buffered,this.video.currentTime)))),e.currentBuffer$),r(Dl(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Nl.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)})),r(Dl(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Nl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),r(Dl(this.player,'playbackPaused'),(()=>{this.videoState.setState(Nl.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)})),r(Dl(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Nl.READY&&this.videoState.setState(Nl.READY)})),r(this.isLive$,e.isLive$),r(Al(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));r(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)),this.syncPlayback);const{playbackDuration$:o,ping$:u,connectionType$:d,connectionReused$:l}=Xd(this.player);r(d,this.params.output.httpConnectionType$),r(l,this.params.output.httpConnectionReused$),r(o,this.maxSeekBackTime$),r(u.pipe(t.once()),e.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&r(t.combine({isLive:this.isLive$,isShort:e.duration$.pipe(t.map((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),r(n.pipe(t.filter((t=>t>this.params.tuning.insufficientBufferRuleMargin)),t.once()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,i,e),this.subscription.add(Dl(this.player,'manifestLoaded').pipe(t.once()).subscribe((()=>{const i=Date.now();this.subscription.add(Dl(this.player,'playbackPlaying').pipe(t.once()).subscribe((()=>e.firstFrameEvent$.next(Date.now()-i)),s))}),s)),this.subscription.add(il(this.video,i.isLooped,s));const{volumeState$:c,looped$:h}=hl(this.video);this.subscription.add(sl(this.video,i.volume,c,s)),this.subscription.add(c.subscribe(e.volume$,s)),this.subscription.add(h.subscribe(e.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(Nl.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Nl.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=No(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,Po.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t/1e3)}play(){this.videoState.startTransitionTo(Nl.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Nl.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 Rl=t=>{switch(t){case'mobile':return exports.VideoQuality.Q_144P;case'lowest':return exports.VideoQuality.Q_240P;case'low':return exports.VideoQuality.Q_360P;case'sd':case'medium':return exports.VideoQuality.Q_480P;case'hd':case'high':return exports.VideoQuality.Q_720P;case'fullhd':case'full':return exports.VideoQuality.Q_1080P;case'quadhd':case'quad':return exports.VideoQuality.Q_1440P;case'ultrahd':case'ultra':return exports.VideoQuality.Q_2160P}},Il=t=>Fo(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 Cl(){return t.now()}function Ll(t){return Cl()-t}function Ol(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 Bl(e,i,s,r){const a=window.XMLHttpRequest;let n,o,u,d,l,c=!1,h=0,p=!1,m='arraybuffer',f=7e3,v=2e3,S=()=>{if(c)return;t.assertNonNullable(d);const e=Ll(d);let i;if(e<v)return i=v-e,void setTimeout(S,i);v*=2,v>f&&(v=f),o&&o.abort(),o=new a,g()};const b=()=>{if(!c){if(--h>=0)return S(),void(r&&r());c=!0,l&&l(),s&&s()}},g=()=>{d=Cl(),o=new a,o.open('get',e);let s,r=0,h=0;const f=()=>(t.assertNonNullable(d),Math.max(d,Math.max(s||0,h||0)));if(n&&o.addEventListener('progress',(t=>{const e=Cl();n.updateChunk&&t.loaded>r&&(n.updateChunk(f(),t.loaded-r),r=t.loaded,s=e)})),u&&(o.timeout=u,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(c)return;t.assertNonNullable(o);const e=o.status;if(e>=200&&e<300){if(o.response.byteLength&&n){const t=o.response.byteLength-r;t&&n.updateChunk&&n.updateChunk(f(),t)}l&&l(),o&&i(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),p){const e=()=>{t.assertNonNullable(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(h=Cl(),o.removeEventListener('readystatechange',e))};o.addEventListener('readystatechange',e)}return o.responseType=m,o.send(),y},y={withBitrateReporting:t=>(n=t,y),withParallel:t=>(p=t,y),withJSONResponse:()=>(m='json',y),withRetryCount:t=>(h=t,y),withRetryInterval:(e,i)=>(t.isNonNullable(e)&&(v=e),t.isNonNullable(i)&&(f=i),y),withTimeout:t=>(u=t,y),withFinally:t=>(l=t,y),send:g,abort:()=>{o&&(o.abort(),o=void 0),c=!0,l&&l()}};return y}class Ml{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 Vl{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=Cl(),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=Bl(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Cl()-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=Cl()}_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=Cl();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 Fl{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 Ml(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Ol(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=Ol(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 e=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return e>3||t.isNonNullable(this.downloadRate)&&(this.downloadRate>1.5&&e>2||this.downloadRate>2&&e>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 Vl(3,1e4,this.bitrateSwitcher,this.params.config.maxParallelRequests,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(e){const{logger:i,videoElement:s,playerCallback:r}=this.params;let a=!1,n=null,o=null,u=null,d=null,l=!1;const c=()=>{const t=a&&(!l||l===this.rep);return t||i('Not running!'),t},h=(t,e,i)=>{u&&u.abort(),u=Bl(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},p=(e,i,s)=>{t.assertNonNullable(this.filesFetcher),null==o||o.abort(),o=this.filesFetcher.requestData(this.urlResolver.resolve(e,!1),i,s,(()=>this._retryCallback())).withFinally((()=>{o=null})).send()},m=t=>{const e=s.playbackRate;s.playbackRate!==t&&(i(`Playback rate switch: ${e}=>${t}`),s.playbackRate=t)},f=t=>{this.lowLatency=t,i(`lowLatency changed to ${t}`),v()},v=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void m(1);const e=Cl()-6e4;let s=0;for(let i=0;i<this.bufferStates.length;i++){const r=this.bufferStates[i];t=Math.min(t,r.buf),r.ts<e&&s++}this.bufferStates.splice(0,s),i(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,m(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else m(1)},S=e=>{let s;const a=()=>s&&s.start?s.start.length:0,n=t=>s.start[t]/1e3,o=t=>s.dur[t]/1e3,u=t=>s.fragIndex+t,l=(t,e)=>({chunkIdx:u(t),startTS:n(t),dur:o(t),discontinuity:e}),h=()=>{let t=0;if(s&&s.dur){let e=this.lowLatency?this.params.config.lowLatencyMinBuffer:this.params.config.minBuffer,i=this.lowLatency?this.params.config.lowLatencyMinBufferSegments:this.params.config.minBufferSegments,r=e;this.sourceJitter>1&&(r+=this.sourceJitter-1);let a=s.dur.length-1;for(;a>=0&&(r-=s.dur[a],!(r<=0));--a);t=Math.min(a,s.dur.length-1-i),t=Math.max(t,0)}return l(t,!0)},p=(t,e,i)=>{d&&d.abort(),d=Bl(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{d=null})).withJSONResponse().send()};return{seek:(i,o)=>{p(e,(e=>{if(!c())return;s=e;const u=Boolean(s.lowLatency);u!==this.lowLatency&&f(u);let d=0;for(let t=0;t<s.dur.length;++t)d+=s.dur[t];d>0&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(d/s.dur.length)),r({name:'index',zeroTime:s.zeroTime,shiftDuration:s.shiftDuration}),this.sourceJitter=s.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,s.jitter/1e3)):1,i((e=>{const i=a();if(!(i<=0)){if(t.isNonNullable(e))for(let t=0;t<i;t++)if(n(t)>e)return l(t);return h()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const e=a(),r=t?t.chunkIdx+1:0,n=r-s.fragIndex;if(!(e<=0)){if(!t||n<0||n-e>10)return i(`Resync: offset=${n} bChunks=${e} chunk=`+JSON.stringify(t)),h();if(!(n>=e))return l(r-s.fragIndex,!1)}}}},b=()=>{a=!1,o&&o.abort(),u&&u.abort(),d&&d.abort(),t.assertNonNullable(this.filesFetcher),this.filesFetcher.abortAll()};return l={start:i=>{const{videoElement:s,logger:r}=this.params;let o,u,l,m,f,g,y,T=S(e.jidxUrl),E=0;const k=()=>{f&&(clearTimeout(f),f=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=E+t,i=Cl(),s=Math.min(1e4,e-i);E=i;const r=()=>{d||c()&&T.seek((()=>{c()&&(E=Cl(),w(),k())}))};s>0?f=window.setTimeout((()=>{this.paused?k():r()}),s):r()},w=()=>{let t;for(;t=T.nextChunk(m);)m=t,N(t);const i=T.nextChunk(l);if(i){if(l&&i.discontinuity)return r('Detected discontinuity; restarting playback'),void(this.paused?k():(b(),this._initPlayerWith(e)));x(i)}else k()},P=(t,e)=>{if(!c()||!this.sourceBuffer)return;let i,a,n;const o=i=>{window.setTimeout((()=>{c()&&P(t,e)}),i)};if(this.sourceBuffer.updating)r('Source buffer is updating; delaying appendBuffer'),o(100);else{const u=Cl(),d=s.currentTime;!this.paused&&s.buffered.length>1&&g===d&&u-y>500&&(r('Stall suspected; trying to fix'),this._fixupStall()),g!==d&&(g=d,y=u);const l=this._getBufferSizeSec();if(l>30)r(`Buffered ${l} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:u,buf:l}),v(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;r('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(i=this.sourceBuffer.buffered.start(0),a=d,a-i>4&&this.sourceBuffer.remove(i,a-3)),o(1e3)}}},$=()=>{u&&o&&(r([`Appending chunk, sz=${u.byteLength}:`,JSON.stringify(l)]),P(u,(function(){u=null,w()})))},A=t=>e.fragUrlTemplate.replace('%%id%%',t.chunkIdx),x=t=>{c()&&p(A(t),((e,i)=>{if(c()){if(i/=1e3,u=e,l=t,n=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}$()}}),(()=>this._handleNetworkError()))},N=e=>{c()&&(t.assertNonNullable(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(A(e),!1)))},D=t=>{c()&&(e.cachedHeader=t,P(t,(()=>{o=!0,$()})))};a=!0,T.seek((e=>{c()&&(E=Cl(),e?(m=e,!t.isNullable(i)||e.startTS>i?x(e):(l=e,w())):k())}),i),e.cachedHeader?D(e.cachedHeader):h(e.headerUrl,D,(()=>this._handleNetworkError()))},stop:b,getTimestampSec:()=>n},l}_switchToQuality(e){const{logger:i,playerCallback:s}=this.params;let r;e.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),t.isNonNullable(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=e,this.rep=this._representation(e),i(`switch to quality: codecs=${e.codecs}; headerUrl=${e.headerUrl}; bitrate=${e.bitrate}`),this.bitrate=e.bitrate,t.assertNonNullable(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),s({name:'qualitySwitch',quality:e}))}_qualityAvailable(e){return t.isNonNullable(this.manifest.find((t=>t.name===e)))}_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=Cl();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&&Ll(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=Cl();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=Bl(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;Il(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 Ul;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Ul||(Ul={}));const jl=[Ul.PAUSED,Ul.PLAYING,Ul.READY],ql=[Ul.PAUSED,Ul.PLAYING,Ul.READY];class Hl{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Ul.STOPPED),this.representations$=new t.ValueSubject([]),this.textTracksManager=new al,this.maxSeekBackTime$=new t.ValueSubject(1/0),this.zeroTime$=new t.ValueSubject(void 0),this.liveOffset=new ol,this._dashCb=e=>{var i,s,r,a;switch(e.name){case'buffering':{const t=e.isBuffering;this.params.output.isBuffering$.next(t);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${e.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const t=e.manifest,a=[];for(const e of t){const t=null!==(i=e.name)&&void 0!==i?i:e.index.toString(10),r=null!==(s=Rl(e.name))&&void 0!==s?s:Lo(e.video),n=e.bitrate/1e3,o=Object.assign({},e.video);if(!r)continue;const u={id:t,quality:r,bitrate:n,size:o};a.push({track:u,representation:e})}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)===Ul.MANIFEST_READY&&this.videoState.setState(Ul.MANIFEST_READY);break}case'qualitySwitch':{const i=e.quality,s=null===(a=this.representations$.getValue().find((({representation:t})=>t===i)))||void 0===a?void 0:a.track;this.params.output.hostname$.next(new URL(i.headerUrl,this.params.source.url).hostname),t.isNonNullable(s)&&this.params.output.currentVideoTrack$.next(s);break}case'bandwidth':{const{size:t,duration:i}=e;this.params.dependencies.throughputEstimator.addRawSpeed(t,i);break}case'index':this.maxSeekBackTime$.next(e.shiftDuration),this.zeroTime$.next(e.zeroTime)}},this.syncPlayback=()=>{var e;const i=this.videoState.getState(),s=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),n=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${i}; videoTransition: ${JSON.stringify(s)}; desiredPlaybackState: ${r}; seekState: ${JSON.stringify(n)};`}),r!==exports.PlaybackState.STOPPED){if(!s){if(ql.includes(i)){const i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to;t.isNonNullable(i)&&this.setVideoTrack(i);const s=this.params.desiredState.autoVideoTrackSwitching.getTransition();s&&this.setAutoQuality(s.to)}if((null==a?void 0:a.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested&&jl.includes(i))this.seek(n.position-this.liveOffset.getTotalPausedTime());else switch(i){case Ul.STOPPED:return this.videoState.startTransitionTo(Ul.MANIFEST_READY),void this.dash.attachSource(No(this.params.source.url));case Ul.MANIFEST_READY:this.videoState.startTransitionTo(Ul.READY),this.prepare();break;case Ul.READY:return void(r===exports.PlaybackState.PAUSED?this.videoState.setState(Ul.PAUSED):r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ul.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(Ul.PAUSED)}))));case Ul.PLAYING:return void(r===exports.PlaybackState.PAUSED&&(this.videoState.startTransitionTo(Ul.PAUSED),this.liveOffset.pause(),this.dash.pause()));case Ul.PAUSED:return void(r===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Ul.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(Ul.PAUSED)})),this.params.output.position$.next(-this.liveOffset.getTotalOffset()/1e3)):this.seek(-this.liveOffset.getTotalOffset())));default:return t.assertNever(i)}}}else i!==Ul.STOPPED&&(this.videoState.startTransitionTo(Ul.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(Ul.STOPPED))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const i=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=nl(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($l(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const s=hl(this.video);this.subscription.add(s.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Ul.READY&&this.videoState.setState(Ul.READY)}),i)).add(s.pause$.subscribe((()=>{this.videoState.setState(Ul.PAUSED)}),i)).add(s.playing$.subscribe((()=>{this.params.desiredState.seekState.getState().state===l.Applying&&this.params.output.seekedEvent$.next(),this.videoState.setState(Ul.PLAYING)}),i)).add(s.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$)).add(t.combine({zeroTime:this.zeroTime$.pipe(t.filter(t.isNonNullable)),position:s.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)).add(il(this.video,this.params.desiredState.isLooped,i)).add(sl(this.video,this.params.desiredState.volume,s.volumeState$,i)).add(s.volumeState$.subscribe(this.params.output.volume$,i)).add(cl(this.video).subscribe(this.params.output.firstBytesEvent$)).add(ul(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&_o[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((e=>{switch(e.to){case Ul.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(exports.PlaybackState.STOPPED);break;case Ul.MANIFEST_READY:case Ul.READY:break;case Ul.PAUSED:this.params.desiredState.playbackState.setState(exports.PlaybackState.PAUSED);break;case Ul.PLAYING:this.params.desiredState.playbackState.setState(exports.PlaybackState.PLAYING);break;default:return t.assertNever(e.to)}}),i)).add(t.merge(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekState.stateChangeEnded$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Fl({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 e,i,s,r,a,n;const o=this.representations$.getValue(),u=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState(),d=null!==(r=null===(s=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===s?void 0:s.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),l=!d&&t.isNonNullable(u)?u:null===(a=Pl(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===l)))||void 0===n?void 0:n.representation;t.assertNonNullable(c,'Representations missing'),this.dash.startPlay(c,d),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(l),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(d)}setVideoTrack(e){var i;const s=null===(i=this.representations$.getValue().find((({track:t})=>t.id===e)))||void 0===i?void 0:i.representation;t.assertNonNullable(s,`No such representation ${e}`),this.dash.switchByName(s.name),this.params.desiredState.videoTrack.setState(e)}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(No(this.params.source.url,i))}}var Gl=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?exports.HttpConnectionType.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}},Yl=(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 Ql{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 e=!1;this._xhr.onreadystatechange=()=>{var i,s,r,a,n,o,u,d;if(t.assertNonNullable(this._xhr),(null===(i=this._xhr)||void 0===i?void 0:i.status)>=400)return null===(s=this._errorCb)||void 0===s||s.call(this,`Http${null===(r=this._xhr)||void 0===r?void 0:r.status}`,`XHR response code ${null===(a=this._xhr)||void 0===a?void 0:a.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!e){e=!0;const t=Kd(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(n=this._headersCb)||void 0===n||n.call(this,new Headers(t))}else 4===this._xhr.readyState?null===(o=this._completeCb)||void 0===o||o.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(u=this._progressCb)||void 0===u||u.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 zl{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 u=Date.now();let d=0,l=0,c=0;const h=t=>{s(zl._str2ua(t.substr(o))),o=t.length};let p=t.baseURL+'&bytes='+e+'-'+i;this._params.requestQuic&&(p=Zd(p)),this._lastXhr=new Ql(p,t.failoverHosts,(t=>{this._lastXhr=void 0,h(t);const e=Date.now()-u;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&&h(t),0===l)return void(l=Date.now());c=t.length-d;const e=Date.now()-l;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,d=t.length,l=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=zl._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 Wl{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=Zd(i)),new Ql(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,u,d,l,c,h,p,m,f,v,S,b,g,y,T,E,k,w;const P=t.getElementsByTagName('SegmentBase')[0],$=P&&r(P,'indexRange').split('-'),A=P&&P.getElementsByTagName('Initialization')[0],x=A&&r(A,'range').split('-');if(!x||!$){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===(l=null===(d=null===(u=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===u?void 0:u.childNodes)||void 0===d?void 0:d[0])||void 0===l?void 0:l.data),h=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:h})}return}const N=Number(null===(h=t.attributes.getNamedItem('bandwidth'))||void 0===h?void 0:h.value),D=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let _;const R=null!==(m=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==m?m:void 0;_=R?pl(R):void 0,a.push({width:Number(null===(f=t.attributes.getNamedItem('width'))||void 0===f?void 0:f.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:N,baseURL:D,failoverHosts:e,indexFrom:Number($[0]),indexTo:Number($[1]),initFrom:Number(x[0]),initTo:Number(x[1]),codecs:null!==(b=null===(S=t.attributes.getNamedItem('codecs'))||void 0===S?void 0:S.value)&&void 0!==b?b:void 0,mimeType:null!==(y=null===(g=t.attributes.getNamedItem('mimeType'))||void 0===g?void 0:g.value)&&void 0!==y?y:void 0,fps:_,bufferSize:.1*N/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!==(w=null===(k=t.attributes.getNamedItem('id'))||void 0===k?void 0:k.value)&&void 0!==w?w: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 u=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<u;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 d=t.refs[t.refs.length-1];d.toTime-d.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.end-this._video.currentTime,a<t.bufferLength&&(this._onDashCallback('buffering'),r!==e.end&&(r=e.end,window.setTimeout((()=>{try{const t=this._buffer.getNextWithGap(e);t&&(this._video.currentTime=t.start)}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 zl({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.end+r){const e=this._findRef(s.toTime);e&&e.toTime<i.end+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 e=this._video.currentTime;this._stream&&!t.isNullable(this._buffer.getByTime(e))||this._loadRef(this._params.selectRepresentation(this._representations),e,!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 Jl;!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'}(Jl||(Jl={}));const Kl=[Jl.PAUSED,Jl.PLAYING];class Xl{constructor(e){this.videoState=new Bo(Jl.STOPPED),this.subscription=new t.Subscription,this.representations$=new t.ValueSubject([]),this.currentRepresentation$=new t.ValueSubject(void 0),this.textTracksManager=new al,this.elementSize$=new t.ValueSubject(void 0),this.dashLiteEvents={idxRequestPing$:new t.Subject,responseHeaders$:new t.Subject,manifestReady$:new t.Subject,representationPlay$:new t.Subject,error$:new t.Subject},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&&Rl(a.name))&&void 0!==s?s:Lo(a),o=a.bandwidth/1e3,u={width:a.width,height:a.height},d=a.fps;if(!n)continue;const l={id:t,quality:n,bitrate:o,size:u,fps:d};r.push({track:l,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(Jl.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 e=this.currentRepresentation$.getValue();return t.assertNonNullable(e,'Can\'t select representation. something went wrong'),e},this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekState.getState();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${s}; seekState: ${JSON.stringify(a)};`}),s!==exports.PlaybackState.STOPPED){if(!i)switch((null==r?void 0:r.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&Kl.includes(e)&&this.seek(a.position,a.forcePrecise),e){case Jl.STOPPED:return this.videoState.startTransitionTo(Jl.MANIFEST_LOADED),void this.prepare();case Jl.MANIFEST_LOADED:return void this.videoState.startTransitionTo(Jl.INITIAL_REPRESENTATION_SELECTED);case Jl.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(Jl.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case Jl.METADATA_LOADED:return this.videoState.startTransitionTo(Jl.READY),void this.dash.updateRefsForCurrentTime();case Jl.READY:return void(s===exports.PlaybackState.PAUSED?(this.videoState.setState(Jl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):s===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Jl.PLAYING),this.playIfAllowed()));case Jl.PLAYING:return void(s===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Jl.PAUSED),this.video.pause()):(null==r?void 0:r.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Jl.PAUSED:return void(s===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Jl.PLAYING),this.playIfAllowed()):(null==r?void 0:r.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==Jl.STOPPED&&(this.videoState.startTransitionTo(Jl.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(Jl.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),t.merge(this.videoState.stateChangeStarted$.pipe(t.map((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(t.map((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=nl(e.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next($l(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new dl(this.video),this.dash=new Wl({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:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:t})},r=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},a=hl(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,s));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.firstFrame$,e.firstFrameEvent$),this.subscription.add(a.seeking$.subscribe((()=>{t.isNullable(this.params.desiredState.seekState.getState().state!==l.Applying)&&(this.videoState.getState()===Jl.PLAYING||this.videoState.getState()===Jl.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(a.seeked$.subscribe(e.seekedEvent$,s)),this.subscription.add(il(this.video,i.isLooped,s)),this.subscription.add(sl(this.video,i.volume,a.volumeState$,s)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,i,e),n(Al(this.video),this.elementSize$),this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Jl.READY&&this.videoState.setState(Jl.READY)}),s)).add(a.pause$.subscribe((()=>{this.videoState.setState(Jl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)}))).add(a.playing$.subscribe((()=>{this.videoState.setState(Jl.PLAYING),Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING)}),s)).add(a.loadedMetadata$.subscribe((()=>{this.videoState.setState(Jl.METADATA_LOADED)}),s)).add(a.currentBuffer$.subscribe((t=>{this.buffer.fill(),e.currentBuffer$.next(t)}),s)).add(this.dashLiteEvents.error$.pipe(t.map((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(t.merge(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,t.fromEvent(this.video,'progress')).pipe(t.map((()=>{var e,i,s;const a=this.currentRepresentation$.getValue(),n=this.representations$.getValue(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition(),u=this.params.desiredState.videoTrack.getState(),d=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),l=this.elementSize$.getValue(),c=r();let h;if(o&&this.params.desiredState.autoVideoTrackSwitching.setState(o.to),!c&&t.isNonNullable(u))h=u;else{const t=Yl(this.video.buffered,1e3*this.video.currentTime),s=c?this.params.tuning.dash.forwardBufferTargetAuto:this.params.tuning.dash.forwardBufferTargetManual,r=Math.min(t/s,1);h=null===(i=Pl(n.map((({track:t})=>t)),{container:l,throughput:d,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:r,playbackRate:this.video.playbackRate,current:null===(e=n.find((({representation:t})=>t===a)))||void 0===e?void 0:e.track}))||void 0===i?void 0:i.id}return t.isNonNullable(h)?null===(s=n.find((({track:t})=>t.id===h)))||void 0===s?void 0:s.representation:void 0})),t.filterChanged()).subscribe(this.currentRepresentation$,s)).add(t.combine({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(t.filter((t=>t.to===Jl.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(t.filter(t.isNonNullable))}).pipe(t.once()).subscribe((()=>this.videoState.setState(Jl.INITIAL_REPRESENTATION_SELECTED)),s)).add(this.currentRepresentation$.pipe(t.filter(t.isNonNullable),t.filterChanged(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&r()?t.height<=e.height:t===e))).subscribe((t=>{const e=Yl(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!r())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next($l(t.baseURL)))}),s)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Gl(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(t.once()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,s)).add(this.dashLiteEvents.representationPlay$.pipe(t.filter(t.isNonNullable)).subscribe(this.handleRepresentationPlay,s)).add(t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0)).subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const e=this.params.source;switch(e.type){case'url':this.dash.attachSource(e.url);break;case'raw':this.dash.attachManifest(e.raw);break;default:return t.assertNever(e)}}seek(t,e=!1){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t/1e3,e)}playIfAllowed(){Il(this.video).then((t=>{t||(this.videoState.setState(Jl.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}var Zl,tc,ec,ic;!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(Zl||(Zl={})),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.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.PARTIALLY_FED='partially_fed',t.FED='fed'}(ec||(ec={})),function(t){t.MP4='mp4',t.WEBM='webm'}(ic||(ic={}));var sc=(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};class rc{constructor(e){this.bufferFull$=new t.Subject,this.error$=new t.Subject,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=e,this.buffer.addEventListener('updateend',this.completeTask)}append(t,e){return Fo(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 Fo(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 Fo(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;try{this.execute(this.currentTask)}catch(t){t instanceof DOMException&&'QuotaExceededError'===t.name&&'append'===this.currentTask.operation?this.bufferFull$.next(this.currentTask.data.byteLength):this.error$.next({id:`BufferTaskQueue_${this.currentTask.operation}`,message:'Buffer operation failed',thrown:t}),this.currentTask.callback(!1),this.currentTask=null}this.currentTask&&'abort'===this.currentTask.operation&&this.completeTask()}execute(e){const{operation:i}=e;switch(i){case'append':this.buffer.appendBuffer(e.data);break;case'remove':this.buffer.remove(e.from/1e3,e.to/1e3);break;case'abort':this.buffer.abort();break;default:t.assertNever(i)}}}var ac;!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(ac||(ac={}));class nc{constructor({throughputEstimator:e,requestQuic:i}){this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.abortAllController=new Jo,this.subscription=new t.Subscription,this.fetchManifest=t.abortable(this.abortAllController.signal,function(t){return jo(this,arguments,(function*(){let e=t;this.requestQuic&&(e=Zd(e));const i=yield yield Uo(Wo(e,{signal:this.abortAllController.signal}).catch(oc));return i?(this.onHeadersReceived(i.headers),yield Uo(i.text())):yield Uo(null)}))}.bind(this)),this.fetchRange=t.abortable(this.abortAllController.signal,function(e,i,s,{method:r=ac.HEADER,onProgress:a,priority:n='auto',signal:o,measureThroughput:u=!0}={}){var d,l,c;return jo(this,arguments,(function*(){let h=e;const p=new Headers;switch(r){case ac.HEADER:p.append('Range',`${i}-${s}`);break;case ac.PARAM:{const t=new URL(h,location.href);t.searchParams.append('bytes',`${i}-${s}`),h=t.toString();break}default:t.assertNever(r)}this.requestQuic&&(h=Zd(h));let m=this.abortAllController.signal;if(o){const e=new Jo;this.subscription.add(t.merge(t.fromEvent(this.abortAllController.signal,'abort'),t.fromEvent(o,'abort')).subscribe((()=>{e.abort()}))),(this.abortAllController.signal.aborted||o.aborted)&&e.abort(),m=e.signal}const f=t.now(),v=yield yield Uo(Wo(h,{priority:n,headers:p,signal:m}).catch(oc));if(null===(d=this.throughputEstimator)||void 0===d||d.addRawRtt(t.now()-f),!v)return yield Uo(null);if(!v.ok||!v.body)return yield Uo(Promise.reject(new Error(`Fetch error ${v.status}: ${v.statusText}`)));this.onHeadersReceived(v.headers);const[S,b]=v.body.tee(),g=S.getReader();u&&(null===(l=this.throughputEstimator)||void 0===l||l.trackStream(b));const y=parseInt(null!==(c=v.headers.get('Content-Length'))&&void 0!==c?c:'',10)||s-i+1;let T=0;const E=new ArrayBuffer(y),k=new Uint8Array(E),w=new DataView(E);let P=!1;const $=t=>{P=!0,oc(t)},A=t.abortable(m,function({done:e,value:i}){return jo(this,arguments,(function*(){if(0===T&&this.lastRequestFirstBytes$.next(t.now()-f),m.aborted)return yield Uo(void 0);e?null==a||a(w,T):i&&(k.set(i,T),T+=i.byteLength,null==a||a(w,T),yield yield Uo(null==g?void 0:g.read().then(A,$)))}))}.bind(this));return yield yield Uo(null==g?void 0:g.read().then(A,$)),yield Uo(P?null:E)}))}.bind(this)),this.fetchRepresentation=t.abortable(this.abortAllController.signal,function(t,e,i='auto',s=0){return jo(this,arguments,(function*(){const{from:r,to:a}=t.initRange;let n,o,u=r,d=a,l=!1;t.indexRange&&(n=t.indexRange.from,o=t.indexRange.to,l=a+1===n,l&&(u=Math.min(n,r),d=Math.max(o,a))),u=Math.min(u,0),d+=s;const c=yield yield Uo(this.fetchRange(t.url,u,d,{method:ac.PARAM,priority:i,measureThroughput:!1}));if(!c)return yield Uo(null);const h=new DataView(c,r-u,a-u+1);if(!e.validateData(h))throw new Error('Invalid media file');const p=e.parseInit(h);let m;if(l&&void 0!==n&&void 0!==o)m=new DataView(c,n-u,o-n+1);else{const s=e.getIndexRange(p);if(s){const e=yield yield Uo(this.fetchRange(t.url,s.from,s.to,{method:ac.PARAM,priority:i,measureThroughput:!1}));if(!e)return yield Uo(null);m=new DataView(e)}}if(!m)throw new ReferenceError('No way to load representation index');const f=e.parseSegments(m,p);return yield Uo({dataView:new DataView(c),segments:f})}))}.bind(this)),this.throughputEstimator=e,this.requestQuic=i}onHeadersReceived(t){const{type:e,reused:i}=Gl(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const oc=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t},uc=new TextDecoder('ascii'),dc=t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=uc.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)}},lc={validateData:t=>'ftyp'===uc.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=dc(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(),u=4294967295&r();let d=n/a*1e3,l=t.byteOffset+t.byteLength+o;for(let t=0;t<u;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:ec.NONE,time:{from:d,to:d+o},byte:{from:l,to:l+s-1}}),d+=o,l+=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=dc(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 cc,hc;!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'}(cc||(cc={})),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'}(hc||(hc={}));const pc={[cc.EBML]:{type:hc.Master},[cc.EBMLVersion]:{type:hc.UnsignedInteger},[cc.EBMLReadVersion]:{type:hc.UnsignedInteger},[cc.EBMLMaxIDLength]:{type:hc.UnsignedInteger},[cc.EBMLMaxSizeLength]:{type:hc.UnsignedInteger},[cc.DocType]:{type:hc.String},[cc.DocTypeVersion]:{type:hc.UnsignedInteger},[cc.DocTypeReadVersion]:{type:hc.UnsignedInteger},[cc.Void]:{type:hc.Binary},[cc.Segment]:{type:hc.Master},[cc.SeekHead]:{type:hc.Master},[cc.Seek]:{type:hc.Master},[cc.SeekID]:{type:hc.Binary},[cc.SeekPosition]:{type:hc.UnsignedInteger},[cc.Info]:{type:hc.Master},[cc.TimestampScale]:{type:hc.UnsignedInteger},[cc.Duration]:{type:hc.Float},[cc.Tracks]:{type:hc.Master},[cc.Chapters]:{type:hc.Master},[cc.Cluster]:{type:hc.Master},[cc.Timestamp]:{type:hc.UnsignedInteger},[cc.SilentTracks]:{type:hc.Master},[cc.SilentTrackNumber]:{type:hc.UnsignedInteger},[cc.Position]:{type:hc.UnsignedInteger},[cc.PrevSize]:{type:hc.UnsignedInteger},[cc.SimpleBlock]:{type:hc.Binary},[cc.BlockGroup]:{type:hc.Master},[cc.EncryptedBlock]:{type:hc.Binary},[cc.Attachments]:{type:hc.Master},[cc.Tags]:{type:hc.Master},[cc.Cues]:{type:hc.Master},[cc.CuePoint]:{type:hc.Master},[cc.CueTime]:{type:hc.UnsignedInteger},[cc.CueTrackPositions]:{type:hc.Master},[cc.CueTrack]:{type:hc.UnsignedInteger},[cc.CueClusterPosition]:{type:hc.UnsignedInteger},[cc.CueRelativePosition]:{type:hc.UnsignedInteger},[cc.CueDuration]:{type:hc.UnsignedInteger},[cc.CueBlockNumber]:{type:hc.UnsignedInteger},[cc.CueCodecState]:{type:hc.UnsignedInteger},[cc.CueReference]:{type:hc.Master},[cc.CueRefTime]:{type:hc.UnsignedInteger}},mc=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 pc,a=r?pc[s].type:hc.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 u=new DataView(t.buffer,t.byteOffset+i+1,o-1),d=((n&255>>o)<<8*(o-1))+fc(u),l=i+o;let c;return c=l+d>t.byteLength?new DataView(t.buffer,t.byteOffset+l):new DataView(t.buffer,t.byteOffset+l,d),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,tagHeaderSize:l,tagSize:l+d,value:c,valueSize:d}},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},vc=(e,i)=>{switch(i){case hc.SignedInteger:return e.getInt8(0);case hc.UnsignedInteger:return fc(e);case hc.Float:return 4===e.byteLength?e.getFloat32(0):e.getFloat64(0);case hc.String:return new TextDecoder('ascii').decode(e);case hc.UTF8:return new TextDecoder('utf-8').decode(e);case hc.Date:return new Date(Date.UTC(2001,0)+e.getInt8(0)).getTime();case hc.Master:case hc.Binary:return e;default:t.assertNever(i)}},Sc=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=mc(s);if(!e(r))return;r.type===hc.Master&&Sc(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},bc=[cc.Info,cc.SeekHead,cc.Tracks,cc.Chapters,cc.Cluster,cc.Cues,cc.Attachments,cc.Tags],gc=[cc.Timestamp,cc.SilentTracks,cc.SilentTrackNumber,cc.Position,cc.PrevSize,cc.SimpleBlock,cc.BlockGroup,cc.EncryptedBlock],yc={validateData:t=>{if(t.getUint32(0)!==cc.EBML)return!1;let e,i,s;const r=mc(t);return Sc(r.value,(({tag:t,type:r,value:a})=>(t===cc.EBMLReadVersion?e=vc(a,r):t===cc.DocType?i=vc(a,r):t===cc.DocTypeReadVersion&&(s=vc(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:e=>{let i,s,r,a,n,o,u=!1,d=!1,l=!1;return Sc(e,(({tag:t,type:e,value:c,valueSize:h})=>{if(t===cc.SeekID){const t=vc(c,e);o=fc(t)}else t!==cc.SeekPosition&&(o=void 0);return t===cc.Segment?(i=c.byteOffset,s=c.byteOffset+h):t===cc.Info?u=!0:t===cc.SeekHead?d=!0:t===cc.TimestampScale?r=vc(c,e):t===cc.Duration?a=vc(c,e):t===cc.SeekPosition&&o===cc.Cues?n=vc(c,e):u&&d&&bc.includes(t)&&(l=!0),!l})),t.assertNonNullable(i,'Failed to parse webm Segment start'),t.assertNonNullable(s,'Failed to parse webm Segment end'),t.assertNonNullable(a,'Failed to parse webm Segment duration'),r=null!=r?r:1e6,{segmentStart:Math.round(i/1e9*r*1e3),segmentEnd:Math.round(s/1e9*r*1e3),timeScale:r,segmentDuration:Math.round(a/1e9*r*1e3),cuesSeekPosition:n}},getIndexRange:e=>{if(t.isNullable(e.cuesSeekPosition))return;const i=e.segmentStart+e.cuesSeekPosition;return{from:i,to:i+1048576}},parseSegments:(e,i)=>{let s=!1,r=!1;const a=e=>t.isNonNullable(e.time)&&t.isNonNullable(e.position),n=[];let o;return Sc(e,(({tag:t,type:e,value:i})=>{switch(t){case cc.Cues:s=!0;break;case cc.CuePoint:o&&a(o)&&n.push(o),o={};break;case cc.CueTime:o&&(o.time=vc(i,e));break;case cc.CueTrackPositions:break;case cc.CueClusterPosition:o&&(o.position=vc(i,e));break;default:s&&bc.includes(t)&&(r=!0)}return!(s&&r)})),o&&a(o)&&n.push(o),n.map(((t,e)=>{const{time:s,position:r}=t,a=n[e+1];return{status:ec.NONE,time:{from:s,to:a?a.time:i.segmentDuration},byte:{from:i.segmentStart+r,to:a?i.segmentStart+a.position-1:i.segmentEnd-1}}}))},parseFeedableSegmentChunk:t=>{let e=0,i=!1;try{Sc(t,(s=>s.tag===cc.Cluster?s.tagSize<=t.byteLength?(e=s.tagSize,!1):(e+=s.tagHeaderSize,!0):!!gc.includes(s.tag)&&(e+s.tagSize<=t.byteLength&&(e+=s.tagSize,i||(i=[cc.SimpleBlock,cc.BlockGroup,cc.EncryptedBlock].includes(s.tag))),!0)))}catch(t){}return e>0&&e<=t.byteLength&&i?new DataView(t.buffer,t.byteOffset,e):null}};class Tc{constructor(e,i,s,r,{fetcher:a,tuning:n,getCurrentPosition:o}){switch(this.onLastSegment$=new t.ValueSubject(!1),this.fullyBuffered$=new t.ValueSubject(!1),this.playingRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.gaps=[],this.subscription=new t.Subscription,this.allInitsLoaded=!1,this.activeSegments=new Set,this.downloadAbortController=new Jo,this.destroyAbortController=new Jo,this.bufferLimit=1/0,this.startWith=t.abortable(this.destroyAbortController.signal,function(e){return jo(this,arguments,(function*(){const i=this.representations.get(e);t.assertNonNullable(i,`Cannot find representation ${e}`),this.playingRepresentationId=e,this.downloadingRepresentationId=e,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${i.mime}; codecs="${i.codecs}"`),this.sourceBufferTaskQueue=new rc(this.sourceBuffer),this.subscription.add(t.fromEvent(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(t.fromEvent(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))));const s=this.tuning.useFetchPriorityHints?'high':'auto';yield yield Uo(this.loadInit(i,s));const r=this.initData.get(i.id),a=this.segments.get(i.id);if(t.assertNonNullable(r,'No init buffer for starting representation'),t.assertNonNullable(a,'No segments for starting representation'),!(r instanceof ArrayBuffer))return yield Uo(void 0);let n=0;for(const t of a)t.time.from-n>=300&&this.gaps.push({representation:i.id,from:n,to:t.time.from}),n=t.time.to;t.isNonNullable(i.duration)&&i.duration-n>=300&&this.gaps.push({representation:i.id,from:n,to:i.duration}),yield yield Uo(this.sourceBufferTaskQueue.append(r,this.destroyAbortController.signal)),this.playingRepresentation$.next(this.playingRepresentationId)}))}.bind(this)),this.switchTo=t.abortable(this.destroyAbortController.signal,function(e){return jo(this,arguments,(function*(){if(e===this.downloadingRepresentationId||e===this.switchingToRepresentationId)return yield Uo(void 0);this.switchingToRepresentationId=e;const i=this.representations.get(e);t.assertNonNullable(i,`No such representation ${e}`);let s=this.initData.get(e);if(t.isNullable(s)){const t=this.tuning.useFetchPriorityHints?'high':'auto';yield yield Uo(this.loadInit(i,t))}else s instanceof Promise&&(yield yield Uo(s));if(s=this.initData.get(e),!(s&&s instanceof ArrayBuffer&&this.sourceBuffer))return yield Uo(void 0);this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=e,this.abort(),yield yield Uo(this.sourceBufferTaskQueue.append(s,this.downloadAbortController.signal));const r=this.getCurrentPosition();t.isNonNullable(r)&&this.maintain(r)}))}.bind(this)),this.fetcher=a,this.tuning=n,this.forwardBufferTarget=n.forwardBufferTargetAuto,this.getCurrentPosition=o,this.container=s,s){case ic.MP4:this.containerParser=lc;break;case ic.WEBM:this.containerParser=yc;break;default:t.assertNever(s)}this.initData=new Map(r.map((t=>[t.id,null]))),this.segments=new Map,this.representations=new Map(r.map((t=>[t.id,t]))),this.kind=e,this.mediaSource=i,this.sourceBuffer=null}abort(){for(const t of this.activeSegments)this.abortSegment(t.segment);this.activeSegments.clear(),this.downloadAbortController.abort(),this.downloadAbortController=new Jo,this.abortBuffer()}maintain(e){if(t.isNullable(this.downloadingRepresentationId)||t.isNullable(this.playingRepresentationId)||t.isNullable(this.sourceBuffer))return;const i=this.representations.get(this.downloadingRepresentationId),s=this.segments.get(this.downloadingRepresentationId);if(t.assertNonNullable(i,`No such representation ${this.downloadingRepresentationId}`),!s)return;const r=s.find((t=>e>=t.time.from&&e<t.time.to));let a=e;if(this.playingRepresentationId!==this.downloadingRepresentationId){const t=100,i=Yl(this.sourceBuffer.buffered,e),s=r?r.time.to+t:-1/0;r&&i>=r.time.to-e+t&&(a=s)}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(s,a),n.length)){let t='auto';if(this.tuning.useFetchPriorityHints&&r)if(n.includes(r))t='high';else{const e=Sl(n,0);e&&e.time.from-r.time.to>=this.forwardBufferTarget/2&&(t='low')}this.loadSegments(n,i,t)}!this.allInitsLoaded&&r&&r.status===ec.FED&&!n.length&&Yl(this.sourceBuffer.buffered,e)>3e3&&this.loadNextInit();const o=Sl(s,-1);o&&o.status===ec.FED&&(this.fullyBuffered$.next(!0),this.onLastSegment$.next(r===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){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===ec.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.forwardBufferTarget));if(-1===i)return[];let s=0;const r=[];for(let e=i;e<t.length&&s<=this.tuning.segmentRequestSize;e++){const i=t[e];if(s+=i.byte.to+1-i.byte.from,i.status!==ec.NONE)break;r.push(i)}return r}loadSegments(t,e,i='auto'){return Fo(this,void 0,void 0,(function*(){if(!t.length)return;const s=Sl(t,0).byte.from,r=Sl(t,-1).byte.to;for(const i of t)i.status=ec.DOWNLOADING,this.activeSegments.add({segment:i,loadedBytes:0,fedBytes:0,representationId:e.id});const{signal:a}=this.downloadAbortController;this.fetcher.fetchRange(e.url,s,r,{method:ac.PARAM,onProgress:(t,i)=>{if(!a.aborted)try{this.onSomeDataLoaded(t,e.id,s,i,a)}catch(t){this.error$.next({id:'SegmentFeeding',message:'Error when feeding segments',thrown:t})}},signal:a,priority:i}).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t})))}))}onSomeDataLoaded(t,e,i,s,r){var a;if(!this.activeSegments.size)return;const n=t=>{this.abortSegment(t.segment)},o=t=>{var i;this.playingRepresentationId=e,this.playingRepresentation$.next(this.playingRepresentationId),t.segment.status=ec.FED;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===ec.FED&&e.time.from===t.segment.time.from&&e.time.to===t.segment.time.to&&(e.status=ec.NONE);this.activeSegments.delete(t),this.detectGapsWhenIdle(e,[t.segment])};for(const u of this.activeSegments){const{segment:d}=u,l=d.byte.to-d.byte.from+1;if(u.representationId!==e)continue;if(r.aborted){n(u);continue}const c=d.byte.from>=i,h=d.byte.from<i+s,p=d.byte.to<=i+s;if(d.status===ec.DOWNLOADING&&c&&h&&p){d.status=ec.DOWNLOADED,this.activeSegments.delete(u);const e=new DataView(t.buffer,t.byteOffset+d.byte.from-i,Math.min(l,i+s-d.byte.from));this.sourceBufferTaskQueue.append(e,r).then((t=>t&&!r.aborted?o(u):n(u)))}else if(this.tuning.enableSubSegmentBufferFeeding&&c&&h){const e=Math.min(l,s-(d.byte.from-i));u.buffer=null!==(a=u.buffer)&&void 0!==a?a:new ArrayBuffer(l);const c=new DataView(u.buffer);for(let s=u.loadedBytes;s<e;s++)c.setUint8(s,t.getUint8(d.byte.from-i+s));u.loadedBytes=e;const h=new DataView(u.buffer,u.fedBytes,u.loadedBytes-u.fedBytes);if(l===u.loadedBytes&&u.fedBytes!==u.loadedBytes)d.status=ec.DOWNLOADED,u.fedBytes=u.loadedBytes,this.sourceBufferTaskQueue.append(h,r).then((t=>t&&!r.aborted?o(u):n(u)));else if(u.loadedBytes>u.fedBytes){const t=this.containerParser.parseFeedableSegmentChunk(h);t&&(d.status=ec.PARTIALLY_FED,u.fedBytes+=t.byteLength,this.sourceBufferTaskQueue.append(t,r).then((t=>{t&&!r.aborted||n(u)})))}}}}abortSegment(t){t.status===ec.PARTIALLY_FED?(this.sourceBufferTaskQueue.remove(t.time.from,t.time.to).then((()=>t.status=ec.NONE)),t.status=ec.NONE):t.status=ec.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);if(!i)return;const s=this.tuning.useFetchPriorityHints?'low':'auto';this.initLoadIdleCallback=requestIdleCallback((()=>Ao(this.loadInit(i,s),(()=>this.initLoadIdleCallback=null))))}loadInit(t,e){return Fo(this,void 0,void 0,(function*(){const i=this.fetcher.fetchRepresentation(t,this.containerParser,e).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)})).catch((e=>{this.initData.set(t.id,null),this.error$.next({id:'LoadInits',message:'loadInit threw',thrown:e})}));return this.initData.set(t.id,i),i}))}pruneBuffer(e){return Fo(this,void 0,void 0,(function*(){const i=this.getCurrentPosition();if(!this.sourceBuffer||!this.playingRepresentationId||t.isNullable(i))return!1;if(this.sourceBuffer.updating)return!1;const s=this.segments.get(this.playingRepresentationId);if(!s)return!1;let r=0,a=1/0,n=-1/0,o=!1;for(const t of s){if(t.time.to>=i||r>=e)break;t.status===ec.FED&&(a=Math.min(a,t.time.from),n=Math.max(n,t.time.to),r+=t.byte.to-t.byte.from)}if(o=isFinite(a)&&isFinite(n)&&(r>=e||e===1/0),!o){r=0,a=1/0,n=-1/0;for(const t of s)t.status===ec.FED&&t.time.from>i+this.forwardBufferTarget&&(a=Math.min(a,t.time.from),n=Math.max(n,t.time.to),r+=t.byte.to-t.byte.from)}return o=isFinite(a)&&isFinite(n)&&(r>=e||e===1/0),!!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=requestIdleCallback((()=>{try{this.detectGaps(t,e)}catch(t){this.error$.next({id:'GapDetection',message:'detectGaps threw',thrown:t})}finally{this.gapDetectionIdleCallback=null}})))}checkEjectedSegments(){if(t.isNullable(this.sourceBuffer)||t.isNullable(this.playingRepresentationId))return;const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=1e3*this.sourceBuffer.buffered.start(t),s=1e3*this.sourceBuffer.buffered.end(t);e.push({from:i,to:s})}const i=this.tuning.segmentTimelineTolerance;for(const t of this.segments.values())for(const s of t){const t=e.some((t=>t.from-i<=s.time.from&&t.to+i>=s.time.to));s.status!==ec.FED||t||(s.status=ec.NONE)}}}const Ec=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)},kc=(e,i)=>{var s,r,a,n,o,u,d,l,c,h,p,m,f,v,S,b,g,y,T,E,k,w,P,$;const A={video:[],audio:[],text:[]},x=(new DOMParser).parseFromString(e,'application/xml').children[0],N=x.getElementsByTagName('Period')[0],D=N.children;let _;const R=x.getAttribute('mediaPresentationDuration'),I=N.getAttribute('duration');if(R)_=Ec(R);else if(I){const e=Ec(I);t.isNonNullable(e)&&(_=e)}let C=0;const L=null!==(r=null===(s=x.getAttribute('profiles'))||void 0===s?void 0:s.split(','))&&void 0!==r?r:[],O=L.includes(tc.WEBM_AS_IN_FFMPEG)||L.includes(tc.WEBM_AS_IN_SPEC)?ic.WEBM:ic.MP4;for(const t of D){const e=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),r=null!==(a=t.getAttribute('contentType'))&&void 0!==a?a:null==e?void 0:e.split('/')[0],x=null!==(o=null===(n=t.getAttribute('profiles'))||void 0===n?void 0:n.split(','))&&void 0!==o?o:[],N=t.querySelectorAll('Representation');for(const a of N){const n=null!==(u=a.getAttribute('mimeType'))&&void 0!==u?u:e,o=null!==(l=null!==(d=a.getAttribute('codecs'))&&void 0!==d?d:s)&&void 0!==l?l:'',N=null!==(h=null!==(c=a.getAttribute('contentType'))&&void 0!==c?c:null==n?void 0:n.split('/')[0])&&void 0!==h?h:r,D=null!==(m=null===(p=t.getAttribute('profiles'))||void 0===p?void 0:p.split(','))&&void 0!==m?m:[],R=parseInt(null!==(f=a.getAttribute('width'))&&void 0!==f?f:'',10),I=parseInt(null!==(v=a.getAttribute('height'))&&void 0!==v?v:'',10),O=parseInt(null!==(S=a.getAttribute('bandwidth'))&&void 0!==S?S:'',10)/1e3,B=null!==(b=a.getAttribute('frameRate'))&&void 0!==b?b:'',M=null!==(g=a.getAttribute('quality'))&&void 0!==g?g:void 0,V=B?pl(B):void 0,F=`${null!==(y=a.getAttribute('id'))&&void 0!==y?y:(C++).toString(10)}@${'video'===N?`${I}p`:'audio'===N?`${O}Kbps`:o}`,U=null!==(k=null===(E=null===(T=a.querySelector('BaseURL'))||void 0===T?void 0:T.textContent)||void 0===E?void 0:E.trim())&&void 0!==k?k:'',j=new URL(U,i).toString(),q=[...L,...x,...D],H=null!==(P=null===(w=a.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==P?P:'',[G,Y]=H.split('-').map((t=>parseInt(t,10))),Q={from:G,to:Y},z=null===($=a.querySelector('SegmentBase'))||void 0===$?void 0:$.getAttribute('indexRange'),[W,J]=z?z.split('-').map((t=>parseInt(t,10))):[],K=z?{from:W,to:J}:void 0;if(!N||!n)continue;const X={video:Zl.VIDEO,audio:Zl.AUDIO,text:Zl.TEXT}[N];X&&A[X].push({id:F,kind:X,duration:_,profiles:q,initRange:Q,indexRange:K,bitrate:O,mime:n,codecs:o,width:R,height:I,fps:V,quality:M,url:j})}}return{container:O,representations:A}},wc=['timeupdate','progress','play','seeked','stalled'];var Pc,$c;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(Pc||(Pc={}));class Ac{constructor(e){this.element=null,this.source=null,this.manifest=null,this.subscription=new t.Subscription,this.state$=new Bo(Pc.NONE),this.currentVideoRepresentation$=new t.ValueSubject(void 0),this.error$=new t.Subject,this.lastConnectionType$=new t.ValueSubject(void 0),this.lastConnectionReused$=new t.ValueSubject(void 0),this.lastRequestFirstBytes$=new t.ValueSubject(void 0),this.forceEnded$=new t.Subject,this.gapWatchdogStarted=!1,this.destroyController=new Jo,this.initManifest=t.abortable(this.destroyController.signal,function(t,e){return jo(this,arguments,(function*(){this.element=t,this.state$.startTransitionTo(Pc.MANIFEST_LOADED);const i=yield yield Uo(this.fetcher.fetchManifest(e).catch((t=>this.error$.next({id:'LoadManifest',message:'Failed to load manifest',thrown:t}))));if(!i)return yield Uo(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 Uo(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:Kd(Object.entries(s.representations).map((([t,e])=>[t,e.filter(r)])))}),this.manifest.representations.video.length?this.state$.setState(Pc.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),yield Uo(this.manifest)}))}.bind(this)),this.initRepresentations=t.abortable(this.destroyController.signal,function(e,i){return jo(this,arguments,(function*(){t.assertNonNullable(this.manifest),t.assertNonNullable(this.element),this.state$.startTransitionTo(Pc.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const s={fetcher:this.fetcher,tuning:this.tuning.dash,getCurrentPosition:()=>this.element?1e3*this.element.currentTime:void 0};this.videoBufferManager=new Tc(Zl.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,s),this.bufferManagers=[this.videoBufferManager],t.isNonNullable(i)&&(this.audioBufferManager=new Tc(Zl.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,s),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=t.merge(...this.bufferManagers.map((t=>t.fullyBuffered$))).pipe(t.map((()=>this.bufferManagers.every((t=>t.fullyBuffered$.getValue()))))),a=t.merge(...this.bufferManagers.map((t=>t.onLastSegment$))).pipe(t.map((()=>this.bufferManagers.some((t=>t.onLastSegment$.getValue())))));this.subscription.add(t.merge(this.forceEnded$,t.combine({allBuffersFull:r,someBufferEnded:a}).pipe(t.filter((({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(t.merge(...this.bufferManagers.map((t=>t.error$))).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield yield Uo(new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)})))),this.audioBufferManager&&t.isNonNullable(i)?yield yield Uo(Promise.all([this.videoBufferManager.startWith(e),this.audioBufferManager.startWith(i)])):yield yield Uo(this.videoBufferManager.startWith(e)),this.state$.setState(Pc.REPRESENTATION_SELECTED),t.assertNonNullable(this.element),this.subscription.add(t.merge(...wc.map((e=>t.fromEvent(this.element,e))),t.fromEvent(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(t.fromEvent(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(t.fromEvent(this.element,'waiting').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&sc(this.element.buffered,1e3*this.element.currentTime)&&(this.element.currentTime=this.element.currentTime)}))),this.tick()}))}.bind(this)),this.tick=()=>{var e,i;if(!this.element||!this.videoBufferManager)return;const s=1e3*this.element.currentTime;this.videoBufferManager.maintain(s),null===(e=this.audioBufferManager)||void 0===e||e.maintain(s),!this.videoBufferManager.gaps.length&&!(null===(i=this.audioBufferManager)||void 0===i?void 0:i.gaps.length)||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=t.interval(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=e.throughputEstimator,this.tuning=e.tuning,this.fetcher=new nc({throughputEstimator:this.throughputEstimator,requestQuic:this.tuning.requestQuick})}switchRepresentation(t,e){return Fo(this,void 0,void 0,(function*(){const i={[Zl.VIDEO]:this.videoBufferManager,[Zl.AUDIO]:this.audioBufferManager,[Zl.TEXT]:null}[t];return null==i?void 0:i.switchTo(e)}))}seek(e,i){var s,r,a,n,o;let u;t.assertNonNullable(this.element),t.assertNonNullable(this.videoBufferManager),u=i||1e3*this.element.duration<=this.tuning.dashSeekInSegmentDurationThreshold||Math.abs(1e3*this.element.currentTime-e)<=this.tuning.dashSeekInSegmentAlwaysSeekDelta?e:Math.max(null!==(s=this.videoBufferManager.findSegmentStartTime(e))&&void 0!==s?s:e,null!==(a=null===(r=this.audioBufferManager)||void 0===r?void 0:r.findSegmentStartTime(e))&&void 0!==a?a:e),sc(this.element.buffered,u)||(this.videoBufferManager.abort(),null===(n=this.audioBufferManager)||void 0===n||n.abort()),this.videoBufferManager.maintain(u),null===(o=this.audioBufferManager)||void 0===o||o.maintain(u),this.element.currentTime=u/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(Pc.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'}($c||($c={}));const xc=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?Rl(a):void 0)&&void 0!==n?n:Lo({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},Nc=(t,e,i)=>{var s;const r=e.indexOf(i);return null!==(s=Sl(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:Sl(t,-1)};class Dc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo($c.STOPPED),this.elementSize$=new t.ValueSubject(void 0),this.textTracksManager=new al,this.videoTracks=[],this.audioRepresentations=new Map,this.videoTrackSwitchHistory=new wl,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(!this.videoState.getTransition())if(r.state===l.Requested&&(null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&e!==$c.STOPPED&&i!==exports.PlaybackState.STOPPED&&this.seek(r.position,r.forcePrecise),i!==exports.PlaybackState.STOPPED){if(e===$c.STOPPED)return this.videoState.startTransitionTo($c.READY),void this.prepare();switch(e){case $c.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState($c.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo($c.PLAYING),this.playIfAllowed()));case $c.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo($c.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case $c.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo($c.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}}else e!==$c.STOPPED&&(this.videoState.startTransitionTo($c.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($c.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0))},this.params=e,this.video=nl(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next($l(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new Ac({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:e,desiredState:i}=this.params,s=hl(this.video),r=t=>{e.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:t})},a=(t,e)=>this.subscription.add(t.subscribe(e,r));a(s.timeUpdate$,e.position$),a(s.durationChange$,e.duration$),a(s.ended$,e.endedEvent$),a(s.looped$,e.loopedEvent$),a(s.error$,e.error$),a(s.isBuffering$,e.isBuffering$),a(s.currentBuffer$,e.currentBuffer$),a(s.firstFrame$,e.firstFrameEvent$),a(this.player.error$,e.error$),a(this.player.lastConnectionType$,e.httpConnectionType$),a(this.player.lastConnectionReused$,e.httpConnectionReused$),a(this.player.lastRequestFirstBytes$.pipe(t.filter(t.isNonNullable),t.once()),e.firstBytesEvent$),this.subscription.add(s.seeked$.subscribe(e.seekedEvent$,r)),this.subscription.add(il(this.video,i.isLooped,r)),this.subscription.add(sl(this.video,i.volume,s.volumeState$,r)),this.subscription.add(s.volumeState$.subscribe(this.params.output.volume$,r)),a(Al(this.video),this.elementSize$),this.subscription.add(s.playing$.subscribe((()=>{this.videoState.setState($c.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),r)).add(s.pause$.subscribe((()=>{this.videoState.setState($c.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),r)).add(s.canplay$.subscribe((()=>{this.videoState.getState()===$c.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(t.filter((({to:t})=>t===Pc.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState($c.READY)})));const n=t=>e.error$.next({id:'RepresentationSwitch',message:'Switching representations threw',thrown:t});this.subscription.add(t.merge(this.player.state$.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,i.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,t.fromEvent(this.video,'progress')).subscribe((()=>{var s,r,a,o,u,d,l,c;const h=this.player.state$.getState(),p=this.player.state$.getTransition();if(h===Pc.NONE||!this.videoTracks.length)return;const m=h===Pc.MANIFEST_LOADED&&!p,f=h===Pc.REPRESENTATION_SELECTED&&!p,v=i.autoVideoTrackSwitching.getState(),S=i.videoTrack.getState(),b=null===(s=this.videoTracks.find((({track:{id:t}})=>t===S)))||void 0===s?void 0:s.track,g=e.currentVideoTrack$.getValue(),y=Yl(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),k=Math.max(b&&!v&&null!==(a=null===(r=this.audioRepresentations.get(b.id))||void 0===r?void 0:r.bitrate)&&void 0!==a?a:0,g&&null!==(u=null===(o=this.audioRepresentations.get(g.id))||void 0===o?void 0:o.bitrate)&&void 0!==u?u:0),w=Pl(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:i.autoVideoTrackLimits.getState(),reserve:k,forwardBufferHealth:E,current:g,history:this.videoTrackSwitchHistory,playbackRate:this.video.playbackRate}),P=v?null!=w?w:b:null!=b?b:w;if(i.autoVideoTrackSwitching.getTransition()&&(i.autoVideoTrackSwitching.setState(v),this.player.setBufferTarget(T)),m){const e=P&&(null===(d=this.videoTracks.find((({track:t})=>t===P)))||void 0===d?void 0:d.representation);t.assertNonNullable(e),this.player.initRepresentations(e.id,null===(l=this.audioRepresentations.get(e.id))||void 0===l?void 0:l.id)}else if(f){const t=P&&(null===(c=this.videoTracks.find((({track:t})=>t===P)))||void 0===c?void 0:c.representation);if(t){const e=this.audioRepresentations.get(t.id);this.player.switchRepresentation(Zl.VIDEO,t.id).catch(n),e&&this.player.switchRepresentation(Zl.AUDIO,e.id).catch(n)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(t.filterChanged(),t.map((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(e.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,i,e);const o=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(o.subscribe(this.syncPlayback,r))}prepare(){return Fo(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=xc(t);if(s){this.videoTracks.push({track:s,representation:t});const r=Nc(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(){Il(this.video).then((t=>{t||(this.videoState.setState($c.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}}const _c={};var Rc;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Rc||(Rc={}));const Ic=(e,i)=>new t.Observable((t=>{const s=(e,i)=>t.next(i);return e.on(i,s),()=>e.off(i,s)}));class Cc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Rc.INITIALIZING),this.textTracksManager=new al,this.trackLevels=new Map,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekState.getState();if(e!==Rc.INITIALIZING)switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&r.state===l.Requested&&this.seek(r.position),i){case exports.PlaybackState.STOPPED:switch(e){case Rc.STOPPED:break;case Rc.READY:case Rc.PLAYING:case Rc.PAUSED:this.stop();break;default:t.assertNever(e)}break;case exports.PlaybackState.PLAYING:switch(e){case Rc.PLAYING:break;case Rc.STOPPED:this.prepare();break;case Rc.READY:case Rc.PAUSED:this.playIfAllowed();break;default:t.assertNever(e)}break;case exports.PlaybackState.PAUSED:switch(e){case Rc.PAUSED:break;case Rc.STOPPED:this.prepare();break;case Rc.READY:this.videoState.setState(Rc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED);break;case Rc.PLAYING:this.pause();break;default:t.assertNever(e)}break;default:t.assertNever(i)}},this.video=nl(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next($l(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},s=window.setTimeout((()=>e('timeout')),5e3);Ao(Promise.resolve().then((function(){return i(require('hls.js'))})).then((e=>{t||(_c.Hls=e.default,_c.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(s),t=!0}))}init(){t.assertNonNullable(_c.Hls,'hls.js not loaded'),this.hls=new _c.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(Rc.STOPPED)}subscribe(){t.assertNonNullable(_c.Events,'hls.js not loaded');const{desiredState:e,output:i}=this.params,s=t=>{i.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},r=hl(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,i.position$),a(r.durationChange$,i.duration$),a(r.ended$,i.endedEvent$),a(r.looped$,i.loopedEvent$),a(r.error$,i.error$),a(r.isBuffering$,i.isBuffering$),a(r.currentBuffer$,i.currentBuffer$),a(r.firstBytes$,i.firstBytesEvent$),a(r.firstFrame$,i.firstFrameEvent$),a(r.seeked$,i.seekedEvent$),this.subscription.add(il(this.video,e.isLooped,s)),this.subscription.add(sl(this.video,e.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(Ic(this.hls,_c.Events.ERROR).subscribe((t=>{var e;t.fatal&&i.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(e=t.err)||void 0===e?void 0:e.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Rc.PLAYING),Do(e.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Rc.PAUSED),Do(e.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Rc.READY&&this.videoState.setState(Rc.READY),this.videoState.getState()===Rc.PLAYING&&this.playIfAllowed()}),s)),a(Ic(this.hls,_c.Events.MANIFEST_PARSED).pipe(t.map((({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=Rl(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:Lo({width:a,height:n});if(!o)return t;const u=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,d={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:u};return this.trackLevels.set(r,{track:d,level:e}),t.push(d),t}),[])))),i.availableVideoTracks$),a(Ic(this.hls,_c.Events.LEVEL_LOADING).pipe(t.map((({url:t})=>$l(t)))),i.hostname$),this.subscription.add(el(e.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:s}));const n=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},o=Ic(this.hls,_c.Events.LEVEL_SWITCHED).pipe(t.map((({level:t})=>n(this.hls.levels[t]))));o.pipe(t.filter(t.isNonNullable)).subscribe(i.currentVideoTrack$,s),this.subscription.add(el(e.videoTrack,(()=>{var t;return null===(t=n(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(e=>{var i;if(t.isNullable(e))return;const s=null===(i=this.trackLevels.get(e))||void 0===i?void 0:i.level;if(!s)return;const r=this.hls.levels.indexOf(s),a=this.hls.currentLevel,n=this.hls.levels[a];!n||s.bitrate>n.bitrate?this.hls.nextLevel=r:(this.hls.loadLevel=r,this.hls.loadLevel=r)}),{changed$:o.pipe(t.map((t=>null==t?void 0:t.id))),onError:s})),a(r.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,e,i);const u=t.merge(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(u.subscribe(this.syncPlayback,s))}prepare(){this.videoState.startTransitionTo(Rc.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return Fo(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(Rc.PLAYING);(yield Il(this.video))||(this.videoState.setState(Rc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(Rc.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(Rc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)}}const Lc=t=>{let e=null;if(t.QUALITY&&(e=Rl(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=Lo({width:i,height:s})}return null!=e?e:null},Oc=(t,e=t)=>Fo(void 0,void 0,void 0,(function*(){var i;const s=yield Wo(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=Kd(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,u=Lc(n);let d;n.BANDWIDTH&&(d=parseInt(n.BANDWIDTH,10)/1e3||void 0),!d&&n['AVERAGE-BANDWIDTH']&&(d=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const l=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 h=new URL(r[++t],e).toString();u&&a.push({id:o,quality:u,url:h,bandwidth:d,size:c,fps:l})}return a}));var Bc,Mc,Vc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Bc||(Bc={}));class Fc{constructor(e){var i;this.subscription=new t.Subscription,this.videoState=new Bo(Bc.STOPPED),this.textTracksManager=new al,this.manifests$=new t.ValueSubject([]),this.liveOffset=new ol,this.manifestStartTime$=new t.ValueSubject(void 0),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Bc.STOPPED&&(this.videoState.startTransitionTo(Bc.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(Bc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===Bc.STOPPED)return this.videoState.startTransitionTo(Bc.READY),void this.prepare();if(r||a){const t=this.videoState.getState();return this.videoState.setState(Bc.CHANGING_MANIFEST),this.videoState.startTransitionTo(t),this.prepare(),void(n.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:-this.liveOffset.getTotalOffset(),forcePrecise:!0}))}if((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested)return this.videoState.startTransitionTo(Bc.READY),this.seek(n.position-this.liveOffset.getTotalPausedTime()),void this.prepare();switch(e){case Bc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Bc.PAUSED),this.liveOffset.pause(),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Bc.PLAYING),this.playIfAllowed()));case Bc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Bc.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Bc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Bc.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==s?void 0:s.to)===exports.PlaybackState.PAUSED&&(Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED),this.liveOffset.pause()));case Bc.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=nl(e.container),this.params.output.element$.next(this.video);const s={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([s]),Oc(No(this.params.source.url),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.params.output.isLive$.next(!0),this.params.output.hostname$.next($l(this.params.source.url)),this.maxSeekBackTime$=new t.ValueSubject(null!==(i=e.source.maxSeekBackTime)&&void 0!==i?i: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 u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:t})},r=hl(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.ended$,e.endedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),this.subscription.add(i.isLooped.stateChangeStarted$.subscribe((()=>i.isLooped.setState(!1)),s)),this.subscription.add(sl(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Bc.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Bc.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Bc.READY&&this.videoState.setState(Bc.READY),this.videoState.getState()===Bc.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(this.maxSeekBackTime$.pipe(t.filterChanged(),t.map((t=>-t/1e3))).subscribe(this.params.output.duration$,s)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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($l(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Bc.CHANGING_MANIFEST&&this.videoState.setState(i.to),e&&e.state===l.Requested&&this.seek(e.position)}),s)),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)}),s)),this.subscription.add(t.combine({startTime:this.manifestStartTime$.pipe(t.filter(t.isNonNullable)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),s)),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();if(t.isNullable(e))return;const i=No(e.url,this.liveOffset.getTotalOffset());var s;this.video.setAttribute('src',i),this.video.load(),(s=i,Fo(void 0,void 0,void 0,(function*(){const t=yield Wo(s,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((e=>{t.isNullable(e)||this.maxSeekBackTime$.next(e)}))}playIfAllowed(){Il(this.video).then((t=>{t||(this.videoState.setState(Bc.PAUSED),this.liveOffset.pause(),Do(this.params.desiredState.playbackState,exports.PlaybackState.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'}(Mc||(Mc={}));class Uc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Mc.STOPPED),this.textTracksManager=new al,this.manifests$=new t.ValueSubject([]),this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Mc.STOPPED&&(this.videoState.startTransitionTo(Mc.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(Mc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const n=this.params.desiredState.seekState.getState();if(e===Mc.STOPPED)return this.videoState.startTransitionTo(Mc.READY),void this.prepare();if(r||a){const t=this.videoState.getState();this.videoState.setState(Mc.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(n.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:1e3*e,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&n.state===l.Requested&&this.seek(n.position),e){case Mc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Mc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Mc.PLAYING),this.playIfAllowed()));case Mc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Mc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Mc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Mc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));case Mc.CHANGING_MANIFEST:break;default:return t.assertNever(e)}},this.params=e,this.video=nl(e.container),this.params.output.element$.next(this.video);const i={id:'master',quality:exports.VideoQuality.INVARIANT,url:this.params.source.url};this.manifests$.next([i]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next($l(this.params.source.url)),Oc(this.params.source.url).then((t=>{this.manifests$.next([i,...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 u=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===u))}subscribe(){const{output:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:t})},r=hl(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(il(this.video,i.isLooped,s)),this.subscription.add(sl(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.textTracksManager.connect(this.video,i,e),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Mc.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Mc.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Mc.READY&&this.videoState.setState(Mc.READY),this.videoState.getState()===Mc.PLAYING&&this.playIfAllowed()}),s).add(r.loadedMetadata$.subscribe((()=>{const e=this.params.desiredState.seekState.getState(),i=this.videoState.getTransition(),s=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(s&&t.isNonNullable(s.to)){const t=s.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($l(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),i&&i.from===Mc.CHANGING_MANIFEST&&this.videoState.setState(i.to),e.state===l.Requested&&this.seek(e.position)}),s))),this.subscription.add(this.manifests$.pipe(t.map((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$,s));const n=t.merge(i.playbackState.stateChangeStarted$,i.seekState.stateChangeEnded$,i.videoTrack.stateChangeStarted$,i.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const e=this.selectManifest();t.isNullable(e)||(this.video.setAttribute('src',e.url),this.video.load())}playIfAllowed(){Il(this.video).then((t=>{t||(this.videoState.setState(Mc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.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'}(Vc||(Vc={}));class jc{constructor(e){this.subscription=new t.Subscription,this.videoState=new Bo(Vc.STOPPED),this.trackUrls={},this.textTracksManager=new al,this.syncPlayback=()=>{const e=this.videoState.getState(),i=this.params.desiredState.playbackState.getState(),s=this.params.desiredState.playbackState.getTransition();if(i===exports.PlaybackState.STOPPED)return void(e!==Vc.STOPPED&&(this.videoState.startTransitionTo(Vc.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(Vc.STOPPED),Do(this.params.desiredState.playbackState,exports.PlaybackState.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekState.getState();if(e===Vc.STOPPED)return this.videoState.startTransitionTo(Vc.READY),void this.prepare();if(r){const{currentTime:t}=this.video;return this.prepare(),void(a.state===l.None&&this.params.desiredState.seekState.setState({state:l.Requested,position:1e3*t,forcePrecise:!0}))}switch((null==s?void 0:s.to)!==exports.PlaybackState.PAUSED&&a.state===l.Requested&&this.seek(a.position),e){case Vc.READY:return void(i===exports.PlaybackState.PAUSED?(this.videoState.setState(Vc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED)):i===exports.PlaybackState.PLAYING&&(this.videoState.startTransitionTo(Vc.PLAYING),this.playIfAllowed()));case Vc.PLAYING:return void(i===exports.PlaybackState.PAUSED?(this.videoState.startTransitionTo(Vc.PAUSED),this.video.pause()):(null==s?void 0:s.to)===exports.PlaybackState.PLAYING&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PLAYING));case Vc.PAUSED:return void(i===exports.PlaybackState.PLAYING?(this.videoState.startTransitionTo(Vc.PLAYING),this.playIfAllowed()):(null==s?void 0:s.to)===exports.PlaybackState.PAUSED&&Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED));default:return t.assertNever(e)}},this.params=e,this.video=nl(e.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:e,desiredState:i}=this.params,s=t=>{e.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:t})},r=hl(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,s));a(r.timeUpdate$,e.position$),a(r.durationChange$,e.duration$),a(r.ended$,e.endedEvent$),a(r.looped$,e.loopedEvent$),a(r.error$,e.error$),a(r.isBuffering$,e.isBuffering$),a(r.currentBuffer$,e.currentBuffer$),a(r.firstBytes$,e.firstBytesEvent$),a(r.firstFrame$,e.firstFrameEvent$),a(r.seeked$,e.seekedEvent$),this.subscription.add(il(this.video,i.isLooped,s)),this.subscription.add(sl(this.video,i.volume,r.volumeState$,s)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,s)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Vc.PLAYING),Do(i.playbackState,exports.PlaybackState.PLAYING)}),s)).add(r.pause$.subscribe((()=>{this.videoState.setState(Vc.PAUSED),Do(i.playbackState,exports.PlaybackState.PAUSED)}),s)).add(r.canplay$.subscribe((()=>{var e;(null===(e=this.videoState.getTransition())||void 0===e?void 0:e.to)===Vc.READY&&this.videoState.setState(Vc.READY);const i=this.params.desiredState.videoTrack.getTransition();i&&t.isNonNullable(i.to)&&(this.params.desiredState.videoTrack.setState(i.to),this.params.output.currentVideoTrack$.next(this.trackUrls[i.to].track)),this.videoState.getState()===Vc.PLAYING&&this.playIfAllowed()}),s)),this.subscription.add(i.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>i.autoVideoTrackSwitching.setState(!1)),s)),this.textTracksManager.connect(this.video,i,e);const n=t.merge(i.playbackState.stateChangeStarted$,i.videoTrack.stateChangeStarted$,i.seekState.stateChangeEnded$,this.videoState.stateChangeEnded$,t.observableFrom(['init'])).pipe(t.debounce(0));this.subscription.add(n.subscribe(this.syncPlayback,s))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var e,i;const s=null!==(i=null===(e=this.params.desiredState.videoTrack.getTransition())||void 0===e?void 0:e.to)&&void 0!==i?i:this.params.desiredState.videoTrack.getState();t.assertNonNullable(s,'MpegProvider: track is not selected');let{url:r}=this.trackUrls[s];t.assertNonNullable(r,`MpegProvider: No url for ${s}`),this.params.tuning.requestQuick&&(r=Zd(r)),this.video.setAttribute('src',r),this.video.load(),this.params.output.hostname$.next($l(r))}playIfAllowed(){Il(this.video).then((t=>{t||(this.videoState.setState(Vc.PAUSED),Do(this.params.desiredState.playbackState,exports.PlaybackState.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t/1e3}}class qc{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)}}var Hc,Gc,Yc,Qc,zc,Wc,Jc,Kc,Xc,Zc,th,eh,ih,sh,rh,ah,nh;const oh=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),uh=(null===(Hc=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===Hc?void 0:Hc.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),dh=document.createElement('video'),lh={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(Yc=null===(Gc=window.SourceBuffer)||void 0===Gc?void 0:Gc.prototype)||void 0===Yc?void 0:Yc.appendBuffer)),hls:Boolean((null===(Qc=dh.canPlayType)||void 0===Qc?void 0:Qc.call(dh,'application/x-mpegurl'))||(null===(zc=dh.canPlayType)||void 0===zc?void 0:zc.call(dh,'vnd.apple.mpegURL')))},ch={mp4:Boolean(null===(Wc=dh.canPlayType)||void 0===Wc?void 0:Wc.call(dh,'video/mp4')),webm:Boolean(null===(Jc=dh.canPlayType)||void 0===Jc?void 0:Jc.call(dh,'video/webm'))},hh={h264:Boolean(null===(Xc=null===(Kc=window.MediaSource)||void 0===Kc?void 0:Kc.isTypeSupported)||void 0===Xc?void 0:Xc.call(Kc,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(th=null===(Zc=window.MediaSource)||void 0===Zc?void 0:Zc.isTypeSupported)||void 0===th?void 0:th.call(Zc,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(ih=null===(eh=window.MediaSource)||void 0===eh?void 0:eh.isTypeSupported)||void 0===ih?void 0:ih.call(eh,'video/webm; codecs="vp9"')),aac:Boolean(null===(rh=null===(sh=window.MediaSource)||void 0===sh?void 0:sh.isTypeSupported)||void 0===rh?void 0:rh.call(sh,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(nh=null===(ah=window.MediaSource)||void 0===ah?void 0:ah.isTypeSupported)||void 0===nh?void 0:nh.call(ah,'audio/webm; codecs="opus"'))},ph=(hh.h264||hh.h265)&&hh.aac,mh=!oh,fh=uh||oh,vh=!lh.hls||!fh;const Sh=3e4,bh=18e4,gh=3,yh=100,Th={cacheDuration:12e4},Eh={maxPausedTime:3e4,chunkDuration:5e3,maxParallelRequests:5},kh={maxPausedTime:3e4},wh={maxPausedTime:3e4};class Ph{constructor(e){this.current$=new t.ValueSubject({type:void 0}),this.providerError$=new t.Subject,this.noAvailableProvidersError$=new t.Subject,this.providerOutput={position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),volume$:new t.ValueSubject({muted:!1,volume:1}),currentVideoTrack$:new t.ValueSubject(void 0),availableVideoTracks$:new t.ValueSubject([]),autoVideoTrackLimitingAvailable$:new t.ValueSubject(!1),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),error$:new t.Subject,willSeekEvent$:new t.Subject,seekedEvent$:new t.Subject,loopedEvent$:new t.Subject,endedEvent$:new t.Subject,firstBytesEvent$:new t.Subject,firstFrameEvent$:new t.Subject,isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),element$:new t.ValueSubject(void 0)},this.subscription=new t.Subscription,this.params=e,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:i}=this.params.tuning,s=i.length?[...e.screenFormatsPriority.filter((t=>!i.includes(t))),...e.screenFormatsPriority.filter((t=>i.includes(t)))]:e.screenFormatsPriority;this.screenFormatsIterator=new qc(s.filter((i=>t.isNonNullable(e.sources[i]))).filter((e=>{switch(e){case exports.VideoFormat.DASH:return lh.mse&&ch.mp4&&ph&&mh;case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_SEP_VK:return lh.mse&&ch.mp4&&ph;case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_WEBM_VK:case exports.VideoFormat.DASH_LIVE_WEBM:return lh.mse&&ch.webm&&hh.vp9&&hh.opus;case exports.VideoFormat.DASH_LIVE:case exports.VideoFormat.DASH_ONDEMAND:return lh.mse&&ch.mp4&&ph;case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_LIVE:case exports.VideoFormat.HLS_ONDEMAND:return lh.hls&&ch.mp4&&fh;case exports.VideoFormat.HLS_JS:return lh.mse&&ch.mp4&&ph&&vh;case exports.VideoFormat.MPEG:return ch.mp4;default:return t.assertNever(e)}}))),this.chromecastFormatsIterator=new qc(e.chromecastFormatsPriority.filter((i=>t.isNonNullable(e.sources[i]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const e=this.chooseDestination(),i=this.chooseFormat(e);if(t.isNullable(i))return void this.handleNoFormatsError(e);let s;try{s=this.createProvider(e,i)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}s?this.current$.next({type:i,provider:s,destination:e}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const e=this.current$.getValue().destination;t.assertNonNullable(e,'No current provider'),this.skipFormat(e),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!==l.None;this.params.desiredState.seekState.setState({state:l.Requested,position:s?i.position:e,forcePrecise:!!s&&i.forcePrecise}),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(e,i){switch(this.log({message:`createProvider: ${e}:${i}`}),e){case n.SCREEN:return this.createScreenProvider(i);case n.CHROMECAST:return this.createChromecastProvider(i);default:return t.assertNever(e)}}createScreenProvider(e){const{sources:i,container:s,desiredState:r}=this.params,a=this.providerOutput;switch(e){case exports.VideoFormat.DASH:{const n=i[e];return t.assertNonNullable(n),new Xl({container:s,source:n,desiredState:r,output:a,config:Th,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP_VK:case exports.VideoFormat.DASH_WEBM_VK:{const n=i[e];return t.assertNonNullable(n),new Dc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_SEP:case exports.VideoFormat.DASH_WEBM:case exports.VideoFormat.DASH_ONDEMAND:case exports.VideoFormat.DASH_LIVE_WEBM:{const n=i[e];return t.assertNonNullable(n),new _l({container:s,source:n,desiredState:r,output:a,format:e,config:wh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS:case exports.VideoFormat.HLS_ONDEMAND:{const n=i[e];return t.assertNonNullable(n),new Uc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_LIVE:{const n=i[e];return t.assertNonNullable(n),new Fc({container:s,source:n,desiredState:r,output:a,config:kh,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.HLS_JS:{const n=i[e];return t.assertNonNullable(n),new Cc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.MPEG:{const n=i[e];return t.assertNonNullable(n),new jc({container:s,source:n,desiredState:r,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}case exports.VideoFormat.DASH_LIVE:{const n=i[e];return t.assertNonNullable(n),new Hl({container:s,source:n,desiredState:r,output:a,config:Eh,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return t.assertNever(e)}}createChromecastProvider(e){const{sources:i,container:s,desiredState:r,meta:a}=this.params,n=this.providerOutput,o=this.params.dependencies.chromecastInitializer.connection$.getValue();return t.assertNonNullable(o),new Vo({connection:o,meta:a,container:s,source:i,format:e,desiredState:r,output:n,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?n.CHROMECAST:n.SCREEN}chooseFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case n.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return t.assertNever(e)}}skipFormat(e){switch(e){case n.SCREEN:return this.screenFormatsIterator.next();case n.CHROMECAST:return this.chromecastFormatsIterator.next();default:return t.assertNever(e)}}handleNoFormatsError(e){switch(e){case n.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case n.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return t.assertNever(e)}}initProviderErrorHandling(){let e=[],i=0;const s=new t.Subscription;var r;return s.add(t.merge(this.providerOutput.error$,(r={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Sh,position$:this.providerOutput.position$,providerChanged$:this.current$},new t.Observable((e=>{const i=new t.Subscription,s=r.desiredPlaybackState$.stateChangeStarted$.pipe(t.map((({from:t,to:e})=>`${t}-${e}`))),a=r.desiredPlaybackState$.stateChangeEnded$,n=r.providerChanged$,o=new t.Subject;let u=0,d='unknown';return i.add(s.subscribe((t=>{u&&clearTimeout(u),d=t,u=window.setTimeout((()=>o.next(d)),r.maxTransitionInterval)}))),i.add(a.subscribe((()=>{clearTimeout(u),d='unknown',u=0}))),i.add(n.subscribe((()=>{u&&clearTimeout(u),d=d?d+'*':'reset',u=window.setTimeout((()=>o.next(d)),r.maxTransitionInterval)}))),i.add(o.subscribe(e)),()=>{clearTimeout(u),i.unsubscribe()}}))).pipe(t.map((t=>({id:`ProviderHangup:${t}`,message:`A ${t} failed to complete within reasonable time`}))))).subscribe(this.providerError$)),s.add(this.providerError$.pipe(t.throttle(yh,{leading:!1,trailing:!0})).subscribe((()=>{const s=Date.now();this.current$.getValue().destination===n.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):t.isNonNullable(e[i])&&s<e[i]+bh?(e=[],this.switchToNextProvider()):(e[i]=s,this.reinitProvider()),i=(i+1)%gh}))),s}}const $h=(t,e,i)=>i*e+(1-i)*t;class Ah{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.ValueSubject(e.initial),this.debounced$=new t.ValueSubject(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new El(`raw_${s}`),this.smoothedSeries$=new El(`smoothed_${s}`),this.reportedSeries$=new El(`reported_${s}`),this.rawSeries$.next(e.initial),this.smoothedSeries$.next(e.initial),this.reportedSeries$.next(e.initial)}next(e){let i=0,s=0;for(let t=0;t<this.pastMeasures.length;t++)void 0!==this.pastMeasures[t]&&(i+=Math.pow(this.pastMeasures[t]-this.smoothed,2),s++);i/=s;const r=Math.sqrt(i),a=this.smoothed+this.params.deviationFactor*r,n=this.smoothed-this.params.deviationFactor*r;this.pastMeasures[this.measuresCursor]=e,this.measuresCursor=(this.measuresCursor+1)%this.pastMeasures.length,this.rawSeries$.next(e),this.slow=$h(this.slow,e,this.params.emaAlphaSlow),this.fast=$h(this.fast,e,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||(t.isNullable(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed))}}var xh;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(xh||(xh={}));const Nh=new Map;let Dh=xh.RUNTIME;const _h=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(_h,'test'),localStorage.removeItem(_h),Dh=xh.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(_h),Dh=xh.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Dh=xh.RUNTIME}}})();const Rh=(e,i)=>{switch(Dh){case xh.LOCAL_STORAGE:try{localStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case xh.SESSION_STORAGE:try{sessionStorage.setItem(e,i)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case xh.RUNTIME:return void Nh.set(e,i);default:t.assertNever(Dh)}},Ih=window.navigator.connection,Ch=()=>{const e=null==Ih?void 0:Ih.downlink;if(t.isNonNullable(e)&&10!==e)return 1e3*e},Lh=()=>{const e=null==Ih?void 0:Ih.rtt;if(t.isNonNullable(e)&&3e3!==e)return e},Oh=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class Bh{constructor(e){var i,s;this.subscription=new t.Subscription,this.concurrentDownloads=new Set,this.tuningConfig=e;const r=Bh.load('one_video_throughput')||(e.useBrowserEstimation?Ch():void 0)||5e3,a=null!==(s=null!==(i=Bh.load('one_video_rtt'))&&void 0!==i?i:e.useBrowserEstimation?Lh():void 0)&&void 0!==s?s:0;if(this.throughput$=new t.ValueSubject(r),this.rtt$=new t.ValueSubject(a),this.rttAdjustedThroughput$=new t.ValueSubject(Oh(r,a,e.rttPenaltyRequestSize)),this.throughput=new Ah({initial:r,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'throughput'}),this.rtt=new Ah({initial:a,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,deviationDepth:e.deviationDepth,deviationFactor:e.deviationFactor,label:'rtt'}),e.useBrowserEstimation){const e=()=>{const e=Ch();e&&this.throughput.next(e);const i=Lh();t.isNonNullable(i)&&this.rtt.next(i)};Ih&&'onchange'in Ih&&this.subscription.add(t.fromEvent(Ih,'change').subscribe(e)),e()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Rh('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Rh('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(t.combine({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(t.map((({throughput:t,rtt:i})=>Oh(t,i,e.rttPenaltyRequestSize))),t.filter((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(e){let i=0,s=t.now();const r=new t.Subscription;switch(this.subscription.add(r),this.concurrentDownloads.add(e),e.readyState){case 4:break;case 3:case 2:r.add(t.fromEvent(e,'progress').pipe(t.once()).subscribe((e=>{i=e.loaded,s=t.now()})));break;case 1:case 0:r.add(t.fromEvent(e,'loadstart').subscribe((()=>{i=0,s=t.now()})))}r.add(t.fromEvent(e,'loadend').subscribe((a=>{if(200===e.status){const e=a.loaded,r=t.now(),n=e-i,o=r-s;this.addRawSpeed(n,o,1)}this.concurrentDownloads.delete(e),r.unsubscribe()})))}trackStream(e){const i=e.getReader();if(!i)return void e.cancel('Could not get reader');let s=0;const r=t.now();let a=0,n=t.now();const o=t=>{this.concurrentDownloads.delete(e),i.releaseLock(),e.cancel(`Throughput Estimator error: ${t}`).catch((()=>{}))},u=({done:d,value:l})=>Fo(this,void 0,void 0,(function*(){d?(this.addRawSpeed(s,t.now()-r,1),this.concurrentDownloads.delete(e)):l&&(s+=l.byteLength,a+=l.byteLength,a>=this.tuningConfig.streamMinSampleSize&&t.now()-n>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(a,t.now()-n,this.concurrentDownloads.size),a=0,n=t.now()),yield null==i?void 0:i.read().then(u,o))}));this.concurrentDownloads.add(e),null==i||i.read().then(u,o)}addRawSpeed(t,e,i=1){if(Bh.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(e){var i;const s=(e=>{var i,s;switch(Dh){case xh.LOCAL_STORAGE:return null!==(i=localStorage.getItem(e))&&void 0!==i?i:void 0;case xh.SESSION_STORAGE:return null!==(s=sessionStorage.getItem(e))&&void 0!==s?s:void 0;case xh.RUNTIME:return Nh.get(e);default:t.assertNever(Dh)}})(e);if(t.isNonNullable(s))return null!==(i=parseInt(s,10))&&void 0!==i?i:void 0}}const Mh={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},enableTelemetryAtStart:!1,formatsToAvoid:[exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP,exports.VideoFormat.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 Vh=(e=(t=>t))=>({playbackState:i,seekState:s,playbackAbort$:r,looped$:a,position$:n})=>new t.Observable((o=>{let u;const d=i.transitionEnded$.pipe(t.filter((t=>(t.from===exports.PlaybackState.PAUSED||t.from===exports.PlaybackState.STOPPED)&&t.to===exports.PlaybackState.PLAYING))),c=i.stateChangeEnded$.pipe(t.filter((t=>t.from===exports.PlaybackState.PLAYING&&t.to===exports.PlaybackState.PAUSED))),h=s.stateChangeEnded$.pipe(t.filter((({to:t})=>{var e,s;return t.state===l.Requested&&(null!==(s=null===(e=i.getTransition())||void 0===e?void 0:e.from)&&void 0!==s?s:i.getState())===exports.PlaybackState.PLAYING}))),p=s.stateChangeEnded$.pipe(t.filter((({from:t,to:e})=>{var s,r;return t.state===l.Applying&&e.state===l.None&&(null!==(r=null===(s=i.getTransition())||void 0===s?void 0:s.from)&&void 0!==r?r:i.getState())===exports.PlaybackState.PLAYING}))),m=t.merge(d,p).pipe(t.map((()=>e(n.getValue())))),f=t.merge(t.merge(c,h,r).pipe(t.map((()=>e(n.getValue())))),a.pipe(t.map(e)));return(new t.Subscription).add(m.subscribe((t=>{u=e(t)}))).add(f.subscribe((i=>{const s=e(i);if(t.isNullable(u)||u===s)return;const r={start:u,end:s};u=void 0,o.next(r)})))})),Fh=Vh((t=>t)),Uh=Vh((t=>Math.round(1e3*t)+Date.now())),jh={[n.SCREEN]:{vod:[exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS_JS,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE,exports.VideoFormat.DASH_LIVE,exports.VideoFormat.DASH_LIVE_WEBM]},[n.CHROMECAST]:{vod:[exports.VideoFormat.DASH_WEBM_VK,exports.VideoFormat.DASH_WEBM,exports.VideoFormat.DASH_SEP_VK,exports.VideoFormat.DASH_SEP,exports.VideoFormat.DASH_ONDEMAND,exports.VideoFormat.HLS,exports.VideoFormat.HLS_ONDEMAND,exports.VideoFormat.MPEG],live:[exports.VideoFormat.HLS_LIVE]}};Object.defineProperty(exports,'Observable',{enumerable:!0,get:function(){return t.Observable}}),Object.defineProperty(exports,'Subject',{enumerable:!0,get:function(){return t.Subject}}),Object.defineProperty(exports,'Subscription',{enumerable:!0,get:function(){return t.Subscription}}),Object.defineProperty(exports,'ValueSubject',{enumerable:!0,get:function(){return t.ValueSubject}}),exports.Player=class{constructor(e={}){if(this.subscription=new t.Subscription,this.logger=new t.Logger,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Bo(exports.PlaybackState.STOPPED),seekState:new Bo({state:l.None}),volume:new Bo({volume:1,muted:!1}),videoTrack:new Bo(void 0),autoVideoTrackSwitching:new Bo(!0),autoVideoTrackLimits:new Bo({}),isLooped:new Bo(!1),externalTextTracks:new Bo([]),currentTextTrack:new Bo(void 0),textTrackCuesSettings:new Bo({})},this.info={playbackState$:new t.ValueSubject(exports.PlaybackState.STOPPED),position$:new t.ValueSubject(0),duration$:new t.ValueSubject(1/0),muted$:new t.ValueSubject(!1),volume$:new t.ValueSubject(1),availableQualities$:new t.ValueSubject([]),availableQualitiesFps$:new t.ValueSubject({}),currentQuality$:new t.ValueSubject(void 0),isAutoQualityEnabled$:new t.ValueSubject(!0),autoQualityLimitingAvailable$:new t.ValueSubject(!1),autoQualityLimits$:new t.ValueSubject({}),currentBuffer$:new t.ValueSubject(void 0),isBuffering$:new t.ValueSubject(!0),isStalled$:new t.ValueSubject(!1),isEnded$:new t.ValueSubject(!1),isLooped$:new t.ValueSubject(!1),isLive$:new t.ValueSubject(void 0),liveTime$:new t.ValueSubject(void 0),currentFormat$:new t.ValueSubject(void 0),availableTextTracks$:new t.ValueSubject([]),currentTextTrack$:new t.ValueSubject(void 0),throughputEstimation$:new t.ValueSubject(void 0),rttEstimation$:new t.ValueSubject(void 0),videoBitrate$:new t.ValueSubject(void 0),hostname$:new t.ValueSubject(void 0),httpConnectionType$:new t.ValueSubject(void 0),httpConnectionReused$:new t.ValueSubject(void 0),chromecastState$:new t.ValueSubject(exports.ChromecastState.NOT_AVAILABLE),chromecastDeviceName$:new t.ValueSubject(void 0),intrinsicVideoSize$:new t.ValueSubject(void 0)},this.events={started$:new t.Subject,startAttempt$:new t.Subject,willPause$:new t.Subject,willResume$:new t.Subject,willDestruct$:new t.Subject,watchCoverageRecord$:new t.Subject,watchCoverageLive$:new t.Subject,managedError$:new t.Subject,fatalError$:new t.Subject,ended$:new t.Subject,looped$:new t.Subject,seeked$:new t.Subject,willSeek$:new t.Subject,firstBytes$:new t.Subject,firstFrame$:new t.Subject,log$:new t.Subject},this.experimental={element$:new t.ValueSubject(void 0),enableDebugTelemetry$:new t.ValueSubject(!1),dumpTelemetry:yl},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(Mh)){const s=Mh[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})(e),this.chromecastInitializer=new c({receiverApplicationId:e.chromecastReceiverId,isDisabled:e.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new Bh(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(e){var i,s;return this.config=e,this.domContainer=(e=>{const i='string'==typeof e.container?document.getElementById(e.container):e.container;return t.assertNonNullable(i,`Wrong container or containerId {${e.container}}`),i})(e),this.chromecastInitializer.contentId=null===(i=e.meta)||void 0===i?void 0:i.videoId,this.providerContainer=new Ph({screenFormatsPriority:[...jh[n.SCREEN].live,...jh[n.SCREEN].vod],chromecastFormatsPriority:[...jh[n.CHROMECAST].live,...jh[n.CHROMECAST].vod],sources:e.sources,meta:null!==(s=e.meta)&&void 0!==s?s:{},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()!==exports.PlaybackState.PLAYING&&t.startTransitionTo(exports.PlaybackState.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.PAUSED&&t.startTransitionTo(exports.PlaybackState.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==exports.PlaybackState.STOPPED&&t.startTransitionTo(exports.PlaybackState.STOPPED),this}seekTime(t,e=!0){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekState.setState({state:l.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()===exports.ChromecastState.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()===exports.ChromecastState.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(e){t.assertNonNullable(this.providerContainer);const i=this.providerContainer.providerOutput.availableVideoTracks$.getValue();i.length||(this.explicitInitialQuality=e);const s=i.find((t=>t.quality===e));return s&&this.desiredState.videoTrack.startTransitionTo(s.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(){t.assertNonNullable(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(t.isNullable(e))return this.info.position$.getValue();const i=this.desiredState.seekState.getState(),s=i.state===l.None?void 0:i.position;return t.isNonNullable(s)?s/1e3:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(t.merge(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(t.map((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(t.map((t=>t.to))).subscribe(this.info.autoQualityLimits$));const e=new t.Subscription;this.subscription.add(e),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING))).subscribe((()=>{e.unsubscribe(),e.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.PLAYING||t.to===exports.PlaybackState.PAUSED)),t.debounce(0),t.once()).subscribe((t=>{const e=t.to===exports.PlaybackState.PLAYING,i=this.info.muted$.getValue(),s=e?i?exports.StartStatus.SuccessWithoutSound:exports.StartStatus.SuccessWithSound:exports.StartStatus.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((t=>t.to===exports.PlaybackState.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 exports.PlaybackState.PAUSED:this.events.willPause$.next();break;case exports.PlaybackState.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekState.getState();t.state===l.Requested?this.desiredState.seekState.setState(Object.assign(Object.assign({},t),{state:l.Applying})):this.events.managedError$.next({id:`WillSeekIn${t.state}`,message:'Received unexpeceted willSeek$'})}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{this.desiredState.seekState.getState().state===l.Applying&&(this.desiredState.seekState.setState({state:l.None}),this.events.seeked$.next())}))).add(e.current$.pipe(t.map((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(t.map((t=>t.destination)),t.filterChanged()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(t.map((t=>t.map((({quality:t})=>t)).sort(((t,e)=>Oo(t)?1:Oo(e)?-1:Ro(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(t.filterChanged()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(t.filterChanged()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.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(t.map((t=>t.muted)),t.filterChanged()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(t.map((t=>t.volume)),t.filterChanged()).subscribe(this.info.volume$)).add((({seekState:e,position$:i})=>t.merge(e.stateChangeEnded$.pipe(t.map((({to:t})=>{var e;return t.state===l.None?void 0:(null!==(e=t.position)&&void 0!==e?e:NaN)/1e3})),t.filter(t.isNonNullable)),i.pipe(t.filter((()=>e.getState().state===l.None)))))({seekState:this.desiredState.seekState,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(t.merge(e.providerOutput.endedEvent$.pipe(t.mapTo(!0)),e.providerOutput.seekedEvent$.pipe(t.mapTo(!1))).pipe(t.filterChanged()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(t.map((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$.subscribe(this.events.firstBytes$)).add(e.providerOutput.firstFrameEvent$.subscribe(this.events.firstFrame$)).add(this.throughputEstimator.throughput$.subscribe(this.info.throughputEstimation$)).add(this.throughputEstimator.rtt$.subscribe(this.info.rttEstimation$));const i=new t.ValueSubject(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>i.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>i.next(!0))));const s=new t.ValueSubject(!0);this.subscription.add(e.current$.subscribe((()=>s.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(t.filter((({to:t})=>t===exports.PlaybackState.PLAYING)),t.once()).subscribe((()=>s.next(!1))));let r=0;const a=t.merge(e.providerOutput.isBuffering$,i,s).pipe(t.map((()=>{const t=e.providerOutput.isBuffering$.getValue(),r=i.getValue()||s.getValue();return t&&!r})),t.filterChanged());this.subscription.add(a.subscribe((t=>{t?r=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(r),this.info.isStalled$.next(!1))})));const n=new t.Subscription;this.subscription.add(n);const o=t.merge(t.fromEvent(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(t.filter((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(t.filterChanged()).subscribe((e=>{switch(t.assertNonNullable(this.providerContainer),n.unsubscribe(),e){case!0:n.add(Uh({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,playbackAbort$:o,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:n.add(Fh({seekState:this.desiredState.seekState,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:o,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageRecord$))}}))}initChromecastSubscription(){this.subscription.add(this.chromecastInitializer.castState$.subscribe(this.info.chromecastState$)),this.subscription.add(this.chromecastInitializer.connection$.pipe(t.map((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(e){const i=new t.Subscription;this.subscription.add(i),this.subscription.add(e.current$.pipe(t.filterChanged(((t,e)=>t.provider===e.provider))).subscribe((()=>{i.unsubscribe(),i.add(e.providerOutput.availableVideoTracks$.pipe(t.filter((t=>t.length>0)),t.once()).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=Pl(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(t.merge(this.desiredState.videoTrack.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'start'})))),this.desiredState.seekState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'seekState',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(t.map((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(t.map((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 e;const i=null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput;t.assertNonNullable(this.providerContainer),t.assertNonNullable(i),gl={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{bl=t})),this.providerContainer.current$.subscribe((({type:t})=>Tl('provider',t))),i.duration$.subscribe((t=>Tl('duration',t))),i.availableVideoTracks$.pipe(t.filter((t=>!!t.length)),t.once()).subscribe((t=>Tl('tracks',t))),this.events.fatalError$.subscribe(new El('fatalError')),this.events.managedError$.subscribe(new El('managedError')),i.position$.subscribe(new El('position')),i.currentVideoTrack$.pipe(t.map((t=>null==t?void 0:t.quality))).subscribe(new El('quality')),i.currentBuffer$.subscribe(new El('buffer')),i.isBuffering$.subscribe(new El('isBuffering'))].forEach((t=>this.subscription.add(t))),Tl('codecs',Object.keys(hh).filter((t=>hh[t])))}},exports.SDK_VERSION='@vkontakte/videoplayer-core@2.0.61';
|