@vkontakte/videoplayer-core 2.0.46 → 2.0.47
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 +2 -2
- package/providers/DashVKProvider/lib/buffer.d.ts +9 -2
- package/providers/DashVKProvider/lib/player.d.ts +3 -0
- package/utils/tuningConfig.d.ts +1 -0
package/es2015.esm.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.47
|
|
3
|
+
* Wed, 06 Apr 2022 17:51:39 GMT
|
|
4
|
+
* https://st.mycdn.me/static/playersdk/2-0-47/doc/
|
|
5
5
|
*/
|
|
6
|
-
import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as r,fromEvent as a,assertNever as n,merge as o,tap as d,map as u,observableFrom as h,filterChanged as c,assertNonNullable as l,Observable as p,once as f,debounce as m,now as v,combine as g,filter as S,timeout as b,mapTo as y,throttle as T,Logger as E}from'@vkontakte/videoplayer-shared/es2015.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/es2015.esm.js';import w from'lodash/debounce';var $,P,A,k,_,D;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}($||($={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(P||(P={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(A||(A={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(k||(k={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(_||(_={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(D||(D={}));const R={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.2,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!1},dash:{extraInitSize:1e3,forwardBufferTarget:3e4,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3},enableTelemetryAtStart:!1,formatsToAvoid:[P.DASH_WEBM,P.DASH_SEP,P.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};class I{constructor(r){var a;this.connection$=new t(void 0),this.castState$=new t(k.NOT_AVAILABLE),this.errorEvent$=new e,this.realCastState$=new t(k.NOT_AVAILABLE),this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const n='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${n}`}),r.isDisabled||!n)return;var o;s(null===(a=window.chrome)||void 0===a?void 0:a.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(o='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();r(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();r(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(a(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{var e,s;switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(s=null===(e=i.getCurrentSession())||void 0===e?void 0:e.getMediaSession())||void 0===s?void 0:s.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return n(t.sessionState)}}))).add(o(a(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),h([i.getCastState()])).pipe(c(),u(L),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var n;const o=a===k.CONNECTED,d=s(this.connection$.getValue());if(o&&!d){const s=i.getCurrentSession();l(s);const a=s.getCastDevice(),o=null===(n=s.getMediaSession())||void 0===n?void 0:n.media.contentId;(r(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!o&&d&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===k.CONNECTED?s(this.connection$.getValue())?k.CONNECTED:k.AVAILABLE:a)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const L=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return k.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return k.AVAILABLE;case cast.framework.CastState.CONNECTING:return k.CONNECTING;case cast.framework.CastState.CONNECTED:return k.CONNECTED;default:return n(t)}};function x(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{d(s.next(t))}catch(t){a(t)}}function o(t){try{d(s.throw(t))}catch(t){a(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}d((s=s.apply(t,e||[])).next())}))}var O='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},C=function(t){return t&&t.Math==Math&&t},N=C('object'==typeof globalThis&&globalThis)||C('object'==typeof window&&window)||C('object'==typeof self&&self)||C('object'==typeof O&&O)||function(){return this}()||Function('return this')(),M=function(t){try{return!!t()}catch(t){return!0}},B=!M((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),U=B,V=Function.prototype,F=V.apply,H=V.call,q='object'==typeof Reflect&&Reflect.apply||(U?H.bind(F):function(){return H.apply(F,arguments)}),G=B,Y=Function.prototype,j=Y.bind,z=Y.call,Q=G&&j.bind(z,z),W=G?function(t){return t&&Q(t)}:function(t){return t&&function(){return z.apply(t,arguments)}},J=function(t){return'function'==typeof t},K={},X=!M((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),Z=B,tt=Function.prototype.call,et=Z?tt.bind(tt):function(){return tt.apply(tt,arguments)},it={},st={}.propertyIsEnumerable,rt=Object.getOwnPropertyDescriptor,at=rt&&!st.call({1:2},1);it.f=at?function(t){var e=rt(this,t);return!!e&&e.enumerable}:st;var nt,ot,dt=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},ut=W,ht=ut({}.toString),ct=ut(''.slice),lt=function(t){return ct(ht(t),8,-1)},pt=W,ft=M,mt=lt,vt=N.Object,gt=pt(''.split),St=ft((function(){return!vt('z').propertyIsEnumerable(0)}))?function(t){return'String'==mt(t)?gt(t,''):vt(t)}:vt,bt=N.TypeError,yt=function(t){if(null==t)throw bt('Can\'t call method on '+t);return t},Tt=St,Et=yt,wt=function(t){return Tt(Et(t))},$t=J,Pt=function(t){return'object'==typeof t?null!==t:$t(t)},At={},kt=At,_t=N,Dt=J,Rt=function(t){return Dt(t)?t:void 0},It=function(t,e){return arguments.length<2?Rt(kt[t])||Rt(_t[t]):kt[t]&&kt[t][e]||_t[t]&&_t[t][e]},Lt=W({}.isPrototypeOf),xt=It('navigator','userAgent')||'',Ot=N,Ct=xt,Nt=Ot.process,Mt=Ot.Deno,Bt=Nt&&Nt.versions||Mt&&Mt.version,Ut=Bt&&Bt.v8;Ut&&(ot=(nt=Ut.split('.'))[0]>0&&nt[0]<4?1:+(nt[0]+nt[1])),!ot&&Ct&&(!(nt=Ct.match(/Edge\/(\d+)/))||nt[1]>=74)&&(nt=Ct.match(/Chrome\/(\d+)/))&&(ot=+nt[1]);var Vt=ot,Ft=Vt,Ht=M,qt=!!Object.getOwnPropertySymbols&&!Ht((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Ft&&Ft<41})),Gt=qt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,Yt=It,jt=J,zt=Lt,Qt=Gt,Wt=N.Object,Jt=Qt?function(t){return'symbol'==typeof t}:function(t){var e=Yt('Symbol');return jt(e)&&zt(e.prototype,Wt(t))},Kt=N.String,Xt=function(t){try{return Kt(t)}catch(t){return'Object'}},Zt=J,te=Xt,ee=N.TypeError,ie=function(t){if(Zt(t))return t;throw ee(te(t)+' is not a function')},se=ie,re=function(t,e){var i=t[e];return null==i?void 0:se(i)},ae=et,ne=J,oe=Pt,de=N.TypeError,ue={exports:{}},he=N,ce=Object.defineProperty,le=function(t,e){try{ce(he,t,{value:e,configurable:!0,writable:!0})}catch(i){he[t]=e}return e},pe=N['__core-js_shared__']||le('__core-js_shared__',{}),fe=pe;(ue.exports=function(t,e){return fe[t]||(fe[t]=void 0!==e?e:{})})('versions',[]).push({version:'3.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 me=yt,ve=N.Object,ge=function(t){return ve(me(t))},Se=ge,be=W({}.hasOwnProperty),ye=Object.hasOwn||function(t,e){return be(Se(t),e)},Te=W,Ee=0,we=Math.random(),$e=Te(1..toString),Pe=function(t){return'Symbol('+(void 0===t?'':t)+')_'+$e(++Ee+we,36)},Ae=N,ke=ue.exports,_e=ye,De=Pe,Re=qt,Ie=Gt,Le=ke('wks'),xe=Ae.Symbol,Oe=xe&&xe.for,Ce=Ie?xe:xe&&xe.withoutSetter||De,Ne=function(t){if(!_e(Le,t)||!Re&&'string'!=typeof Le[t]){var e='Symbol.'+t;Re&&_e(xe,t)?Le[t]=xe[t]:Le[t]=Ie&&Oe?Oe(e):Ce(e)}return Le[t]},Me=et,Be=Pt,Ue=Jt,Ve=re,Fe=function(t,e){var i,s;if('string'===e&&ne(i=t.toString)&&!oe(s=ae(i,t)))return s;if(ne(i=t.valueOf)&&!oe(s=ae(i,t)))return s;if('string'!==e&&ne(i=t.toString)&&!oe(s=ae(i,t)))return s;throw de('Can\'t convert object to primitive value')},He=Ne,qe=N.TypeError,Ge=He('toPrimitive'),Ye=function(t,e){if(!Be(t)||Ue(t))return t;var i,s=Ve(t,Ge);if(s){if(void 0===e&&(e='default'),i=Me(s,t,e),!Be(i)||Ue(i))return i;throw qe('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),Fe(t,e)},je=Jt,ze=function(t){var e=Ye(t,'string');return je(e)?e:e+''},Qe=Pt,We=N.document,Je=Qe(We)&&Qe(We.createElement),Ke=function(t){return Je?We.createElement(t):{}},Xe=Ke,Ze=!X&&!M((function(){return 7!=Object.defineProperty(Xe('div'),'a',{get:function(){return 7}}).a})),ti=X,ei=et,ii=it,si=dt,ri=wt,ai=ze,ni=ye,oi=Ze,di=Object.getOwnPropertyDescriptor;K.f=ti?di:function(t,e){if(t=ri(t),e=ai(e),oi)try{return di(t,e)}catch(t){}if(ni(t,e))return si(!ei(ii.f,t,e),t[e])};var ui=M,hi=J,ci=/#|\.prototype\./,li=function(t,e){var i=fi[pi(t)];return i==vi||i!=mi&&(hi(e)?ui(e):!!e)},pi=li.normalize=function(t){return String(t).replace(ci,'.').toLowerCase()},fi=li.data={},mi=li.NATIVE='N',vi=li.POLYFILL='P',gi=li,Si=ie,bi=B,yi=W(W.bind),Ti=function(t,e){return Si(t),void 0===e?t:bi?yi(t,e):function(){return t.apply(e,arguments)}},Ei={},wi=X&&M((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),$i=N,Pi=Pt,Ai=$i.String,ki=$i.TypeError,_i=function(t){if(Pi(t))return t;throw ki(Ai(t)+' is not an object')},Di=X,Ri=Ze,Ii=wi,Li=_i,xi=ze,Oi=N.TypeError,Ci=Object.defineProperty,Ni=Object.getOwnPropertyDescriptor;Ei.f=Di?Ii?function(t,e,i){if(Li(t),e=xi(e),Li(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Ni(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Ci(t,e,i)}:Ci:function(t,e,i){if(Li(t),e=xi(e),Li(i),Ri)try{return Ci(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Oi('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Mi=Ei,Bi=dt,Ui=X?function(t,e,i){return Mi.f(t,e,Bi(1,i))}:function(t,e,i){return t[e]=i,t},Vi=N,Fi=q,Hi=W,qi=J,Gi=K.f,Yi=gi,ji=At,zi=Ti,Qi=Ui,Wi=ye,Ji=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 Fi(t,this,arguments)};return e.prototype=t.prototype,e},Ki=function(t,e){var i,s,r,a,n,o,d,u,h=t.target,c=t.global,l=t.stat,p=t.proto,f=c?Vi:l?Vi[h]:(Vi[h]||{}).prototype,m=c?ji:ji[h]||Qi(ji,h,{})[h],v=m.prototype;for(r in e)i=!Yi(c?r:h+(l?'.':'#')+r,t.forced)&&f&&Wi(f,r),n=m[r],i&&(o=t.noTargetGet?(u=Gi(f,r))&&u.value:f[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(d=t.bind&&i?zi(a,Vi):t.wrap&&i?Ji(a):p&&qi(a)?Hi(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Qi(d,'sham',!0),Qi(m,r,d),p&&(Wi(ji,s=h+'Prototype')||Qi(ji,s,{}),Qi(ji[s],r,a),t.real&&v&&!v[r]&&Qi(v,r,a)))},Xi=Math.ceil,Zi=Math.floor,ts=function(t){var e=+t;return e!=e||0===e?0:(e>0?Zi:Xi)(e)},es=ts,is=Math.min,ss=function(t){return t>0?is(es(t),9007199254740991):0},rs=function(t){return ss(t.length)},as=ge,ns=rs,os=ts;Ki({target:'Array',proto:!0},{at:function(t){var e=as(this),i=ns(e),s=os(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var ds,us,hs,cs,ls=It,ps=ls('Array','at');!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(ds||(ds={})),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'}(us||(us={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.FED='fed'}(hs||(hs={})),function(t){t.MP4='mp4',t.WEBM='webm'}(cs||(cs={}));var fs=t=>x(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}));const ms=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),u=e(),h=r(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(u,d)||(s(d),h&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),h&&t.setState(e.to)}),o)),c},vs=(t,e,i)=>ms(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),gs=(t,e,i,r)=>ms(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:i,onError:r}),Ss=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class bs{constructor(){this.available$=new e,this.current$=new t(void 0),this.error$=new e,this.subscription=new i,this.externalTracks=new Map}connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(ms(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(u((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(ms(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:r})),this.subscription.add(ms(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(a(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(a(t,'addtrack'),a(t,'removetrack'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(o(a(t,'change'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(a(t,'addtrack').subscribe((t=>{var i,s;null===(i=t.track)||void 0===i||i.addEventListener('cuechange',e);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(a(t,'removetrack').subscribe((t=>{var i;null===(i=t.track)||void 0===i||i.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(bs.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&Ss(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){l(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var ys=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},Ts=t=>new p((e=>{let s=0;return(new i).add(a(t,'loadstart').subscribe((()=>{s=Date.now()}))).add(a(t,'loadeddata').subscribe((()=>{e.next(Date.now()-s)})))})).pipe(f());class Es{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 ws=(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}},$s=t=>new p((e=>{let s=0;return(new i).add(a(t,'loadstart').subscribe((()=>{s=Date.now()}))).add(a(t,'loadedmetadata').subscribe((()=>{e.next(Date.now()-s)})))})).pipe(f());const Ps=t=>{const i=(e,i=(()=>{}))=>a(t,e).pipe(u(i)),r=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>a(t,e)))).pipe(u((()=>t.readyState<3)),c()),n=o(a(t,'progress'),a(t,'timeupdate')).pipe(u((()=>ws(t.buffered,t.currentTime)))),d=a(t,'volumechange').pipe(m(0),u((()=>({muted:t.muted,volume:t.volume})))),h=a(t,'error').pipe(u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),l=i('timeupdate',(()=>t.currentTime)),p=new e;let f;return l.subscribe((e=>{t.loop&&s(f)&&s(e)&&f>=t.duration-.3&&e<=.3&&p.next(f),f=e})),{playing$:i('playing'),pause$:i('pause'),canplay$:i('canplay'),ended$:i('ended'),looped$:p,error$:h,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:i('durationchange',(()=>t.duration)),isBuffering$:r,currentBuffer$:n,volumeState$:d,firstBytes$:$s(t),firstFrame$:Ts(t)}};var As;!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(As||(As={}));var ks=t=>{switch(t){case'mobile':return As.Q_144P;case'lowest':return As.Q_240P;case'low':return As.Q_360P;case'sd':case'medium':return As.Q_480P;case'hd':case'high':return As.Q_720P;case'fullhd':case'full':return As.Q_1080P;case'quadhd':case'quad':return As.Q_1440P;case'ultrahd':case'ultra':return As.Q_2160P}},_s=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};const Ds={[As.Q_144P]:{width:256,height:144},[As.Q_240P]:{width:428,height:240},[As.Q_360P]:{width:640,height:360},[As.Q_480P]:{width:856,height:480},[As.Q_720P]:{width:1280,height:720},[As.Q_1080P]:{width:1920,height:1080},[As.Q_1440P]:{width:2560,height:1440},[As.Q_2160P]:{width:3840,height:2160},[As.Q_4320P]:{width:7680,height:4320}},Rs=(t,e)=>Ds[t].height>Ds[e].height,Is=(t,e)=>Ds[t].height<Ds[e].height,Ls=Object.keys(Ds).sort(((t,e)=>Is(t,e)?-1:1)),xs=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return Ls.find((t=>{const e=Ds[t];return e.width>=s&&e.height>=i}))},Os=t=>t===As.INVARIANT;let Cs=!1,Ns={};const Ms=t=>{t(Ns)},Bs=(t,e)=>{var i;Cs&&(Ns.meta=null!==(i=Ns.meta)&&void 0!==i?i:{},Ns.meta[t]=e)};class Us{constructor(t){this.name=t}next(t){var e,i;if(!Cs)return;Ns.series=null!==(e=Ns.series)&&void 0!==e?e:{};const s=null!==(i=Ns.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Ns.series[this.name]=s}}const Vs=new Us('best_bitrate'),Fs=(t,{container:e,throughput:i,tuning:a,limits:n,forwardBufferHealth:o,currentRepresentation:d})=>{var u,h,c,l;const p=a.usePixelRatio&&null!==(u=window.devicePixelRatio)&&void 0!==u?u:1,f=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*a.containerSizeFactor,height:e.height*p*a.containerSizeFactor},m=f&&xs(f),v=t.filter((t=>!Os(t.quality))).sort(((t,e)=>Rs(t.quality,e.quality)?-1:1)),g=null===(h=ps(v,-1))||void 0===h?void 0:h.quality,S=null===(c=ps(v,0))||void 0===c?void 0:c.quality,b=r(n)||s(n.min)&&s(n.max)&&Is(n.max,n.min)||s(n.min)&&S&&Rs(n.min,S)||s(n.max)&&g&&Is(n.max,g),y=v.filter((t=>{var e;const u=!m||Is(t.quality,m),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i>=t.bitrate*(c=null!=o?o:.5,l=a.bitrateFactorAtEmptyBuffer,p=a.bitrateFactorAtFullBuffer,(l-p)*Math.pow(2,-10*c)+p);var c,l,p;const f=!a.lazyQualitySwitch||!d||(null!=o?o:.5)>=.5||((null===(e=t.size)||void 0===e?void 0:e.height)||0)<=((null==d?void 0:d.height)||0),v=b||(r(n.max)||(g=t.quality,S=n.max,Ds[g].height<=Ds[S].height))&&(r(n.min)||((t,e)=>Ds[t].height>=Ds[e].height)(t.quality,n.min));var g,S;return u&&h&&f&&v}))[0];return y&&y.bitrate&&Vs.next(y.bitrate),null!==(l=null!=y?y:v[Math.ceil((v.length-1)/2)])&&void 0!==l?l:t[0]};var Hs=(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)},qs=t=>new URL(t).hostname;const Gs=(t,e=300)=>new p((i=>{const{width:r,height:a}=t.getBoundingClientRect();if(i.next({width:r,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver(w((t=>{const e=t[0];if(!e)return;let r,a;e.contentBoxSize&&e.contentBoxSize[0]?(a=e.contentBoxSize[0].blockSize,r=e.contentBoxSize[0].inlineSize):e.contentRect&&(r=e.contentRect.width,a=e.contentRect.height),s(r)&&s(a)&&i.next({width:r,height:a})}),e));return n.observe(t),()=>n.disconnect()}));class Ys{constructor(t){this.transitionStarted$=new e,this.transitionEnded$=new e,this.transitionUpdated$=new e,this.forceChanged$=new e,this.stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$),this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var js={},zs=J,Qs=pe,Ws=W(Function.toString);zs(Qs.inspectSource)||(Qs.inspectSource=function(t){return Ws(t)});var Js,Ks,Xs,Zs=Qs.inspectSource,tr=J,er=Zs,ir=N.WeakMap,sr=tr(ir)&&/native code/.test(er(ir)),rr=ue.exports,ar=Pe,nr=rr('keys'),or=function(t){return nr[t]||(nr[t]=ar(t))},dr={},ur=sr,hr=N,cr=W,lr=Pt,pr=Ui,fr=ye,mr=pe,vr=or,gr=dr,Sr=hr.TypeError,br=hr.WeakMap;if(ur||mr.state){var yr=mr.state||(mr.state=new br),Tr=cr(yr.get),Er=cr(yr.has),wr=cr(yr.set);Js=function(t,e){if(Er(yr,t))throw new Sr('Object already initialized');return e.facade=t,wr(yr,t,e),e},Ks=function(t){return Tr(yr,t)||{}},Xs=function(t){return Er(yr,t)}}else{var $r=vr('state');gr[$r]=!0,Js=function(t,e){if(fr(t,$r))throw new Sr('Object already initialized');return e.facade=t,pr(t,$r,e),e},Ks=function(t){return fr(t,$r)?t[$r]:{}},Xs=function(t){return fr(t,$r)}}var Pr={set:Js,get:Ks,has:Xs,enforce:function(t){return Xs(t)?Ks(t):Js(t,{})},getterFor:function(t){return function(e){var i;if(!lr(e)||(i=Ks(e)).type!==t)throw Sr('Incompatible receiver, '+t+' required');return i}}},Ar=X,kr=ye,_r=Function.prototype,Dr=Ar&&Object.getOwnPropertyDescriptor,Rr=kr(_r,'name'),Ir={EXISTS:Rr,PROPER:Rr&&'something'===function(){}.name,CONFIGURABLE:Rr&&(!Ar||Ar&&Dr(_r,'name').configurable)},Lr={},xr=ts,Or=Math.max,Cr=Math.min,Nr=wt,Mr=function(t,e){var i=xr(t);return i<0?Or(i+e,0):Cr(i,e)},Br=rs,Ur=function(t){return function(e,i,s){var r,a=Nr(e),n=Br(a),o=Mr(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}},Vr={includes:Ur(!0),indexOf:Ur(!1)},Fr=ye,Hr=wt,qr=Vr.indexOf,Gr=dr,Yr=W([].push),jr=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],zr=function(t,e){var i,s=Hr(t),r=0,a=[];for(i in s)!Fr(Gr,i)&&Fr(s,i)&&Yr(a,i);for(;e.length>r;)Fr(s,i=e[r++])&&(~qr(a,i)||Yr(a,i));return a},Qr=jr,Wr=Object.keys||function(t){return zr(t,Qr)},Jr=X,Kr=wi,Xr=Ei,Zr=_i,ta=wt,ea=Wr;Lr.f=Jr&&!Kr?Object.defineProperties:function(t,e){Zr(t);for(var i,s=ta(e),r=ea(e),a=r.length,n=0;a>n;)Xr.f(t,i=r[n++],s[i]);return t};var ia,sa=It('document','documentElement'),ra=_i,aa=Lr,na=jr,oa=dr,da=sa,ua=Ke,ha=or('IE_PROTO'),ca=function(){},la=function(t){return'<script>'+t+'<\/script>'},pa=function(t){t.write(la('')),t.close();var e=t.parentWindow.Object;return t=null,e},fa=function(){try{ia=new ActiveXObject('htmlfile')}catch(t){}var t,e;fa='undefined'!=typeof document?document.domain&&ia?pa(ia):((e=ua('iframe')).style.display='none',da.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(la('document.F=Object')),t.close(),t.F):pa(ia);for(var i=na.length;i--;)delete fa.prototype[na[i]];return fa()};oa[ha]=!0;var ma,va,ga,Sa=Object.create||function(t,e){var i;return null!==t?(ca.prototype=ra(t),i=new ca,ca.prototype=null,i[ha]=t):i=fa(),void 0===e?i:aa.f(i,e)},ba=!M((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),ya=N,Ta=ye,Ea=J,wa=ge,$a=ba,Pa=or('IE_PROTO'),Aa=ya.Object,ka=Aa.prototype,_a=$a?Aa.getPrototypeOf:function(t){var e=wa(t);if(Ta(e,Pa))return e[Pa];var i=e.constructor;return Ea(i)&&e instanceof i?i.prototype:e instanceof Aa?ka:null},Da=Ui,Ra=function(t,e,i,s){s&&s.enumerable?t[e]=i:Da(t,e,i)},Ia=M,La=J,xa=Sa,Oa=_a,Ca=Ra,Na=Ne('iterator'),Ma=!1;[].keys&&('next'in(ga=[].keys())?(va=Oa(Oa(ga)))!==Object.prototype&&(ma=va):Ma=!0);var Ba=null==ma||Ia((function(){var t={};return ma[Na].call(t)!==t}));La((ma=Ba?{}:xa(ma))[Na])||Ca(ma,Na,(function(){return this}));var Ua={IteratorPrototype:ma,BUGGY_SAFARI_ITERATORS:Ma},Va={};Va[Ne('toStringTag')]='z';var Fa='[object z]'===String(Va),Ha=N,qa=Fa,Ga=J,Ya=lt,ja=Ne('toStringTag'),za=Ha.Object,Qa='Arguments'==Ya(function(){return arguments}()),Wa=qa?Ya: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=za(t),ja))?i:Qa?Ya(e):'Object'==(s=Ya(e))&&Ga(e.callee)?'Arguments':s},Ja=Wa,Ka=Fa?{}.toString:function(){return'[object '+Ja(this)+']'},Xa=Fa,Za=Ei.f,tn=Ui,en=ye,sn=Ka,rn=Ne('toStringTag'),an=function(t,e,i,s){if(t){var r=i?t:t.prototype;en(r,rn)||Za(r,rn,{configurable:!0,value:e}),s&&!Xa&&tn(r,'toString',sn)}},nn=Ua.IteratorPrototype,on=Sa,dn=dt,un=an,hn=js,cn=function(){return this},ln=N,pn=(ln.String,ln.TypeError,W);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=pn(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var fn=Ki,mn=et,vn=function(t,e,i,s){var r=e+' Iterator';return t.prototype=on(nn,{next:dn(+!s,i)}),un(t,r,!1,!0),hn[r]=cn,t},gn=_a,Sn=an,bn=Ra,yn=js,Tn=Ir.PROPER,En=Ua.BUGGY_SAFARI_ITERATORS,wn=Ne('iterator'),$n=function(){return this},Pn=wt,An=js,kn=Pr;Ei.f;var _n=function(t,e,i,s,r,a,n){vn(i,e,s);var o,d,u,h=function(t){if(t===r&&m)return m;if(!En&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},c=e+' Iterator',l=!1,p=t.prototype,f=p[wn]||p['@@iterator']||r&&p[r],m=!En&&f||h(r),v='Array'==e&&p.entries||f;if(v&&(o=gn(v.call(new t)))!==Object.prototype&&o.next&&(Sn(o,c,!0,!0),yn[c]=$n),Tn&&'values'==r&&f&&'values'!==f.name&&(l=!0,m=function(){return mn(f,this)}),r)if(d={values:h('values'),keys:a?m:h('keys'),entries:h('entries')},n)for(u in d)(En||l||!(u in p))&&bn(p,u,d[u]);else fn({target:e,proto:!0,forced:En||l},d);return n&&p[wn]!==m&&bn(p,wn,m,{name:r}),yn[e]=m,d},Dn=kn.set,Rn=kn.getterFor('Array Iterator');_n(Array,'Array',(function(t,e){Dn(this,{type:'Array Iterator',target:Pn(t),index:0,kind:e})}),(function(){var t=Rn(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'),An.Arguments=An.Array;var In=js,Ln=Ne('iterator'),xn=Array.prototype,On=Wa,Cn=re,Nn=js,Mn=Ne('iterator'),Bn=function(t){if(null!=t)return Cn(t,Mn)||Cn(t,'@@iterator')||Nn[On(t)]},Un=et,Vn=ie,Fn=_i,Hn=Xt,qn=Bn,Gn=N.TypeError,Yn=et,jn=_i,zn=re,Qn=Ti,Wn=et,Jn=_i,Kn=Xt,Xn=function(t){return void 0!==t&&(In.Array===t||xn[Ln]===t)},Zn=rs,to=Lt,eo=function(t,e){var i=arguments.length<2?qn(t):e;if(Vn(i))return Fn(Un(i,t));throw Gn(Hn(t)+' is not iterable')},io=Bn,so=function(t,e,i){var s,r;jn(t);try{if(!(s=zn(t,'return'))){if('throw'===e)throw i;return i}s=Yn(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return jn(s),i},ro=N.TypeError,ao=function(t,e){this.stopped=t,this.result=e},no=ao.prototype,oo=function(t,e,i){var s,r,a,n,o,d,u,h=i&&i.that,c=!(!i||!i.AS_ENTRIES),l=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),f=Qn(e,h),m=function(t){return s&&so(s,'normal',t),new ao(!0,t)},v=function(t){return c?(Jn(t),p?f(t[0],t[1],m):f(t[0],t[1])):p?f(t,m):f(t)};if(l)s=t;else{if(!(r=io(t)))throw ro(Kn(t)+' is not iterable');if(Xn(r)){for(a=0,n=Zn(t);n>a;a++)if((o=v(t[a]))&&to(no,o))return o;return new ao(!1)}s=eo(t,r)}for(d=s.next;!(u=Wn(d,s)).done;){try{o=v(u.value)}catch(t){so(s,'throw',t)}if('object'==typeof o&&o&&to(no,o))return o}return new ao(!1)},uo=ze,ho=Ei,co=dt,lo=oo,po=function(t,e,i){var s=uo(e);s in t?ho.f(t,s,co(0,i)):t[s]=i};Ki({target:'Object',stat:!0},{fromEntries:function(t){var e={};return lo(t,(function(t,i){po(e,t,i)}),{AS_ENTRIES:!0}),e}});var fo=At.Object.fromEntries,mo={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},vo=N,go=Wa,So=Ui,bo=js,yo=Ne('toStringTag');for(var To in mo){var Eo=vo[To],wo=Eo&&Eo.prototype;wo&&go(wo)!==yo&&So(wo,yo,To),bo[To]=bo.Array}var $o=fo,Po={};function Ao(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function ko(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,'value'in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}function _o(t,e,i){return e&&ko(t.prototype,e),i&&ko(t,i),t}function Do(t){return(Do=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Ro(t,e){return(Ro=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Io(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function Lo(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?Io(t):e}function xo(t){var e=function(){if('undefined'==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if('function'==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var i,s=Do(t);if(e){var r=Do(this).constructor;i=Reflect.construct(s,arguments,r)}else i=s.apply(this,arguments);return Lo(this,i)}}function Oo(t,e,i){return(Oo='undefined'!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,i){var s=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=Do(t)););return t}(t,e);if(s){var r=Object.getOwnPropertyDescriptor(s,e);return r.get?r.get.call(i):r.value}})(t,e,i||t)}Object.defineProperty(Po,'__esModule',{value:!0});var Co=function(){function t(){Ao(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return _o(t,[{key:'addEventListener',value:function(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}},{key:'removeEventListener',value:function(t,e){if(t in this.listeners)for(var i=this.listeners[t],s=0,r=i.length;s<r;s++)if(i[s].callback===e)return void i.splice(s,1)}},{key:'dispatchEvent',value:function(t){if(t.type in this.listeners){for(var e=this.listeners[t.type].slice(),i=0,s=e.length;i<s;i++){var r=e[i];try{r.callback.call(this,t)}catch(t){Promise.resolve().then((function(){throw t}))}r.options&&r.options.once&&this.removeEventListener(t.type,r.callback)}return!t.defaultPrevented}}}]),t}(),No=function(t){!function(t,e){if('function'!=typeof e&&null!==e)throw new TypeError('Super expression must either be null or a function');t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&Ro(t,e)}(i,Co);var e=xo(i);function i(){var t;return Ao(this,i),(t=e.call(this)).listeners||Co.call(Io(t)),Object.defineProperty(Io(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(Io(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return _o(i,[{key:'toString',value:function(){return'[object AbortSignal]'}},{key:'dispatchEvent',value:function(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),Oo(Do(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),Mo=function(){function t(){Ao(this,t),Object.defineProperty(this,'signal',{value:new No,writable:!0,configurable:!0})}return _o(t,[{key:'abort',value:function(){var t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event')).initEvent('abort',!1,!1):(t=document.createEventObject()).type='abort':t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}},{key:'toString',value:function(){return'[object AbortController]'}}]),t}();'undefined'!=typeof Symbol&&Symbol.toStringTag&&(Mo.prototype[Symbol.toStringTag]='AbortController',No.prototype[Symbol.toStringTag]='AbortSignal');var Bo=Po.AbortController=Mo;Po.AbortSignal=No;var Uo=Po.abortableFetch=function(t){'function'==typeof t&&(t={fetch:t});var e=t,i=e.fetch,s=e.Request,r=void 0===s?i.Request:s,a=e.AbortController,n=e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,o=void 0!==n&&n;if(!function(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}({fetch:i,Request:r,AbortController:a,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:i,Request:d};var d=r;(d&&!d.prototype.hasOwnProperty('signal')||o)&&((d=function(t,e){var i;e&&e.signal&&(i=e.signal,delete e.signal);var s=new r(t,e);return i&&Object.defineProperty(s,'signal',{writable:!1,enumerable:!1,configurable:!0,value:i}),s}).prototype=r.prototype);var u=i;return{fetch:function(t,e){var i=d&&d.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){var s;try{s=new DOMException('Aborted','AbortError')}catch(t){(s=new Error('Aborted')).name='AbortError'}if(i.aborted)return Promise.reject(s);var r=new Promise((function(t,e){i.addEventListener('abort',(function(){return e(s)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,u(t,e)])}return u(t,e)},Request:d}},Vo=N.Promise,Fo=Ra,Ho=It,qo=Ei,Go=X,Yo=Ne('species'),jo=Lt,zo=N.TypeError,Qo=Ne('iterator'),Wo=!1;try{var Jo=0,Ko={next:function(){return{done:!!Jo++}},return:function(){Wo=!0}};Ko[Qo]=function(){return this},Array.from(Ko,(function(){throw 2}))}catch(t){}var Xo=W,Zo=M,td=J,ed=Wa,id=Zs,sd=function(){},rd=[],ad=It('Reflect','construct'),nd=/^\s*(?:class|function)\b/,od=Xo(nd.exec),dd=!nd.exec(sd),ud=function(t){if(!td(t))return!1;try{return ad(sd,rd,t),!0}catch(t){return!1}},hd=function(t){if(!td(t))return!1;switch(ed(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return dd||!!od(nd,id(t))}catch(t){return!0}};hd.sham=!0;var cd,ld,pd,fd,md=!ad||Zo((function(){var t;return ud(ud.call)||!ud(Object)||!ud((function(){t=!0}))||t}))?hd:ud,vd=Xt,gd=N.TypeError,Sd=_i,bd=function(t){if(md(t))return t;throw gd(vd(t)+' is not a constructor')},yd=Ne('species'),Td=function(t,e){var i,s=Sd(t).constructor;return void 0===s||null==(i=Sd(s)[yd])?e:bd(i)},Ed=W([].slice),wd=N.TypeError,$d=/(?:ipad|iphone|ipod).*applewebkit/i.test(xt),Pd='process'==lt(N.process),Ad=N,kd=q,_d=Ti,Dd=J,Rd=ye,Id=M,Ld=sa,xd=Ed,Od=Ke,Cd=function(t,e){if(t<e)throw wd('Not enough arguments');return t},Nd=$d,Md=Pd,Bd=Ad.setImmediate,Ud=Ad.clearImmediate,Vd=Ad.process,Fd=Ad.Dispatch,Hd=Ad.Function,qd=Ad.MessageChannel,Gd=Ad.String,Yd=0,jd={};try{cd=Ad.location}catch(t){}var zd=function(t){if(Rd(jd,t)){var e=jd[t];delete jd[t],e()}},Qd=function(t){return function(){zd(t)}},Wd=function(t){zd(t.data)},Jd=function(t){Ad.postMessage(Gd(t),cd.protocol+'//'+cd.host)};Bd&&Ud||(Bd=function(t){Cd(arguments.length,1);var e=Dd(t)?t:Hd(t),i=xd(arguments,1);return jd[++Yd]=function(){kd(e,void 0,i)},ld(Yd),Yd},Ud=function(t){delete jd[t]},Md?ld=function(t){Vd.nextTick(Qd(t))}:Fd&&Fd.now?ld=function(t){Fd.now(Qd(t))}:qd&&!Nd?(fd=(pd=new qd).port2,pd.port1.onmessage=Wd,ld=_d(fd.postMessage,fd)):Ad.addEventListener&&Dd(Ad.postMessage)&&!Ad.importScripts&&cd&&'file:'!==cd.protocol&&!Id(Jd)?(ld=Jd,Ad.addEventListener('message',Wd,!1)):ld='onreadystatechange'in Od('script')?function(t){Ld.appendChild(Od('script')).onreadystatechange=function(){Ld.removeChild(this),zd(t)}}:function(t){setTimeout(Qd(t),0)});var Kd,Xd,Zd,tu,eu,iu,su,ru,au={set:Bd,clear:Ud},nu=N,ou=/ipad|iphone|ipod/i.test(xt)&&void 0!==nu.Pebble,du=/web0s(?!.*chrome)/i.test(xt),uu=N,hu=Ti,cu=K.f,lu=au.set,pu=$d,fu=ou,mu=du,vu=Pd,gu=uu.MutationObserver||uu.WebKitMutationObserver,Su=uu.document,bu=uu.process,yu=uu.Promise,Tu=cu(uu,'queueMicrotask'),Eu=Tu&&Tu.value;Eu||(Kd=function(){var t,e;for(vu&&(t=bu.domain)&&t.exit();Xd;){e=Xd.fn,Xd=Xd.next;try{e()}catch(t){throw Xd?tu():Zd=void 0,t}}Zd=void 0,t&&t.enter()},pu||vu||mu||!gu||!Su?!fu&&yu&&yu.resolve?((su=yu.resolve(void 0)).constructor=yu,ru=hu(su.then,su),tu=function(){ru(Kd)}):vu?tu=function(){bu.nextTick(Kd)}:(lu=hu(lu,uu),tu=function(){lu(Kd)}):(eu=!0,iu=Su.createTextNode(''),new gu(Kd).observe(iu,{characterData:!0}),tu=function(){iu.data=eu=!eu}));var wu=Eu||function(t){var e={fn:t,next:void 0};Zd&&(Zd.next=e),Xd||(Xd=e,tu()),Zd=e},$u={},Pu=ie,Au=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=Pu(e),this.reject=Pu(i)};$u.f=function(t){return new Au(t)};var ku=_i,_u=Pt,Du=$u,Ru=function(t,e){if(ku(t),_u(e)&&e.constructor===t)return e;var i=Du.f(t);return(0,i.resolve)(e),i.promise},Iu=N,Lu=function(){this.head=null,this.tail=null};Lu.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 xu,Ou,Cu,Nu='object'==typeof window,Mu=Ki,Bu=N,Uu=It,Vu=et,Fu=Vo,Hu=function(t,e,i){for(var s in e)i&&i.unsafe&&t[s]?t[s]=e[s]:Fo(t,s,e[s],i);return t},qu=an,Gu=function(t){var e=Ho(t),i=qo.f;Go&&e&&!e[Yo]&&i(e,Yo,{configurable:!0,get:function(){return this}})},Yu=ie,ju=J,zu=Pt,Qu=function(t,e){if(jo(e,t))return t;throw zo('Incorrect invocation')},Wu=Zs,Ju=oo,Ku=function(t,e){if(!e&&!Wo)return!1;var i=!1;try{var s={};s[Qo]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i},Xu=Td,Zu=au.set,th=wu,eh=Ru,ih=function(t,e){var i=Iu.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},sh=$u,rh=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},ah=Lu,nh=Pr,oh=gi,dh=Nu,uh=Pd,hh=Vt,ch=Ne('species'),lh='Promise',ph=nh.getterFor(lh),fh=nh.set,mh=nh.getterFor(lh),vh=Fu&&Fu.prototype,gh=Fu,Sh=vh,bh=Bu.TypeError,yh=Bu.document,Th=Bu.process,Eh=sh.f,wh=Eh,$h=!!(yh&&yh.createEvent&&Bu.dispatchEvent),Ph=ju(Bu.PromiseRejectionEvent),Ah=oh(lh,(function(){var t=Wu(gh),e=t!==String(gh);if(!e&&66===hh)return!0;if(!Sh.finally)return!0;if(hh>=51&&/native code/.test(t))return!1;var i=new gh((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};return(i.constructor={})[ch]=s,!(i.then((function(){}))instanceof s)||!e&&dh&&!Ph})),kh=Ah||!Ku((function(t){gh.all(t).catch((function(){}))})),_h=function(t){var e;return!(!zu(t)||!ju(e=t.then))&&e},Dh=function(t,e){var i,s,r,a=e.value,n=1==e.state,o=n?t.ok:t.fail,d=t.resolve,u=t.reject,h=t.domain;try{o?(n||(2===e.rejection&&Oh(e),e.rejection=1),!0===o?i=a:(h&&h.enter(),i=o(a),h&&(h.exit(),r=!0)),i===t.promise?u(bh('Promise-chain cycle')):(s=_h(i))?Vu(s,i,d,u):d(i)):u(a)}catch(t){h&&!r&&h.exit(),u(t)}},Rh=function(t,e){t.notified||(t.notified=!0,th((function(){for(var i,s=t.reactions;i=s.get();)Dh(i,t);t.notified=!1,e&&!t.rejection&&Lh(t)})))},Ih=function(t,e,i){var s,r;$h?((s=yh.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),Bu.dispatchEvent(s)):s={promise:e,reason:i},!Ph&&(r=Bu['on'+t])?r(s):'unhandledrejection'===t&&ih('Unhandled promise rejection',i)},Lh=function(t){Vu(Zu,Bu,(function(){var e,i=t.facade,s=t.value;if(xh(t)&&(e=rh((function(){uh?Th.emit('unhandledRejection',s,i):Ih('unhandledrejection',i,s)})),t.rejection=uh||xh(t)?2:1,e.error))throw e.value}))},xh=function(t){return 1!==t.rejection&&!t.parent},Oh=function(t){Vu(Zu,Bu,(function(){var e=t.facade;uh?Th.emit('rejectionHandled',e):Ih('rejectionhandled',e,t.value)}))},Ch=function(t,e,i){return function(s){t(e,s,i)}},Nh=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,Rh(t,!0))},Mh=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw bh('Promise can\'t be resolved itself');var s=_h(e);s?th((function(){var i={done:!1};try{Vu(s,e,Ch(Mh,i,t),Ch(Nh,i,t))}catch(e){Nh(i,e,t)}})):(t.value=e,t.state=1,Rh(t,!1))}catch(e){Nh({done:!1},e,t)}}};Ah&&(Sh=(gh=function(t){Qu(this,Sh),Yu(t),Vu(xu,this);var e=ph(this);try{t(Ch(Mh,e),Ch(Nh,e))}catch(t){Nh(e,t)}}).prototype,(xu=function(t){fh(this,{type:lh,done:!1,notified:!1,parent:!1,reactions:new ah,rejection:!1,state:0,value:void 0})}).prototype=Hu(Sh,{then:function(t,e){var i=mh(this),s=Eh(Xu(this,gh));return i.parent=!0,s.ok=!ju(t)||t,s.fail=ju(e)&&e,s.domain=uh?Th.domain:void 0,0==i.state?i.reactions.add(s):th((function(){Dh(s,i)})),s.promise},catch:function(t){return this.then(void 0,t)}}),Ou=function(){var t=new xu,e=ph(t);this.promise=t,this.resolve=Ch(Mh,e),this.reject=Ch(Nh,e)},sh.f=Eh=function(t){return t===gh||t===Cu?new Ou(t):wh(t)}),Mu({global:!0,wrap:!0,forced:Ah},{Promise:gh}),qu(gh,lh,!1,!0),Gu(lh),Cu=Uu(lh),Mu({target:lh,stat:!0,forced:Ah},{reject:function(t){var e=Eh(this);return Vu(e.reject,void 0,t),e.promise}}),Mu({target:lh,stat:!0,forced:true},{resolve:function(t){return eh(this===Cu?gh:this,t)}}),Mu({target:lh,stat:!0,forced:kh},{all:function(t){var e=this,i=Eh(e),s=i.resolve,r=i.reject,a=rh((function(){var i=Yu(e.resolve),a=[],n=0,o=1;Ju(t,(function(t){var d=n++,u=!1;o++,Vu(i,e,t).then((function(t){u||(u=!0,a[d]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise},race:function(t){var e=this,i=Eh(e),s=i.reject,r=rh((function(){var r=Yu(e.resolve);Ju(t,(function(t){Vu(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var Bh=Vo,Uh=It,Vh=J,Fh=Td,Hh=Ru;Ki({target:'Promise',proto:!0,real:!0,forced:!!Bh&&M((function(){Bh.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=Fh(this,Uh('Promise')),i=Vh(t);return this.then(i?function(i){return Hh(e,t()).then((function(){return i}))}:t,i?function(i){return Hh(e,t()).then((function(){throw i}))}:t)}});var qh,Gh=ls('Promise','finally'),Yh=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?D.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}};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(qh||(qh={}));class jh{constructor({throughputEstimator:e}={}){this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.abortAllController=new Bo,this.subscription=new i,this.fetchRepresentation=(t,e,i=0)=>x(this,void 0,void 0,(function*(){const{from:s,to:r}=t.initRange;let a,n,o=s,d=r,u=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,u=r+1===a,u&&(o=Math.min(a,s),d=Math.max(n,r))),o=Math.min(o,0),d+=i;const h=yield this.fetchRange(t.url,o,d,{method:qh.PARAM});if(!h)return null;const c=new DataView(h,s-o,r-o);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(u&&void 0!==a&&void 0!==n)p=new DataView(h,a-o,n-a);else{const i=e.getIndexRange(l);if(i){const e=yield this.fetchRange(t.url,i.from,i.to,{method:qh.PARAM});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const f=e.parseSegments(p,l);return{dataView:new DataView(h),segments:f}})),this.throughputEstimator=e}onHeadersReceived(t){const{type:e,reused:i}=Yh(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest(t){return x(this,void 0,void 0,(function*(){const e=yield Uo(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(zh);return e?(this.onHeadersReceived(e.headers),e.text()):null}))}fetchRange(t,e,i,{method:s=qh.HEADER,onProgress:r,signal:d}={}){var u,h,c;return x(this,void 0,void 0,(function*(){let l=t;const p=new Headers;switch(s){case qh.HEADER:p.append('Range',`${e}-${i}`);break;case qh.PARAM:{const t=new URL(l,location.href);t.searchParams.append('bytes',`${e}-${i}`),l=t.toString();break}default:n(s)}let f=this.abortAllController.signal;if(d){const t=new Bo;this.subscription.add(o(a(this.abortAllController.signal,'abort'),a(d,'abort')).subscribe((()=>{t.abort()}))),(this.abortAllController.signal.aborted||d.aborted)&&t.abort(),f=t.signal}const m=v(),g=yield Uo(fetch).fetch(l,{headers:p,signal:f}).catch(zh);if(null===(u=this.throughputEstimator)||void 0===u||u.addRawRtt(v()-m),!g)return null;if(!g.ok||!g.body)return Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));this.onHeadersReceived(g.headers);const[S,b]=g.body.tee(),y=S.getReader();null===(h=this.throughputEstimator)||void 0===h||h.trackStream(b);const T=parseInt(null!==(c=g.headers.get('Content-Length'))&&void 0!==c?c:'',10);let E=0;const w=new ArrayBuffer(T),$=new Uint8Array(w),P=new DataView(w);let A=!1;const k=t=>{A=!0,zh(t)},_=({done:t,value:e})=>x(this,void 0,void 0,(function*(){0===E&&this.lastRequestFirstBytes$.next(v()-m),t?null==r||r(P,E):e&&($.set(e,E),E+=e.byteLength,null==r||r(P,E),yield null==y?void 0:y.read().then(_,k))}));return yield null==y?void 0:y.read().then(_,k),A?null:w}))}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const zh=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var Qh,Wh;!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.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'}(Qh||(Qh={})),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'}(Wh||(Wh={}));const Jh={[Qh.EBML]:{type:Wh.Master},[Qh.EBMLVersion]:{type:Wh.UnsignedInteger},[Qh.EBMLReadVersion]:{type:Wh.UnsignedInteger},[Qh.EBMLMaxIDLength]:{type:Wh.UnsignedInteger},[Qh.EBMLMaxSizeLength]:{type:Wh.UnsignedInteger},[Qh.DocType]:{type:Wh.String},[Qh.DocTypeVersion]:{type:Wh.UnsignedInteger},[Qh.DocTypeReadVersion]:{type:Wh.UnsignedInteger},[Qh.Void]:{type:Wh.Binary},[Qh.Segment]:{type:Wh.Master},[Qh.SeekHead]:{type:Wh.Master},[Qh.Seek]:{type:Wh.Master},[Qh.SeekID]:{type:Wh.Binary},[Qh.SeekPosition]:{type:Wh.UnsignedInteger},[Qh.Info]:{type:Wh.Master},[Qh.TimestampScale]:{type:Wh.UnsignedInteger},[Qh.Duration]:{type:Wh.Float},[Qh.Tracks]:{type:Wh.Master},[Qh.Chapters]:{type:Wh.Master},[Qh.Cluster]:{type:Wh.Master},[Qh.Attachments]:{type:Wh.Master},[Qh.Tags]:{type:Wh.Master},[Qh.Cues]:{type:Wh.Master},[Qh.CuePoint]:{type:Wh.Master},[Qh.CueTime]:{type:Wh.UnsignedInteger},[Qh.CueTrackPositions]:{type:Wh.Master},[Qh.CueTrack]:{type:Wh.UnsignedInteger},[Qh.CueClusterPosition]:{type:Wh.UnsignedInteger},[Qh.CueRelativePosition]:{type:Wh.UnsignedInteger},[Qh.CueDuration]:{type:Wh.UnsignedInteger},[Qh.CueBlockNumber]:{type:Wh.UnsignedInteger},[Qh.CueCodecState]:{type:Wh.UnsignedInteger},[Qh.CueReference]:{type:Wh.Master},[Qh.CueRefTime]:{type:Wh.UnsignedInteger}},Kh=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=Xh(t,i),r=s in Jh,a=r?Jh[s].type:Wh.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),u=((n&255>>o)<<8*(o-1))+Xh(d),h=i+o;let c;return c=h+u>t.byteLength?new DataView(t.buffer,t.byteOffset+h):new DataView(t.buffer,t.byteOffset+h,u),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,value:c,valueSize:u}},Xh=(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},Zh=(t,e)=>{switch(e){case Wh.SignedInteger:return t.getInt8(0);case Wh.UnsignedInteger:return Xh(t);case Wh.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Wh.String:return new TextDecoder('ascii').decode(t);case Wh.UTF8:return new TextDecoder('utf-8').decode(t);case Wh.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Wh.Master:case Wh.Binary:return t;default:n(e)}},tc=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=Kh(s);if(!e(r))return;r.type===Wh.Master&&tc(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},ec=[Qh.Info,Qh.SeekHead,Qh.Tracks,Qh.Chapters,Qh.Cluster,Qh.Cues,Qh.Attachments,Qh.Tags],ic={validateData:t=>{if(t.getUint32(0)!==Qh.EBML)return!1;let e,i,s;const r=Kh(t);return tc(r.value,(({tag:t,type:r,value:a})=>(t===Qh.EBMLReadVersion?e=Zh(a,r):t===Qh.DocType?i=Zh(a,r):t===Qh.DocTypeReadVersion&&(s=Zh(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,r,a,n,o=!1,d=!1,u=!1;return tc(t,(({tag:t,type:h,value:c,valueSize:l})=>{if(t===Qh.SeekID){const t=Zh(c,h);n=Xh(t)}else t!==Qh.SeekPosition&&(n=void 0);return t===Qh.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===Qh.Info?o=!0:t===Qh.SeekHead?d=!0:t===Qh.TimestampScale?s=Zh(c,h):t===Qh.Duration?r=Zh(c,h):t===Qh.SeekPosition&&n===Qh.Cues?a=Zh(c,h):o&&d&&ec.includes(t)&&(u=!0),!u})),l(e,'Failed to parse webm Segment start'),l(i,'Failed to parse webm Segment end'),l(r,'Failed to parse webm Segment duration'),s=null!=s?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:a}},getIndexRange:t=>{if(r(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,r=!1;const a=t=>s(t.time)&&s(t.position),n=[];let o;return tc(t,(({tag:t,type:e,value:s})=>{switch(t){case Qh.Cues:i=!0;break;case Qh.CuePoint:o&&a(o)&&n.push(o),o={};break;case Qh.CueTime:o&&(o.time=Zh(s,e));break;case Qh.CueTrackPositions:break;case Qh.CueClusterPosition:o&&(o.position=Zh(s,e));break;default:i&&ec.includes(t)&&(r=!0)}return!(i&&r)})),o&&a(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:r}=t,a=n[i+1];return{status:hs.NONE,time:{from:s,to:a?a.time:e.segmentDuration},byte:{from:e.segmentStart+r,to:a?e.segmentStart+a.position-1:e.segmentEnd-1}}}))}},sc=new TextDecoder('ascii'),rc={validateData:t=>'ftyp'===sc.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=(t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=sc.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e+1;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}})(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),d=255&r();let u=n/a*1e3,h=t.byteOffset+t.byteLength+o+1;for(let t=0;t<d;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:hs.NONE,time:{from:u,to:u+o},byte:{from:h,to:h+s-1}}),u+=o,h+=s}return i}};class ac{constructor(s,r,a,o,{fetcher:d,tuning:u}){switch(this.ended$=new t(!1),this.playingRepresentation$=new t(void 0),this.error$=new e,this.subscription=new i,this.abortController=new Bo,this.allInitsLoaded=!1,this.fetcher=d,this.tuning=u,this.container=a,a){case cs.MP4:this.containerParser=rc;break;case cs.WEBM:this.containerParser=ic;break;default:n(a)}this.initData=new Map,this.segments=new Map,this.representations=new Map(o.map((t=>[t.id,t]))),this.kind=s,this.mediaSource=r,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}startWith(t){return x(this,void 0,void 0,(function*(){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`);const i=Math.ceil(1e3*e.bitrate/8*(this.tuning.extraInitSize/1e3)*1.1);this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.subscription.add(a(this.sourceBuffer,'updateEnd').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejecte by browser',thrown:t})))),this.subscription.add(a(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t}))));const s=yield this.fetcher.fetchRepresentation(e,this.containerParser,i).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return!1;const{dataView:r,segments:n}=s,o=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength-i);this.initData.set(t,o);const d=n.filter((t=>t.byte.from>=r.byteOffset&&t.byte.to<r.byteOffset+r.byteLength)),u=ps(d,-1),h=new DataView(r.buffer,r.byteOffset,d.length&&u?Math.min(u.byte.to-r.byteOffset+1,r.byteLength):r.byteLength-i);return yield this.appendDataToBuffer(h),this.segments.set(t,n.map((t=>Object.assign(Object.assign({},t),{status:t.byte.from>=r.byteOffset&&t.byte.to<r.byteOffset+r.byteLength?hs.FED:hs.NONE})))),this.maintain(0),!0}))}switchTo(t){var e;return x(this,void 0,void 0,(function*(){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=t,!this.initData.has(t))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const e=this.representations.get(t);l(e);const i=yield this.fetcher.fetchRepresentation(e,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!i)return;const{dataView:s,segments:r}=i,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(t,a),this.segments.set(t,r)}const i=this.initData.get(t);l(i,`No init buffer for ${t}`),l(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abortController.abort(),this.abortController=new Bo,this.abortBuffer(),yield this.appendDataToBuffer(i,this.abortController.signal),s(this.playingRepresentationId)&&(null===(e=this.segments.get(this.playingRepresentationId))||void 0===e||e.forEach((t=>{t.status===hs.FED&&(t.status=hs.NONE)})))}))}maintain(t){return x(this,void 0,void 0,(function*(){if(r(this.downloadingRepresentationId)||r(this.playingRepresentationId)||r(this.sourceBuffer)||this.ended$.getValue())return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);l(e),l(i);const s=i.find((e=>t>=e.time.from&&t<e.time.to));let a=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=Hs(this.sourceBuffer.buffered,t);a=t+Math.min(e,this.tuning.representationSwitchForwardBufferGap)}const n=this.selectForwardBufferSegments(i,a);n.length&&(yield this.loadSegments(n,e)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&s&&s.status===hs.FED&&!n.length&&Hs(this.sourceBuffer.buffered,t)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const o=ps(i,-1);o&&s===o&&o.status===hs.FED&&this.ended$.next(!0)}))}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.abortController.abort()}selectForwardBufferSegments(t,e){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===hs.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.tuning.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===hs.NONE)r.push(i);else if([hs.DOWNLOADING,hs.DOWNLOADED,hs.FED].includes(i.status))break}return r}loadSegments(t,e){return x(this,void 0,void 0,(function*(){if(!t.length)return;const i=ps(t,0).byte.from,s=ps(t,-1).byte.to;for(const e of t)e.status=hs.DOWNLOADING;const{signal:r}=this.abortController,a=(t,i)=>{t.status=hs.DOWNLOADED,this.appendDataToBuffer(i,r).then((i=>{!i||r.aborted?t.status=hs.NONE:(this.playingRepresentationId=e.id,this.playingRepresentation$.next(this.playingRepresentationId),t.status=hs.FED)}))},n=(e,s)=>{for(const r of t)r.status===hs.DOWNLOADING&&r.byte.from-i>=0&&r.byte.to+1-i<=s&&a(r,new DataView(e.buffer,e.byteOffset+r.byte.from-i,r.byte.to+1-r.byte.from))};return this.segmentDownloadPromise=this.segmentDownloadPromise.then((()=>x(this,void 0,void 0,(function*(){if(r.aborted){for(const e of t)e.status===hs.DOWNLOADING&&(e.status=hs.NONE);return}const o=yield this.fetcher.fetchRange(e.url,i,s,{method:qh.PARAM,onProgress:n,signal:r}),d=ps(t,-1),u=ps(this.segments.get(e.id),-1);if(!o)for(const e of t)e.status===hs.DOWNLOADING&&(e.status=hs.NONE);o&&!r.aborted&&d&&u&&d.status===hs.DOWNLOADING&&d===u&&a(d,new DataView(o,d.byte.from-i))})))).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}))}loadAllInits(){return x(this,void 0,void 0,(function*(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=Gh(Promise.all(Array.from(this.representations.entries()).map((([t,e])=>this.initData.has(t)?Promise.resolve():this.fetcher.fetchRepresentation(e,this.containerParser).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,r),this.segments.set(t,s)}))))).then((()=>{this.allInitsLoaded=!0})),(()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}))}appendDataToBuffer(t,e){return x(this,void 0,void 0,(function*(){if(l(this.sourceBuffer),e&&e.aborted)return!1;if(!this.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;if(this.sourceBuffer.updating)return yield ac.waitForBufferUpdate(this.sourceBuffer),this.appendDataToBuffer(t,e);try{this.sourceBuffer.appendBuffer(t)}catch(t){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),!1}return yield ac.waitForBufferUpdate(this.sourceBuffer),!0}))}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(t){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:t})}}checkEjectedSegments(){if(r(this.sourceBuffer)||r(this.playingRepresentationId))return;const t=this.segments.get(this.playingRepresentationId);l(t);const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=1e3*this.sourceBuffer.buffered.start(t),s=this.sourceBuffer.buffered.end(t),r=1e3*(s%1>.9?Math.round(s):s);e.push({from:i,to:r})}for(const i of t){const t=e.some((t=>t.from<=i.time.from&&t.to>=i.time.to));i.status!==hs.FED||t||(i.status=hs.NONE)}}static waitForBufferUpdate(t){return x(this,void 0,void 0,(function*(){return new Promise((e=>t?t.addEventListener('update',(()=>e())):e()))}))}}const nc=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},oc=['timeupdate','progress','play','seeked','stalled'];var dc,uc;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(dc||(dc={}));class hc{constructor(s){this.element=null,this.source=null,this.manifest=null,this.subscription=new i,this.state$=new Ys(dc.NONE),this.currentVideoRepresentation$=new t(void 0),this.error$=new e,this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.forceEnded$=new e,this.tick=()=>{var t,e;if(!this.element)return;const i=1e3*this.element.currentTime;null===(t=this.videoBufferManager)||void 0===t||t.maintain(i),null===(e=this.audioBufferManager)||void 0===e||e.maintain(i)},this.throughputEstimator=s.throughputEstimator,this.tuning=s.tuning,this.fetcher=new jh({throughputEstimator:this.throughputEstimator})}initManifest(t,e){return x(this,void 0,void 0,(function*(){this.element=t,this.subscription.add(a(t,'waiting').subscribe((()=>{t.duration-t.currentTime<this.tuning.endGapTolerance/1e3&&this.forceEnded$.next()}),(t=>this.error$.next({id:'ForceEnd',message:'Error when forcing stream end',thrown:t})))),this.state$.startTransitionTo(dc.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e);let s;try{s=((t,e)=>{var i,s,r,a,n,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$,P;const A={video:[],audio:[],text:[]},k=(new DOMParser).parseFromString(t,'application/xml').children[0],_=k.getElementsByTagName('Period')[0].children;let D=0;const R=null!==(s=null===(i=k.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==s?s:[],I=R.includes(us.WEBM_AS_IN_FFMPEG)||R.includes(us.WEBM_AS_IN_SPEC)?cs.WEBM:cs.MP4;for(const t of _){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),k=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==i?void 0:i.split('/')[0],_=null!==(n=null===(a=t.getAttribute('profiles'))||void 0===a?void 0:a.split(','))&&void 0!==n?n:[],I=t.querySelectorAll('Representation');for(const r of I){const a=null!==(o=r.getAttribute('mimeType'))&&void 0!==o?o:i,n=null!==(u=null!==(d=r.getAttribute('codecs'))&&void 0!==d?d:s)&&void 0!==u?u:'',I=null!==(c=null!==(h=r.getAttribute('contentType'))&&void 0!==h?h:null==a?void 0:a.split('/')[0])&&void 0!==c?c:k,L=null!==(p=null===(l=t.getAttribute('profiles'))||void 0===l?void 0:l.split(','))&&void 0!==p?p:[],x=parseInt(null!==(f=r.getAttribute('width'))&&void 0!==f?f:'',10),O=parseInt(null!==(m=r.getAttribute('height'))&&void 0!==m?m:'',10),C=parseInt(null!==(v=r.getAttribute('bandwidth'))&&void 0!==v?v:'',10)/1e3,N=null!==(g=r.getAttribute('frameRate'))&&void 0!==g?g:'',M=null!==(S=r.getAttribute('quality'))&&void 0!==S?S:void 0,B=N?nc(N):void 0,U=`${null!==(b=r.getAttribute('id'))&&void 0!==b?b:(D++).toString(10)}@${'video'===I?`${O}p`:'audio'===I?`${C}Kbps`:n}`,V=null!==(E=null===(T=null===(y=r.querySelector('BaseURL'))||void 0===y?void 0:y.textContent)||void 0===T?void 0:T.trim())&&void 0!==E?E:'',F=new URL(V,e).toString(),H=[...R,..._,...L],q=null!==($=null===(w=r.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==$?$:'',[G,Y]=q.split('-').map((t=>parseInt(t,10))),j={from:G,to:Y},z=null===(P=r.querySelector('SegmentBase'))||void 0===P?void 0:P.getAttribute('indexRange'),[Q,W]=z?z.split('-').map((t=>parseInt(t,10))):[],J=z?{from:Q,to:W}:void 0;if(!I||!a)continue;const K={video:ds.VIDEO,audio:ds.AUDIO,text:ds.TEXT}[I];K&&A[K].push({id:U,kind:K,profiles:H,initRange:j,indexRange:J,bitrate:C,mime:a,codecs:n,width:x,height:O,fps:B,quality:M,url:F})}}return{container:I,representations:A}})(null!=i?i:'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}l(s);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:$o(Object.entries(s.representations).map((([t,e])=>[t,e.filter(r)])))}),this.manifest.representations.video.length?this.state$.setState(dc.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}))}initRepresentations(t,e){return x(this,void 0,void 0,(function*(){l(this.manifest),l(this.element),this.state$.startTransitionTo(dc.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning.dash};this.videoBufferManager=new ac(ds.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new ac(ds.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),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$)),this.subscription.add(o(this.forceEnded$,g({video:this.videoBufferManager.ended$,audio:this.audioBufferManager.ended$}).pipe(S((t=>Object.values(t).every((t=>!0===t)))))).subscribe((()=>{var t,e;if('open'===(null===(t=this.source)||void 0===t?void 0:t.readyState))try{null===(e=this.source)||void 0===e||e.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(this.videoBufferManager.error$,this.audioBufferManager.error$).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)})));(yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)])).some((t=>!t))||(this.state$.setState(dc.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...oc.map((t=>a(this.element,t))),a(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(a(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.tick())}))}switchRepresentation(t,e){return x(this,void 0,void 0,(function*(){const i={[ds.VIDEO]:this.videoBufferManager,[ds.AUDIO]:this.audioBufferManager,[ds.TEXT]:null}[t];return l(i),i.switchTo(e)}))}seek(t){l(this.element),l(this.videoBufferManager),l(this.audioBufferManager),this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),this.element.currentTime=t/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.state$.setState(dc.NONE)}destroy(){this.subscription.unsubscribe(),this.fetcher.destroy(),this.stop(),this.source=null}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(uc||(uc={}));const cc=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?ks(a):void 0)&&void 0!==n?n:xs({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},lc=(t,e,i)=>{var s;const r=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(i);return null!==(s=ps(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:ps(t,-1)};class pc{constructor(e){this.subscription=new i,this.videoState=new Ys(uc.STOPPED),this.elementSize$=new t(void 0),this.textTracksManager=new bs,this.videoTracks=[],this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.videoState.getTransition())return;const a=null==r?void 0:r.to;if((null==i?void 0:i.to)!==$.PAUSED&&s(a)&&t!==uc.STOPPED&&e!==$.STOPPED&&this.seek(a),e!==$.STOPPED){if(t===uc.STOPPED)return this.videoState.startTransitionTo(uc.READY),void this.prepare();switch(t){case uc.READY:return void(e===$.PAUSED?(this.videoState.setState(uc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED)):e===$.PLAYING&&(this.videoState.startTransitionTo(uc.PLAYING),this.playIfAllowed()));case uc.PLAYING:return void(e===$.PAUSED?(this.videoState.startTransitionTo(uc.PAUSED),this.video.pause()):(null==i?void 0:i.to)===$.PLAYING&&_s(this.params.desiredState.playbackState,$.PLAYING));case uc.PAUSED:return void(e===$.PLAYING?(this.videoState.startTransitionTo(uc.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===$.PAUSED&&_s(this.params.desiredState.playbackState,$.PAUSED));default:return n(t)}}else t!==uc.STOPPED&&(this.videoState.startTransitionTo(uc.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(uc.STOPPED),_s(this.params.desiredState.playbackState,$.STOPPED,!0))},this.params=e,this.video=ys(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(qs(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new hc({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=Ps(this.video),r=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,r));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.firstFrame$,t.firstFrameEvent$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(S(s),f()),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(vs(this.video,e.isLooped,r)),this.subscription.add(gs(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),n(Gs(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(uc.PLAYING),_s(e.playbackState,$.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(uc.PAUSED),_s(e.playbackState,$.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===uc.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(S((({to:t})=>t===dc.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(uc.READY)}))),this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a(this.video,'progress')).subscribe((()=>{var t,i,s;const r=this.player.state$.getState(),a=this.player.state$.getTransition();if(r===dc.NONE||!this.videoTracks.length)return;const n=r===dc.MANIFEST_LOADED&&!a,o=e.autoVideoTrackSwitching.getState(),d=e.videoTrack.getState(),u=null===(t=this.videoTracks.find((({track:{id:t}})=>t===d)))||void 0===t?void 0:t.track;e.autoVideoTrackSwitching.getTransition()&&e.autoVideoTrackSwitching.setState(o);const h=Hs(this.video.buffered,1e3*this.video.currentTime),c=Math.min(h/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),p=Fs(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),forwardBufferHealth:c}),f=o?null!=p?p:u:null!=u?u:p;if(n){const t=f&&(null===(i=this.videoTracks.find((({track:t})=>t===f)))||void 0===i?void 0:i.representation);l(t);const e=lc(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);l(e),this.player.initRepresentations(t.id,e.id)}else{const t=f&&(null===(s=this.videoTracks.find((({track:t})=>t===f)))||void 0===s?void 0:s.representation);if(t){const e=lc(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(ds.VIDEO,t.id),e&&this.player.switchRepresentation(ds.AUDIO,e.id)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),u((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const d=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){return x(this,void 0,void 0,(function*(){const t=yield this.player.initManifest(this.video,this.params.source.url);this.videoTracks=[];for(const e of t.representations.video){const t=cc(e);t&&this.videoTracks.push({track:t,representation:e})}this.audioRepresentations=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}))}seek(t){this.params.output.willSeekEvent$.next(),this.player.seek(1e3*t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){fs(this.video).then((t=>{t||(this.videoState.setState(uc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED,!0))}))}}var fc;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(fc||(fc={}));var mc=(t,e=0,i=fc.OFFSET_P)=>{switch(i){case fc.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case fc.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:n(i)}return t};var vc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(vc||(vc={}));class gc{constructor(t){this.subscription=new i,this.loadMediaTimeoutSubscription=new i,this.videoState=new Ys(vc.STOPPED),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(a)};`}),i===$.STOPPED)return void(t!==vc.STOPPED&&(this.videoState.startTransitionTo(vc.STOPPED),this.stop()));if(e)return;const o=null==a?void 0:a.to;if((null==r?void 0:r.to)!==$.PAUSED&&s(o)&&t!==vc.STOPPED)this.seek(o);else switch(i){case $.PLAYING:switch(t){case vc.PLAYING:break;case vc.PAUSED:case vc.READY:this.videoState.startTransitionTo(vc.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case vc.STOPPED:this.videoState.startTransitionTo(vc.READY),this.prepare();break;default:n(t)}break;case $.PAUSED:switch(t){case vc.PLAYING:this.videoState.startTransitionTo(vc.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case vc.PAUSED:break;case vc.READY:this.videoState.startTransitionTo(vc.PAUSED),this.videoState.setState(vc.PAUSED);break;case vc.STOPPED:this.videoState.startTransitionTo(vc.READY),this.prepare();break;default:n(t)}break;default:n(i)}},this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case P.MPEG:case P.DASH:case P.DASH_SEP:case P.DASH_SEP_VK:case P.DASH_ONDEMAND:case P.DASH_WEBM:case P.DASH_WEBM_VK:case P.HLS:case P.HLS_JS:case P.HLS_ONDEMAND:return!1;case P.HLS_LIVE:case P.DASH_LIVE:case P.DASH_LIVE_WEBM:return!0;default:return n(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(o(this.videoState.stateChangeStarted$.pipe(u((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(u((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const d=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new e;t.add(i.pipe(m(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let n=NaN;t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);const a=this.params.desiredState.seekPosition.getTransition();(s(a)&&r(a.to)||Math.abs(e-n)>5)&&i.next(e),n=e}))),t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),_s(this.params.desiredState.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:n(i)}})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));d(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(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(vc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED)):(this.videoState.setState(vc.PLAYING),_s(this.params.desiredState.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.seekPosition.setState(void 0)}}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)!==vc.PAUSED&&t!==vc.PLAYING||(this.videoState.setState(vc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==vc.PLAYING&&t!==vc.PAUSED||(this.videoState.setState(vc.PLAYING),_s(this.params.desiredState.playbackState,$.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===vc.READY&&this.videoState.setState(vc.READY)}handleRemoteStop(){this.videoState.getState()!==vc.STOPPED&&this.videoState.setState(vc.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){var e;const i=this.params.source;let r,a,o;switch(t){case P.MPEG:{const e=i[t];l(e);const s=Object.keys(e).sort(((t,e)=>t===e?0:t===As.INVARIANT?1:e===As.INVARIANT?-1:Is(t,e)?1:-1))[0];l(s);const n=e[s];l(n),r=n,a='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case P.HLS:case P.HLS_ONDEMAND:{const e=i[t];l(e),r=e.url,a='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case P.DASH_SEP:case P.DASH_SEP_VK:case P.DASH_ONDEMAND:case P.DASH_WEBM_VK:case P.DASH_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case P.HLS_LIVE:{const e=i[t];l(e),r=mc(e.url),a='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case P.DASH_LIVE_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case P.HLS_JS:case P.DASH:case P.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return n(t)}const d=new chrome.cast.media.MediaInfo(null!==(e=this.params.meta.videoId)&&void 0!==e?e:r,a);d.contentUrl=r,d.streamType=o,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:h}=this.params.meta;return s(u)&&(d.metadata.title=u),s(h)&&(d.metadata.subtitle=h),d}createLoadRequest(t){var e;const i=new chrome.cast.media.LoadRequest(t);i.autoplay=!1;const s=this.params.desiredState.seekPosition.getTransition();return i.currentTime=s?this.params.output.isLive$.getValue()?0:null!==(e=s.to)&&void 0!==e?e:0:0,i}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(b(7e3).subscribe((()=>e('timeout(7000)'))))}));Gh(Promise.race([e,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});const t=this.params.desiredState.seekPosition;t.getTransition()&&t.setState(void 0),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)}`})}}var Sc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Sc||(Sc={}));class bc{constructor(t){this.subscription=new i,this.videoState=new Ys(Sc.STOPPED),this.trackUrls={},this.textTracksManager=new bs,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===$.STOPPED)return void(t!==Sc.STOPPED&&(this.videoState.startTransitionTo(Sc.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(Sc.STOPPED),_s(this.params.desiredState.playbackState,$.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(t===Sc.STOPPED)return this.videoState.startTransitionTo(Sc.READY),void this.prepare();if(r){const{currentTime:t}=this.video;return this.prepare(),void(a||this.params.desiredState.seekPosition.startTransitionTo(t))}const o=null==a?void 0:a.to;switch((null==i?void 0:i.to)!==$.PAUSED&&s(o)&&this.seek(o),t){case Sc.READY:return void(e===$.PAUSED?(this.videoState.setState(Sc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED)):e===$.PLAYING&&(this.videoState.startTransitionTo(Sc.PLAYING),this.playIfAllowed()));case Sc.PLAYING:return void(e===$.PAUSED?(this.videoState.startTransitionTo(Sc.PAUSED),this.video.pause()):(null==i?void 0:i.to)===$.PLAYING&&_s(this.params.desiredState.playbackState,$.PLAYING));case Sc.PAUSED:return void(e===$.PLAYING?(this.videoState.startTransitionTo(Sc.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===$.PAUSED&&_s(this.params.desiredState.playbackState,$.PAUSED));default:return n(t)}},this.params=t,this.video=ys(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},r=Ps(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.firstBytes$,t.firstBytesEvent$),a(r.firstFrame$,t.firstFrameEvent$),a(r.seeked$,t.seekedEvent$),this.subscription.add(vs(this.video,e.isLooped,i)),this.subscription.add(gs(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Sc.PLAYING),_s(e.playbackState,$.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Sc.PAUSED),_s(e.playbackState,$.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Sc.READY&&this.videoState.setState(Sc.READY);const e=this.params.desiredState.videoTrack.getTransition();e&&s(e.to)&&(this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to].track)),this.videoState.getState()===Sc.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var t,e;const i=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState();l(i,'MpegProvider: track is not selected');const{url:s}=this.trackUrls[i];l(s,`MpegProvider: No url for ${i}`),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(qs(s))}playIfAllowed(){fs(this.video).then((t=>{t||(this.videoState.setState(Sc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}class yc{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{var e,i,s,r,a,n,o,d;if(l(this._xhr),(null===(e=this._xhr)||void 0===e?void 0:e.status)>=400)return null===(i=this._errorCb)||void 0===i||i.call(this,`Http${null===(s=this._xhr)||void 0===s?void 0:s.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=$o(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(a=this._headersCb)||void 0===a||a.call(this,new Headers(e))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(o=this._progressCb)||void 0===o||o.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Tc{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,r,a,n){this.abort((()=>{let o=0;const d=Date.now();let u=0,h=0,c=0;const l=t=>{s(Tc._str2ua(t.substr(o))),o=t.length};this._lastXhr=new yc(t.baseURL+'&bytes='+e+'-'+i,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-o>n&&l(t),0===h)return void(h=Date.now());c=t.length-u;const e=Date.now()-h;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,u=t.length,h=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Tc._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 Ec{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){new yc(t,e,(i=>{this.attachManifest(i,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(t))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$;const P=t.getElementsByTagName('SegmentBase')[0],A=P&&r(P,'indexRange').split('-'),k=P&&P.getElementsByTagName('Initialization')[0],_=k&&r(k,'range').split('-');if(!_||!A){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(h=null===(u=null===(d=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===d?void 0:d.childNodes)||void 0===u?void 0:u[0])||void 0===h?void 0:h.data),l=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:l})}return}const D=Number(null===(l=t.attributes.getNamedItem('bandwidth'))||void 0===l?void 0:l.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let I;const L=null!==(f=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==f?f:void 0;I=L?nc(L):void 0,a.push({width:Number(null===(m=t.attributes.getNamedItem('width'))||void 0===m?void 0:m.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:D,baseURL:R,failoverHosts:e,indexFrom:Number(A[0]),indexTo:Number(A[1]),initFrom:Number(_[0]),initTo:Number(_[1]),codecs:null!==(S=null===(g=t.attributes.getNamedItem('codecs'))||void 0===g?void 0:g.value)&&void 0!==S?S:void 0,mimeType:null!==(y=null===(b=t.attributes.getNamedItem('mimeType'))||void 0===b?void 0:b.value)&&void 0!==y?y:void 0,fps:I,bufferSize:.1*D/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==($=null===(w=t.attributes.getNamedItem('id'))||void 0===w?void 0:w.value)&&void 0!==$?$:void 0})})),a.length?(this._representations=a,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const u=t.refs[t.refs.length-1];u.toTime-u.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,r;const a=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let a;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');a=e.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 Tc({mediaSource:i,sourceBuffer:e,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){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const s=this._findRef(e);if(s){if(i){this._isLastRef(s)&&e>=s.toTime&&(e=s.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||s===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:s.fromTime}this._appendVector[String(s.fromTime)]=t,this._stream.load(t,s.fromOffset,s.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=s.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=!1){this._stream&&this._buffer.getByTime(t)&&!e?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!r(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var wc;!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'}(wc||(wc={}));const $c=[wc.PAUSED,wc.PLAYING];class Pc{constructor(r){this.videoState=new Ys(wc.STOPPED),this.subscription=new i,this.representations$=new t([]),this.currentRepresentation$=new t(void 0),this.textTracksManager=new bs,this.elementSize$=new t(void 0),this.dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&ks(a.name))&&void 0!==s?s:xs(a),o=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!n)continue;const h={id:t,quality:n,bitrate:o,size:d,fps:u};r.push({track:h,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState(wc.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t},this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekPositionTransition: ${JSON.stringify(a)};`}),i===$.STOPPED)return void(t!==wc.STOPPED&&(this.videoState.startTransitionTo(wc.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(wc.STOPPED),_s(this.params.desiredState.playbackState,$.STOPPED,!0)));if(e)return;const o=null==a?void 0:a.to;switch((null==r?void 0:r.to)!==$.PAUSED&&s(o)&&$c.includes(t)&&this.seek(o),t){case wc.STOPPED:return this.videoState.startTransitionTo(wc.MANIFEST_LOADED),void this.prepare();case wc.MANIFEST_LOADED:return void this.videoState.startTransitionTo(wc.INITIAL_REPRESENTATION_SELECTED);case wc.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo(wc.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case wc.METADATA_LOADED:return this.videoState.startTransitionTo(wc.READY),void this.dash.seek(null!=o?o:0);case wc.READY:return void(i===$.PAUSED?(this.videoState.setState(wc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED)):i===$.PLAYING&&(this.videoState.startTransitionTo(wc.PLAYING),this.playIfAllowed()));case wc.PLAYING:return void(i===$.PAUSED?(this.videoState.startTransitionTo(wc.PAUSED),this.video.pause()):(null==r?void 0:r.to)===$.PLAYING&&_s(this.params.desiredState.playbackState,$.PLAYING));case wc.PAUSED:return void(i===$.PLAYING?(this.videoState.startTransitionTo(wc.PLAYING),this.playIfAllowed()):(null==r?void 0:r.to)===$.PAUSED&&_s(this.params.desiredState.playbackState,$.PAUSED));default:return n(t)}},this.params=r,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=ys(r.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(qs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new Es(this.video),this.dash=new Ec({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}}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=Ps(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,i));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.looped$,t.loopedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.firstFrame$,t.firstFrameEvent$),this.subscription.add(d.seeking$.subscribe((()=>{r(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===wc.PLAYING||this.videoState.getState()===wc.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(vs(this.video,e.isLooped,i)),this.subscription.add(gs(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(Gs(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===wc.READY&&this.videoState.setState(wc.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState(wc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState(wc.PLAYING),_s(this.params.desiredState.playbackState,$.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState(wc.METADATA_LOADED)}),i)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(u((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(o(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,a(this.video,'progress')).pipe(u((()=>{var t,e;const i=this.currentRepresentation$.getValue(),r=this.representations$.getValue(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.videoTrack.getState(),d=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),u=this.elementSize$.getValue(),h=n();let c;if(a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),!h&&s(o))c=o;else{const e=Hs(this.video.buffered,1e3*this.video.currentTime),s=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);c=null===(t=Fs(r.map((({track:t})=>t)),{container:u,throughput:d,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:s,currentRepresentation:i}))||void 0===t?void 0:t.id}return s(c)?null===(e=r.find((({track:t})=>t.id===c)))||void 0===e?void 0:e.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(g({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(S((t=>t.to===wc.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(S(s))}).pipe(f()).subscribe((()=>this.videoState.setState(wc.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(S(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=Hs(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(qs(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=Yh(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(f()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(S(s)).subscribe(this.handleRepresentationPlay,i)).add(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return n(t)}}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t)}playIfAllowed(){fs(this.video).then((t=>{t||(this.videoState.setState(wc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED,!0))}))}}var Ac=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)},kc=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 _c=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Dc{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 x(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]=_c(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(_c),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 Bo,d=o.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return Uo(fetch).fetch(n,{signal:d}).then((t=>{var e,i,s;if(!t.ok||!t.body)return void this.onBigRequestError(u);const[r,a]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,a);const n=r.getReader(),o=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10);u.data=new ArrayBuffer(o);const d=new Uint8Array(u.data),c=({done:t,value:e})=>x(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(u):e&&(d.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),yield null==n?void 0:n.read().then(c,Dc.suppressStreamErrors).catch(h))}));null==n||n.read().then(c,Dc.suppressStreamErrors).catch(h)}),Dc.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r}){var a,n,o,d,u,h,c;if(!this.activeRequests.has(t)||!r)return;const l=null!==(a=this.dashJsRequestQueue.get(t))&&void 0!==a?a:[];for(const a of l){const{request:l}=a,[p,f]=_c(l),m=p>=e&&f<=e+s,v=e>=p&&e+s<f,g=r.slice(p-e,Math.min(f-e+1,s));(m||v)&&(l.requestStartDate=null!==(n=l.requestStartDate)&&void 0!==n?n:new Date,l.firstByteDate=null!==(o=l.firstByteDate)&&void 0!==o?o:new Date,l.bytesLoaded=g.byteLength,l.bytesTotal=i-e),m?(l.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(d=this.dashJsRequestQueue.get(t))&&void 0!==d?d:[]).filter((t=>t!==a))),null===(u=a.success)||void 0===u||u.call(a,g,'',t),null===(h=this.dashMetrics)||void 0===h||h.addHttpRequest(l,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 d=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of d){const[r,a]=_c(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]=_c(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 Rc{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(Rc.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;Rc.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const Ic=(t,e)=>{const i=new Dc(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 Rc(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var Lc=i=>{const r=new t(1/0),a=new e;let n=NaN,o=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{var e,i,a;if(!t.getAllResponseHeaders().includes('x-playback-duration'))return;const n=parseInt(null!==(e=t.getResponseHeader('X-Playback-Duration'))&&void 0!==e?e:'',10),o=parseInt(null!==(i=t.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==i?i:'',10),d=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;s(d)&&!isNaN(d)&&r.next(d)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!o&&(o=!0,a.next(Date.now()-n)),i(...t)},n=Date.now(),o=!1}return e(t)}}}),!0),{playbackDuration$:r,ping$:a}};class xc{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}}const Oc={};var Cc;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Cc||(Cc={}));const Nc=(t,e)=>new p((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Mc{constructor(e){this.subscription=new i,this.videoState=new Ys(Cc.DOWNLOADING_LIB),this.textTracksManager=new bs,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t(void 0),this.maxSeekBackTime$=new t(1/0),this.availableFrom$=new t(void 0),this.elementSize$=new t(void 0),this.liveOffset=new xc,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition(),a=this.isLive$.getValue();if(this.videoState.getTransition())return;if(t===Cc.DOWNLOADING_LIB||t===Cc.STREAM_INITIALIZED)return;const o=null==r?void 0:r.to;switch((null==i?void 0:i.to)!==$.PAUSED&&s(o)&&t!==Cc.STOPPED&&e!==$.STOPPED&&(a?this.seek(o+Bc(this.liveOffset.getTotalPausedTime())):this.seek(o)),e){case $.STOPPED:switch(t){case Cc.STOPPED:break;case Cc.PLAYING:case Cc.PAUSED:case Cc.READY:this.stop();break;default:n(t)}break;case $.PLAYING:switch(t){case Cc.PLAYING:break;case Cc.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(Bc(this.liveOffset.getTotalOffset()))):this.seek(Bc(this.liveOffset.getTotalOffset()))),this.play();break;case Cc.READY:this.play();break;case Cc.STOPPED:this.prepare();break;default:n(t)}break;case $.PAUSED:switch(t){case Cc.PLAYING:this.pause(),this.liveOffset.pause();break;case Cc.PAUSED:break;case Cc.READY:this.videoState.setState(Cc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED);break;case Cc.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}},this.video=ys(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(qs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Gh(import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Oc.MediaPlayer=e.MediaPlayer,Oc.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(Oc.MediaPlayer,'dashjs not loaded'),l(Oc.Debug,'dashjs not loaded'),this.player=Oc.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?nc(t.frameRate+''):void 0),!0)));(this.params.format===P.DASH_WEBM||this.params.format===P.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Ic(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&&kc(this.player),Ac(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Cc.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(Gs(this.video),this.elementSize$),a(Nc(this.player,'error').pipe(u((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),a(Nc(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Nc(this.player,'qualityChangeRendered').pipe(S((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));n.pipe(S(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(S((({to:t})=>t===Cc.STREAM_INITIALIZED)),f()).subscribe((()=>{this.subscription.add(ms(e.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.videoTracks.find((({track:e})=>e.id===t)))||void 0===e?void 0:e.bitrateInfo;i&&this.player.setQualityFor('video',i.qualityIndex)}),{changed$:n.pipe(u((t=>null==t?void 0:t.id))),onError:i}))}),i)),this.subscription.add(ms(e.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),a(Nc(this.player,'bufferStateChanged').pipe(S((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),a(Nc(this.player,'fragmentLoadingStarted').pipe(u((t=>qs(t.request.url)))),t.hostname$),a(Nc(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=xs(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===r&&(a=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&t.currentVideoTrack$.next(a),this.videoState.setState(Cc.STREAM_INITIALIZED),this.videoState.startTransitionTo(Cc.READY)})),a(Nc(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),a(o(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=Fs(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(g({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(S(s))}).pipe(S((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>Bc(t)))),this.params.output.duration$);const d=Nc(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>null!=t?t:0)));a(g({availableFrom:this.availableFrom$.pipe(S(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(d.pipe(S((()=>!1===this.isLive$.getValue()))),t.position$),a(Nc(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(Nc(this.player,'playbackEnded'),t.endedEvent$),a(Nc(this.player,'playbackProgress').pipe(u((()=>ws(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(Nc(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Cc.PLAYING),_s(e.playbackState,$.PLAYING)})),a(Nc(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Cc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Nc(this.player,'playbackPaused'),(()=>{this.videoState.setState(Cc.PAUSED),_s(e.playbackState,$.PAUSED)})),a(Nc(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Cc.READY&&this.videoState.setState(Cc.READY)})),a(this.isLive$,t.isLive$),a(Gs(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l}=Lc(this.player);a(c,this.maxSeekBackTime$),a(l.pipe(f()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&a(g({isLive:this.isLive$,isShort:t.duration$.pipe(u((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(d.pipe(S((t=>t>this.params.tuning.insufficientBufferRuleMargin)),f()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Nc(this.player,'manifestLoaded').pipe(f()).subscribe((()=>{const e=Date.now();this.subscription.add(Nc(this.player,'playbackPlaying').pipe(f()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-e)),i))}),i)),this.subscription.add(vs(this.video,e.isLooped,i));const{volumeState$:p,looped$:v}=Ps(this.video);this.subscription.add(gs(this.video,e.volume,p,i)),this.subscription.add(p.subscribe(t.volume$,i)),this.subscription.add(v.subscribe(t.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Cc.STOPPED),_s(this.params.desiredState.playbackState,$.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Cc.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=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Bc(i));const s=mc(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,fc.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(Cc.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Cc.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)}}const Bc=t=>-t/1e3;function Uc(){return v()}function Vc(t){return Uc()-t}function Fc(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 Hc(t,e,i,r){const a=window.XMLHttpRequest;let n,o,d,u,h,c=!1,p=0,f=!1,m='arraybuffer',v=7e3,g=2e3,S=()=>{if(c)return;l(u);const t=Vc(u);let e;if(t<g)return e=g-t,void setTimeout(S,e);g*=2,g>v&&(g=v),o&&o.abort(),o=new a,y()};const b=()=>{if(!c){if(--p>=0)return S(),void(r&&r());c=!0,h&&h(),i&&i()}},y=()=>{u=Uc(),o=new a,o.open('get',t);let i,s=0,r=0;const p=()=>(l(u),Math.max(u,Math.max(i||0,r||0)));if(n&&o.addEventListener('progress',(t=>{const e=Uc();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(c)return;l(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(p(),t)}h&&h(),o&&e(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),f){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(r=Uc(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=m,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(f=t,T),withJSONResponse:()=>(m='json',T),withRetryCount:t=>(p=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(v=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(h=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return T}class qc{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 Gc{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=Uc(),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=Hc(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Uc()-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=Uc()}_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=Uc();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 Yc{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 qc(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Fc(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=Fc(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{l(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 Gc(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,d=null,u=null,h=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},f=(t,e,i)=>{u&&u.abort(),u=Hc(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},m=(t,e,i)=>{l(this.filesFetcher),null==d||d.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},v=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void v(1);const i=Uc()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const r=this.bufferStates[e];t=Math.min(t,r.buf),r.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,v(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else v(1)},b=t=>{let i;const r=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,u=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=Math.max(this.sourceJitter,1);for(this.lowLatency||(e+=2),t=i.dur.length-1;t>=0&&(e-=i.dur[t]/1e3,!(e<=0));--t);}return u(t,!0)},f=(t,e,i)=>{h&&h.abort(),h=Hc(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{h=null})).withJSONResponse().send()};return{seek:(e,o)=>{f(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let h=0;for(let t=0;t<i.dur.length;++t)h+=i.dur[t];h>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(h/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=r();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return u(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=r(),a=t?t.chunkIdx+1:0,n=a-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return u(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),u&&u.abort(),h&&h.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,u,c,v,g,T,E=b(t.jidxUrl),w=0;const $=()=>{v&&(clearTimeout(v),v=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Uc(),s=Math.min(1e4,e-i);w=i;const r=()=>{h||p()&&E.seek((()=>{p()&&(w=Uc(),P(),$())}))};s>0?v=window.setTimeout((()=>{this.paused?$():r()}),s):r()},P=()=>{let e;for(;e=E.nextChunk(c);)c=e,R(e);const i=E.nextChunk(u);if(i){if(u&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));D(i)}else $()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let r,a,n;const o=i=>{window.setTimeout((()=>{p()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Uc(),u=i.currentTime;!this.paused&&i.buffered.length>1&&g===u&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,T=d);const h=this._getBufferSizeSec();if(h>30)s(`Buffered ${h} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(r=this.sourceBuffer.buffered.start(0),a=u,a-r>4&&this.sourceBuffer.remove(r,a-3)),o(1e3)}}},k=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(u)]),A(d,(function(){d=null,P()})))},_=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{p()&&m(_(t),((e,i)=>{if(p()){if(i/=1e3,d=e,u=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}k()}}),(()=>this._handleNetworkError()))},R=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(_(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{a=!0,k()})))};n=!0,E.seek((t=>{p()&&(w=Uc(),t?(c=t,!r(e)||t.startTS>e?D(t):(u=t,P())):$())}),e),t.cachedHeader?I(t.cachedHeader):f(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let r;t.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Uc();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&&Vc(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=Uc();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=Hc(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;fs(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 jc;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(jc||(jc={}));const zc=[jc.PAUSED,jc.PLAYING,jc.READY],Qc=[jc.PAUSED,jc.PLAYING,jc.READY];class Wc{constructor(e){this.subscription=new i,this.videoState=new Ys(jc.STOPPED),this.representations$=new t([]),this.textTracksManager=new bs,this.maxSeekBackTime$=new t(1/0),this.zeroTime$=new t(void 0),this.liveOffset=new xc,this._dashCb=t=>{var e,i,r,a;switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const s=t.manifest,a=[];for(const t of s){const s=null!==(e=t.name)&&void 0!==e?e:t.index.toString(10),r=null!==(i=ks(t.name))&&void 0!==i?i:xs(t.video),n=t.bitrate/1e3,o=Object.assign({},t.video);if(!r)continue;const d={id:s,quality:r,bitrate:n,size:o};a.push({track:d,representation:t})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===jc.MANIFEST_READY&&this.videoState.setState(jc.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=null===(a=this.representations$.getValue().find((({representation:t})=>t===e)))||void 0===a?void 0:a.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}},this.syncPlayback=()=>{var t;const e=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekPositionTransition: ${JSON.stringify(o)};`}),r===$.STOPPED)return void(e!==jc.STOPPED&&(this.videoState.startTransitionTo(jc.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(jc.STOPPED)));if(i)return;if(Qc.includes(e)){const e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to;s(e)&&this.setVideoTrack(e);const i=this.params.desiredState.autoVideoTrackSwitching.getTransition();i&&this.setAutoQuality(i.to)}const d=null==o?void 0:o.to;if((null==a?void 0:a.to)!==$.PAUSED&&s(d)&&zc.includes(e))this.seek(d+Jc(this.liveOffset.getTotalPausedTime()));else switch(e){case jc.STOPPED:return this.videoState.startTransitionTo(jc.MANIFEST_READY),void this.dash.attachSource(mc(this.params.source.url));case jc.MANIFEST_READY:this.videoState.startTransitionTo(jc.READY),this.prepare();break;case jc.READY:return void(r===$.PAUSED?this.videoState.setState(jc.PAUSED):r===$.PLAYING&&(this.videoState.startTransitionTo(jc.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(jc.PAUSED)}))));case jc.PLAYING:return void(r===$.PAUSED&&(this.videoState.startTransitionTo(jc.PAUSED),this.liveOffset.pause(),this.dash.pause()));case jc.PAUSED:return void(r===$.PLAYING&&(this.videoState.startTransitionTo(jc.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(jc.PAUSED)})),this.params.output.position$.next(Jc(this.liveOffset.getTotalOffset()))):this.seek(Jc(this.liveOffset.getTotalOffset()))));default:return n(e)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const r=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=ys(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(qs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const a=Ps(this.video);this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===jc.READY&&this.videoState.setState(jc.READY)}),r)).add(a.pause$.subscribe((()=>{this.videoState.setState(jc.PAUSED)}),r)).add(a.playing$.subscribe((()=>{this.videoState.setState(jc.PLAYING)}),r)).add(a.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),u(Jc)).subscribe(this.params.output.duration$)).add(g({zeroTime:this.zeroTime$.pipe(S(s)),position:a.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),r)).add(vs(this.video,this.params.desiredState.isLooped,r)).add(gs(this.video,this.params.desiredState.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(this.params.output.volume$,r)).add($s(this.video).subscribe(this.params.output.firstBytesEvent$)).add(Ts(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&Ds[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case jc.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState($.STOPPED);break;case jc.MANIFEST_READY:case jc.READY:break;case jc.PAUSED:this.params.desiredState.playbackState.setState($.PAUSED);break;case jc.PLAYING:this.params.desiredState.playbackState.setState($.PLAYING);break;default:return n(t.to)}}),r)).add(o(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekPosition.stateChangeStarted$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new Yc({videoElement:this.video,config:{CHUNK_DURATION:this.params.config.chunkDuration,BUFFER_OPTIMAL_DURATION:this.params.config.optimalBufferDuration,MAX_PARALLEL_REQUESTS:this.params.config.maxParallelRequests},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var t,e,i,r,a,n;const o=this.representations$.getValue(),d=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState(),u=null!==(r=null===(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===i?void 0:i.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&s(d)?d:null===(a=Fs(o.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))||void 0===a?void 0:a.id,c=null===(n=o.find((({track:t})=>t.id===h)))||void 0===n?void 0:n.representation;l(c),this.dash.startPlay(c,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(h),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(t){var e;const i=null===(e=this.representations$.getValue().find((({track:e})=>e.id===t)))||void 0===e?void 0:e.representation;l(i),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Jc(i)),this.dash.reinit(mc(this.params.source.url,i)),this.params.output.seekedEvent$.next()}}const Jc=t=>-t/1e3,Kc=t=>{let e=null;if(t.QUALITY&&(e=ks(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=xs({width:i,height:s})}return null!=e?e:null},Xc=(t,e=t)=>x(void 0,void 0,void 0,(function*(){var i;const s=yield Uo(fetch).fetch(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=$o(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,d=Kc(n);let u;n.BANDWIDTH&&(u=parseInt(n.BANDWIDTH,10)/1e3||void 0),!u&&n['AVERAGE-BANDWIDTH']&&(u=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let c;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(c={width:t,height:e})}const l=new URL(r[++t],e).toString();d&&a.push({id:o,quality:d,url:l,bandwidth:u,size:c,fps:h})}return a}));var Zc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(Zc||(Zc={}));class tl{constructor(e){this.subscription=new i,this.videoState=new Ys(Zc.STOPPED),this.textTracksManager=new bs,this.manifests$=new t([]),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===$.STOPPED)return void(t!==Zc.STOPPED&&(this.videoState.startTransitionTo(Zc.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(Zc.STOPPED),_s(this.params.desiredState.playbackState,$.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===Zc.STOPPED)return this.videoState.startTransitionTo(Zc.READY),void this.prepare();if(a||o){const t=this.videoState.getState();this.videoState.setState(Zc.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(d&&!r(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const u=null==d?void 0:d.to;switch((null==i?void 0:i.to)!==$.PAUSED&&s(u)&&this.seek(u),t){case Zc.READY:return void(e===$.PAUSED?(this.videoState.setState(Zc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED)):e===$.PLAYING&&(this.videoState.startTransitionTo(Zc.PLAYING),this.playIfAllowed()));case Zc.PLAYING:return void(e===$.PAUSED?(this.videoState.startTransitionTo(Zc.PAUSED),this.video.pause()):(null==i?void 0:i.to)===$.PLAYING&&_s(this.params.desiredState.playbackState,$.PLAYING));case Zc.PAUSED:return void(e===$.PLAYING?(this.videoState.startTransitionTo(Zc.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===$.PAUSED&&_s(this.params.desiredState.playbackState,$.PAUSED));case Zc.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=ys(e.container),this.params.output.element$.next(this.video);const a={id:'master',quality:As.INVARIANT,url:this.params.source.url};this.manifests$.next([a]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(qs(this.params.source.url)),Xc(this.params.source.url).then((t=>{this.manifests$.next([a,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},r=Ps(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.firstBytes$,t.firstBytesEvent$),a(r.firstFrame$,t.firstFrameEvent$),a(r.seeked$,t.seekedEvent$),this.subscription.add(vs(this.video,e.isLooped,i)),this.subscription.add(gs(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(Zc.PLAYING),_s(e.playbackState,$.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(Zc.PAUSED),_s(e.playbackState,$.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Zc.READY&&this.videoState.setState(Zc.READY),this.videoState.getState()===Zc.PLAYING&&this.playIfAllowed()}),i).add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(qs(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===Zc.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&s(t.to)&&this.seek(t.to)}),i))),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();r(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){fs(this.video).then((t=>{t||(this.videoState.setState(Zc.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}var el;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(el||(el={}));class il{constructor(e){var a;this.subscription=new i,this.videoState=new Ys(el.STOPPED),this.textTracksManager=new bs,this.manifests$=new t([]),this.liveOffset=new xc,this.manifestStartTime$=new t(void 0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===$.STOPPED)return void(t!==el.STOPPED&&(this.videoState.startTransitionTo(el.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(el.STOPPED),_s(this.params.desiredState.playbackState,$.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===el.STOPPED)return this.videoState.startTransitionTo(el.READY),void this.prepare();if(a||o){const t=this.videoState.getState();this.videoState.setState(el.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const e=sl(this.liveOffset.getTotalOffset());return this.prepare(),void(d&&!r(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const u=null==d?void 0:d.to;if((null==i?void 0:i.to)!==$.PAUSED&&s(u))return this.videoState.startTransitionTo(el.READY),this.seek(u+sl(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case el.READY:return void(e===$.PAUSED?(this.videoState.setState(el.PAUSED),this.liveOffset.pause(),_s(this.params.desiredState.playbackState,$.PAUSED)):e===$.PLAYING&&(this.videoState.startTransitionTo(el.PLAYING),this.playIfAllowed()));case el.PLAYING:return void(e===$.PAUSED?(this.videoState.startTransitionTo(el.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==i?void 0:i.to)===$.PLAYING&&_s(this.params.desiredState.playbackState,$.PLAYING));case el.PAUSED:return void(e===$.PLAYING?(this.videoState.startTransitionTo(el.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(sl(this.liveOffset.getTotalOffset()))):this.seek(sl(this.liveOffset.getTotalOffset()))):(null==i?void 0:i.to)===$.PAUSED&&(_s(this.params.desiredState.playbackState,$.PAUSED),this.liveOffset.pause()));case el.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=ys(e.container),this.params.output.element$.next(this.video);const o={id:'master',quality:As.INVARIANT,url:this.params.source.url};this.manifests$.next([o]),Xc(mc(this.params.source.url)).then((t=>{this.manifests$.next([o,...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(qs(this.params.source.url)),this.maxSeekBackTime$=new t(null!==(a=e.source.maxSeekBackTime)&&void 0!==a?a:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},r=Ps(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.ended$,t.endedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.firstBytes$,t.firstBytesEvent$),a(r.firstFrame$,t.firstFrameEvent$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(gs(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(el.PLAYING),_s(e.playbackState,$.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(el.PAUSED),_s(e.playbackState,$.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===el.READY&&this.videoState.setState(el.READY),this.videoState.getState()===el.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),u(sl)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(qs(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===el.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&s(t.to)&&this.seek(t.to)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),i)),this.subscription.add(g({startTime:this.manifestStartTime$.pipe(S(s)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,h(['init'])).pipe(m(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(r(t))return;const e=mc(t.url,this.liveOffset.getTotalOffset());var i;this.video.setAttribute('src',e),this.video.load(),(i=e,x(void 0,void 0,void 0,(function*(){const t=yield Uo(fetch).fetch(i,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){fs(this.video).then((t=>{t||(this.videoState.setState(el.PAUSED),this.liveOffset.pause(),_s(this.params.desiredState.playbackState,$.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(sl(i)),this.params.output.seekedEvent$.next()}}const sl=t=>-t/1e3,rl={};var al;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(al||(al={}));const nl=(t,e)=>new p((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class ol{constructor(t){this.subscription=new i,this.videoState=new Ys(al.INITIALIZING),this.textTracksManager=new bs,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(t===al.INITIALIZING)return;const a=null==r?void 0:r.to;switch((null==i?void 0:i.to)!==$.PAUSED&&s(a)&&this.seek(a),e){case $.STOPPED:switch(t){case al.STOPPED:break;case al.READY:case al.PLAYING:case al.PAUSED:this.stop();break;default:n(t)}break;case $.PLAYING:switch(t){case al.PLAYING:break;case al.STOPPED:this.prepare();break;case al.READY:case al.PAUSED:this.playIfAllowed();break;default:n(t)}break;case $.PAUSED:switch(t){case al.PAUSED:break;case al.STOPPED:this.prepare();break;case al.READY:this.videoState.setState(al.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED);break;case al.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}},this.video=ys(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(qs(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Gh(import('hls.js').then((e=>{t||(rl.Hls=e.default,rl.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(rl.Hls,'hls.js not loaded'),this.hls=new rl.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(al.STOPPED)}subscribe(){l(rl.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=Ps(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.firstBytes$,e.firstBytesEvent$),n(a.firstFrame$,e.firstFrameEvent$),n(a.seeked$,e.seekedEvent$),this.subscription.add(vs(this.video,t.isLooped,i)),this.subscription.add(gs(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(nl(this.hls,rl.Events.ERROR).subscribe((t=>{var i;t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(i=t.err)||void 0===i?void 0:i.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(al.PLAYING),_s(t.playbackState,$.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(al.PAUSED),_s(t.playbackState,$.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===al.READY&&this.videoState.setState(al.READY),this.videoState.getState()===al.PLAYING&&this.playIfAllowed()}),i)),n(nl(this.hls,rl.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=ks(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:xs({width:a,height:n});if(!o)return t;const d=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:d};return this.trackLevels.set(r,{track:u,level:e}),t.push(u),t}),[])))),e.availableVideoTracks$),n(nl(this.hls,rl.Events.LEVEL_LOADING).pipe(u((({url:t})=>qs(t)))),e.hostname$),this.subscription.add(ms(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const d=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},c=nl(this.hls,rl.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>d(this.hls.levels[t]))));c.pipe(S(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(ms(t.videoTrack,(()=>{var t;return null===(t=d(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.trackLevels.get(t))||void 0===e?void 0:e.level;if(!i)return;const s=this.hls.levels.indexOf(i),a=this.hls.currentLevel,n=this.hls.levels[a];!n||i.bitrate>n.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:c.pipe(u((t=>null==t?void 0:t.id))),onError:i})),n(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const p=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(p.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(al.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return x(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(al.PLAYING);(yield fs(this.video))||(this.videoState.setState(al.PAUSED),_s(this.params.desiredState.playbackState,$.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(al.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}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(al.STOPPED),_s(this.params.desiredState.playbackState,$.STOPPED,!0)}}class dl{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 ul,hl,cl,ll,pl,fl,ml,vl,gl,Sl,bl,yl,Tl,El,wl,$l,Pl;const Al=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),kl=(null===(ul=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===ul?void 0:ul.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),_l=document.createElement('video'),Dl={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(cl=null===(hl=window.SourceBuffer)||void 0===hl?void 0:hl.prototype)||void 0===cl?void 0:cl.appendBuffer)),hls:Boolean((null===(ll=_l.canPlayType)||void 0===ll?void 0:ll.call(_l,'application/x-mpegurl'))||(null===(pl=_l.canPlayType)||void 0===pl?void 0:pl.call(_l,'vnd.apple.mpegURL')))},Rl={mp4:Boolean(null===(fl=_l.canPlayType)||void 0===fl?void 0:fl.call(_l,'video/mp4')),webm:Boolean(null===(ml=_l.canPlayType)||void 0===ml?void 0:ml.call(_l,'video/webm'))},Il={h264:Boolean(null===(gl=null===(vl=window.MediaSource)||void 0===vl?void 0:vl.isTypeSupported)||void 0===gl?void 0:gl.call(vl,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(bl=null===(Sl=window.MediaSource)||void 0===Sl?void 0:Sl.isTypeSupported)||void 0===bl?void 0:bl.call(Sl,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(Tl=null===(yl=window.MediaSource)||void 0===yl?void 0:yl.isTypeSupported)||void 0===Tl?void 0:Tl.call(yl,'video/webm; codecs="vp9"')),aac:Boolean(null===(wl=null===(El=window.MediaSource)||void 0===El?void 0:El.isTypeSupported)||void 0===wl?void 0:wl.call(El,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Pl=null===($l=window.MediaSource)||void 0===$l?void 0:$l.isTypeSupported)||void 0===Pl?void 0:Pl.call($l,'audio/webm; codecs="opus"'))},Ll=(Il.h264||Il.h265)&&Il.aac,xl=!Al,Ol=kl||Al,Cl=!Dl.hls||!Ol,Nl=3e4,Ml=18e4,Bl=3,Ul=100,Vl={cacheDuration:12e4},Fl={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},Hl={maxPausedTime:3e4},ql={maxPausedTime:3e4};class Gl{constructor(r){this.current$=new t({type:void 0}),this.providerError$=new e,this.noAvailableProvidersError$=new e,this.providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)},this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:a}=this.params.tuning,o=a.length?[...r.screenFormatsPriority.filter((t=>!a.includes(t))),...r.screenFormatsPriority.filter((t=>a.includes(t)))]:r.screenFormatsPriority;this.screenFormatsIterator=new dl(o.filter((t=>s(r.sources[t]))).filter((t=>{switch(t){case P.DASH:return Dl.mse&&Rl.mp4&&Ll&&xl;case P.DASH_SEP:case P.DASH_SEP_VK:return Dl.mse&&Rl.mp4&⋘case P.DASH_WEBM:case P.DASH_WEBM_VK:case P.DASH_LIVE_WEBM:return Dl.mse&&Rl.webm&&Il.vp9&&Il.opus;case P.DASH_LIVE:case P.DASH_ONDEMAND:return Dl.mse&&Rl.mp4&⋘case P.HLS:case P.HLS_LIVE:case P.HLS_ONDEMAND:return Dl.hls&&Rl.mp4&&Ol;case P.HLS_JS:return Dl.mse&&Rl.mp4&&Ll&&Cl;case P.MPEG:return Rl.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new dl(r.chromecastFormatsPriority.filter((t=>s(r.sources[t]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),e=this.chooseFormat(t);if(r(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;l(t),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=this.params.desiredState.seekPosition,i=e.getTransition();i?s(i.from)&&e.startTransitionTo(i.from):e.startTransitionTo(this.providerOutput.position$.getValue()),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case A.SCREEN:return this.createScreenProvider(e);case A.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,r=this.providerOutput;switch(t){case P.DASH:{const a=e[t];return l(a),new Pc({container:i,source:a,desiredState:s,output:r,config:Vl,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_SEP_VK:case P.DASH_WEBM_VK:{const a=e[t];return l(a),new pc({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_SEP:case P.DASH_WEBM:case P.DASH_ONDEMAND:case P.DASH_LIVE_WEBM:{const a=e[t];return l(a),new Mc({container:i,source:a,desiredState:s,output:r,format:t,config:ql,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS:case P.HLS_ONDEMAND:{const a=e[t];return l(a),new tl({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS_LIVE:{const a=e[t];return l(a),new il({container:i,source:a,desiredState:s,output:r,config:Hl,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.HLS_JS:{const a=e[t];return l(a),new ol({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.MPEG:{const a=e[t];return l(a),new bc({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case P.DASH_LIVE:{const a=e[t];return l(a),new Wc({container:i,source:a,desiredState:s,output:r,config:Fl,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:r}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new gc({connection:n,meta:r,container:i,source:e,format:t,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?A.CHROMECAST:A.SCREEN}chooseFormat(t){switch(t){case A.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case A.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case A.SCREEN:return this.screenFormatsIterator.next();case A.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case A.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case A.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let e=[],r=0;const a=new i;var n;return a.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Nl,position$:this.providerOutput.position$,providerChanged$:this.current$},new p((e=>{const s=new i,r=b(n.maxTransitionInterval),a=new t(void 0);o(n.desiredPlaybackState$.stateChangeStarted$.pipe(y(r)),n.desiredPlaybackState$.stateChangeEnded$.pipe(y(void 0)),n.providerChanged$.pipe(u((()=>a.getValue())))).subscribe(a);const d=new i;return s.add(d),s.add(a.subscribe((t=>{d.unsubscribe(),t&&d.add(t.subscribe(e))}))),s}))).pipe(y({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),a.add(this.providerError$.pipe(T(Ul,{leading:!1,trailing:!0})).subscribe((()=>{const t=Date.now();this.current$.getValue().destination===A.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(e[r])&&t<e[r]+Ml?(e=[],this.switchToNextProvider()):(e[r]=t,this.reinitProvider()),r=(r+1)%Bl}))),a}}const Yl=(t,e,i)=>i*e+(1-i)*t;class jl{constructor(e){var i;this.prevReported=void 0,this.params=e,this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Us(`raw_${s}`),this.smoothedSeries$=new Us(`smoothed_${s}`),this.reportedSeries$=new Us(`reported_${s}`)}next(t){this.slow=Yl(this.slow,t,this.params.emaAlphaSlow),this.fast=Yl(this.fast,t,this.params.emaAlphaFast);const e=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=e(this.slow,this.fast),this.smoothed$.next(this.smoothed),(r(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed)),this.rawSeries$.next(t),this.smoothedSeries$.next(this.smoothed)}}var zl;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(zl||(zl={}));const Ql=new Map;let Wl=zl.RUNTIME;const Jl=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Jl,'test'),localStorage.removeItem(Jl),Wl=zl.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;try{sessionStorage.getItem(Jl),Wl=zl.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException))throw t;Wl=zl.RUNTIME}}})();const Kl=(t,e)=>{switch(Wl){case zl.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case zl.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case zl.RUNTIME:return void Ql.set(t,e);default:n(Wl)}},Xl=window.navigator.connection,Zl=()=>{const t=null==Xl?void 0:Xl.downlink;if(s(t)&&10!==t)return 1e3*t},tp=()=>{const t=null==Xl?void 0:Xl.rtt;if(s(t)&&3e3!==t)return t},ep=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class ip{constructor(e){var r,n;this.subscription=new i,this.tuningConfig=e;const o=ip.load('one_video_throughput')||(e.useBrowserEstimation?Zl():void 0)||5e3,d=null!==(n=null!==(r=ip.load('one_video_rtt'))&&void 0!==r?r:e.useBrowserEstimation?tp():void 0)&&void 0!==n?n:0;if(this.throughput$=new t(o),this.rtt$=new t(d),this.rttAdjustedThroughput$=new t(ep(o,d,e.rttPenaltyRequestSize)),this.throughput=new jl({initial:o,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new jl({initial:d,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=Zl();t&&this.throughput.next(t);const e=tp();s(e)&&this.rtt.next(e)};Xl&&'onchange'in Xl&&this.subscription.add(a(Xl,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Kl('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Kl('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(g({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>ep(t,i,e.rttPenaltyRequestSize))),S((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(t){let e=0,s=v();const r=new i;switch(this.subscription.add(r),t.readyState){case 4:break;case 3:case 2:r.add(a(t,'progress').pipe(f()).subscribe((t=>{e=t.loaded,s=v()})));break;case 1:case 0:r.add(a(t,'loadstart').subscribe((()=>{e=0,s=v()})))}r.add(a(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,r=v(),a=t-e,n=r-s;this.addRawSpeed(a,n)}r.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=v();let r=0,a=v();const n=i=>{e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=({done:t,value:d})=>x(this,void 0,void 0,(function*(){t?this.addRawSpeed(i,v()-s):d&&(i+=d.byteLength,r+=d.byteLength,r>=this.tuningConfig.streamMinSampleSize&&v()-a>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,v()-a),r=0,a=v()),yield null==e?void 0:e.read().then(o,n))}));null==e||e.read().then(o,n)}addRawSpeed(t,e){if(ip.sanityCheck(t,e)){const i=8*t/e;this.throughput.next(i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){var e;const i=(t=>{var e,i;switch(Wl){case zl.LOCAL_STORAGE:return null!==(e=localStorage.getItem(t))&&void 0!==e?e:void 0;case zl.SESSION_STORAGE:return null!==(i=sessionStorage.getItem(t))&&void 0!==i?i:void 0;case zl.RUNTIME:return Ql.get(t);default:n(Wl)}})(t);if(s(i))return null!==(e=parseInt(i,10))&&void 0!==e?e:void 0}}const sp=(t=(t=>t))=>({playbackState:e,seekPosition:a,playbackAbort$:n,looped$:d,position$:h})=>new p((c=>{let l;const p=e.transitionEnded$.pipe(S((t=>(t.from===$.PAUSED||t.from===$.STOPPED)&&t.to===$.PLAYING))),f=e.stateChangeEnded$.pipe(S((t=>t.from===$.PLAYING&&t.to===$.PAUSED))),m=a.stateChangeEnded$.pipe(S((t=>{var i,r;return s(t.to)&&(null!==(r=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==r?r:e.getState())===$.PLAYING}))),v=a.stateChangeEnded$.pipe(S((t=>{var i,s;return r(t.to)&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===$.PLAYING}))),g=o(p,v).pipe(u((()=>t(h.getValue())))),b=o(o(f,m,n).pipe(u((()=>t(h.getValue())))),d.pipe(u(t)));return(new i).add(g.subscribe((e=>{l=t(e)}))).add(b.subscribe((e=>{const i=t(e);if(r(l)||l===i)return;const s={start:l,end:i};l=void 0,c.next(s)})))})),rp=sp((t=>t)),ap=sp((t=>Math.round(1e3*t)+Date.now())),np={[A.SCREEN]:{vod:[P.HLS,P.HLS_ONDEMAND,P.DASH_WEBM_VK,P.DASH_WEBM,P.DASH,P.DASH_SEP_VK,P.DASH_SEP,P.DASH_ONDEMAND,P.HLS_JS,P.MPEG],live:[P.HLS_LIVE,P.DASH_LIVE,P.DASH_LIVE_WEBM]},[A.CHROMECAST]:{vod:[P.DASH_WEBM_VK,P.DASH_WEBM,P.DASH_SEP_VK,P.DASH_SEP,P.DASH_ONDEMAND,P.HLS,P.HLS_ONDEMAND,P.MPEG],live:[P.HLS_LIVE]}};class op{constructor(s={}){if(this.subscription=new i,this.logger=new E,this.isPlaybackStarted=!1,this.desiredState={playbackState:new Ys($.STOPPED),seekPosition:new Ys(void 0),volume:new Ys({volume:1,muted:!1}),videoTrack:new Ys(void 0),autoVideoTrackSwitching:new Ys(!0),autoVideoTrackLimits:new Ys({}),isLooped:new Ys(!1),externalTextTracks:new Ys([]),currentTextTrack:new Ys(void 0),textTrackCuesSettings:new Ys({})},this.info={playbackState$:new t($.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentBuffer$:new t(void 0),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(k.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)},this.events={started$:new e,startAttempt$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,log$:new e},this.experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:Ms},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(R)){const s=R[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?Object.assign(Object.assign({},s),r):null!=r?r:s}return e})(s),this.chromecastInitializer=new I({receiverApplicationId:s.chromecastReceiverId,isDisabled:s.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new ip(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),r=`Player.${String(e)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(t){var e,i;return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=null===(e=t.meta)||void 0===e?void 0:e.videoId,this.providerContainer=new Gl({screenFormatsPriority:[...np[A.SCREEN].live,...np[A.SCREEN].vod],chromecastFormatsPriority:[...np[A.CHROMECAST].live,...np[A.CHROMECAST].vod],sources:t.sources,meta:null!==(i=t.meta)&&void 0!==i?i:{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==$.PLAYING&&t.startTransitionTo($.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==$.PAUSED&&t.startTransitionTo($.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==$.STOPPED&&t.startTransitionTo($.STOPPED),this}seekTime(t){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekPosition.startTransitionTo(t),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()===k.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()===k.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){l(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>Object.assign({type:'external'},t)))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){var t;l(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r(e))return this.info.position$.getValue();const i=this.desiredState.seekPosition.getTransition(),a=null!==(t=null==i?void 0:i.to)&&void 0!==t?t:null==i?void 0:i.from;return s(a)?a:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(o(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(u((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.autoQualityLimits$));const t=new i;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(S((t=>t.to===$.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((t=>t.to===$.PLAYING||t.to===$.PAUSED)),m(0),f()).subscribe((t=>{const e=t.to===$.PLAYING,i=this.info.muted$.getValue(),s=e?i?_.SuccessWithoutSound:_.SuccessWithSound:_.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((t=>t.to===$.PLAYING)),m(0)).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 $.PAUSED:this.events.willPause$.next();break;case $.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition(),e=null==t?void 0:t.to;s(e)&&(this.desiredState.seekPosition.setState(e),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition();s(null==t?void 0:t.to)||this.desiredState.seekPosition.setState(void 0),this.events.seeked$.next()}))).add(e.current$.pipe(u((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(u((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(u((t=>t.map((({quality:t})=>t)).sort(((t,e)=>Os(t)?1:Os(e)?-1:Rs(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(u((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(u((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekPosition:t,position$:e})=>o(t.stateChangeStarted$.pipe(u((t=>t.to)),S(s)),e.pipe(S((()=>r(t.getState())&&r(t.getTransition()))))))({seekPosition:this.desiredState.seekPosition,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(y(!0)),e.providerOutput.seekedEvent$.pipe(y(!1))).pipe(c()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(u((t=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.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 n=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>n.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>n.next(!0))));const d=new t(!0);this.subscription.add(e.current$.subscribe((()=>d.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((({to:t})=>t===$.PLAYING)),f()).subscribe((()=>d.next(!1))));let h=0;const p=o(e.providerOutput.isBuffering$,n,d).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=n.getValue()||d.getValue();return t&&!i})),c());this.subscription.add(p.subscribe((t=>{t?h=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(h),this.info.isStalled$.next(!1))})));const m=new i;this.subscription.add(m);const v=o(a(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(S((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),m.unsubscribe(),t){case!0:m.add(ap({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:v,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:m.add(rp({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:v,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(u((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(S((t=>t.length>0)),f()).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=Fs(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(o(this.desiredState.videoTrack.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekPosition.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'seekPosition',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(u((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;const e=null===(t=this.providerContainer)||void 0===t?void 0:t.providerOutput;l(this.providerContainer),l(e),Ns={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Cs=t})),this.providerContainer.current$.subscribe((({type:t})=>Bs('provider',t))),e.duration$.subscribe((t=>Bs('duration',t))),e.availableVideoTracks$.pipe(S((t=>!!t.length)),f()).subscribe((t=>Bs('tracks',t))),this.events.fatalError$.subscribe(new Us('fatalError')),this.events.managedError$.subscribe(new Us('managedError')),e.position$.subscribe(new Us('position')),e.currentVideoTrack$.pipe(u((t=>null==t?void 0:t.quality))).subscribe(new Us('quality')),e.currentBuffer$.subscribe(new Us('buffer')),e.isBuffering$.subscribe(new Us('isBuffering'))].forEach((t=>this.subscription.add(t))),Bs('codecs',Object.keys(Il).filter((t=>Il[t])))}}const dp='@vkontakte/videoplayer-core@2.0.46';export{k as ChromecastState,D as HttpConnectionType,$ as PlaybackState,op as Player,dp as SDK_VERSION,_ as StartStatus,P as VideoFormat,As as VideoQuality};
|
|
6
|
+
import{ValueSubject as t,Subject as e,Subscription as i,isNonNullable as s,isNullable as r,fromEvent as a,assertNever as n,merge as o,tap as d,map as u,observableFrom as h,filterChanged as c,assertNonNullable as l,Observable as p,once as f,debounce as m,now as v,interval as g,filter as S,timeout as b,combine as y,mapTo as T,throttle as E,Logger as w}from'@vkontakte/videoplayer-shared/es2015.esm.js';export{Observable,Subject,Subscription,ValueSubject}from'@vkontakte/videoplayer-shared/es2015.esm.js';import $ from'lodash/debounce';var P,A,k,_,D,R;!function(t){t.STOPPED='stopped',t.PLAYING='playing',t.PAUSED='paused'}(P||(P={})),function(t){t.MPEG='MPEG',t.DASH='DASH',t.DASH_SEP='DASH_SEP',t.DASH_SEP_VK='DASH_SEP_VK',t.DASH_WEBM='DASH_WEBM',t.DASH_WEBM_VK='DASH_WEBM_VK',t.DASH_ONDEMAND='DASH_ONDEMAND',t.DASH_LIVE='DASH_LIVE',t.DASH_LIVE_WEBM='DASH_LIVE_WEBM',t.HLS='HLS',t.HLS_ONDEMAND='HLS_ONDEMAND',t.HLS_JS='HLS_JS',t.HLS_LIVE='HLS_LIVE'}(A||(A={})),function(t){t.SCREEN='SCREEN',t.CHROMECAST='CHROMECAST'}(k||(k={})),function(t){t.NOT_AVAILABLE='NOT_AVAILABLE',t.AVAILABLE='AVAILABLE',t.CONNECTING='CONNECTING',t.CONNECTED='CONNECTED'}(_||(_={})),function(t){t.SuccessWithSound='success_with_sound',t.SuccessWithoutSound='success_without_sound',t.Failed='failed'}(D||(D={})),function(t){t.HTTP1='http1',t.HTTP2='http2',t.QUIC='quic'}(R||(R={}));const I={throughputEstimator:{emaAlphaSlow:.2,emaAlphaFast:.7,changeThreshold:.2,useBrowserEstimation:!0,rttPenaltyRequestSize:1048576,streamMinSampleSize:10240,streamMinSampleTime:300},autoTrackSelection:{bitrateFactorAtEmptyBuffer:1.8,bitrateFactorAtFullBuffer:1.2,usePixelRatio:!0,limitByContainer:!0,containerSizeFactor:2,lazyQualitySwitch:!1},dash:{extraInitSize:1e3,forwardBufferTarget:3e4,segmentRequestSize:1048576,representationSwitchForwardBufferGap:3e3},enableTelemetryAtStart:!1,formatsToAvoid:[A.DASH_WEBM,A.DASH_SEP,A.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};class L{constructor(r){var a;this.connection$=new t(void 0),this.castState$=new t(_.NOT_AVAILABLE),this.errorEvent$=new e,this.realCastState$=new t(_.NOT_AVAILABLE),this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ChromecastInitializer');const n='chrome'in window;if(this.log({message:`[constructor] receiverApplicationId: ${this.params.receiverApplicationId}, isDisabled: ${this.params.isDisabled}, isSupported: ${n}`}),r.isDisabled||!n)return;var o;s(null===(a=window.chrome)||void 0===a?void 0:a.cast)?this.initializeCastApi():(window.__onGCastApiAvailable=t=>{t&&this.initializeCastApi()},(o='https://www.gstatic.com/cv/js/sender/v1/cast_sender.js?loadCastFramework=1',new Promise(((t,e)=>{const i=document.createElement('script');i.setAttribute('src',o),i.onload=()=>t,i.onerror=()=>e,document.body.appendChild(i)}))).catch((()=>this.errorEvent$.next({id:'ChromecastLoading',message:'Script loading failed!'}))))}connect(){var t;null===(t=cast.framework.CastContext.getInstance())||void 0===t||t.requestSession()}disconnect(){var t,e;null===(e=null===(t=cast.framework.CastContext.getInstance())||void 0===t?void 0:t.getCurrentSession())||void 0===e||e.endSession(!0)}stopMedia(){return new Promise(((t,e)=>{var i,s,r;null===(r=null===(s=null===(i=cast.framework.CastContext.getInstance())||void 0===i?void 0:i.getCurrentSession())||void 0===s?void 0:s.getMediaSession())||void 0===r||r.stop(new chrome.cast.media.StopRequest,t,e)}))}toggleConnection(){s(this.connection$.getValue())?this.disconnect():this.connect()}setVolume(t){const e=this.connection$.getValue();r(e)||(e.remotePlayer.volumeLevel=t,e.remotePlayerController.setVolumeLevel())}setMuted(t){const e=this.connection$.getValue();r(e)||t!==e.remotePlayer.isMuted&&e.remotePlayerController.muteOrUnmute()}destroy(){this.subscription.unsubscribe()}initListeners(){const t=new cast.framework.RemotePlayer,e=new cast.framework.RemotePlayerController(t),i=cast.framework.CastContext.getInstance();this.subscription.add(a(i,cast.framework.CastContextEventType.SESSION_STATE_CHANGED).subscribe((t=>{var e,s;switch(t.sessionState){case cast.framework.SessionState.SESSION_STARTED:case cast.framework.SessionState.SESSION_STARTING:case cast.framework.SessionState.SESSION_RESUMED:this.contentId=null===(s=null===(e=i.getCurrentSession())||void 0===e?void 0:e.getMediaSession())||void 0===s?void 0:s.media.contentId;break;case cast.framework.SessionState.NO_SESSION:case cast.framework.SessionState.SESSION_ENDING:case cast.framework.SessionState.SESSION_ENDED:case cast.framework.SessionState.SESSION_START_FAILED:this.contentId=void 0;break;default:return n(t.sessionState)}}))).add(o(a(i,cast.framework.CastContextEventType.CAST_STATE_CHANGED).pipe(d((t=>{this.log({message:`[cast.framework.RemotePlayerEventType.CAST_STATE_CHANGED]: ${JSON.stringify(t)}`})})),u((t=>t.castState))),h([i.getCastState()])).pipe(c(),u(x),d((t=>{this.log({message:`realCastState$: ${t}`})}))).subscribe(this.realCastState$)).add(this.realCastState$.subscribe((a=>{var n;const o=a===_.CONNECTED,d=s(this.connection$.getValue());if(o&&!d){const s=i.getCurrentSession();l(s);const a=s.getCastDevice(),o=null===(n=s.getMediaSession())||void 0===n?void 0:n.media.contentId;(r(o)||o===this.contentId)&&(this.log({message:'connection created'}),this.connection$.next({remotePlayer:t,remotePlayerController:e,session:s,castDevice:a}))}else!o&&d&&(this.log({message:'connection destroyed'}),this.connection$.next(void 0));this.castState$.next(a===_.CONNECTED?s(this.connection$.getValue())?_.CONNECTED:_.AVAILABLE:a)})))}initializeCastApi(){var t;let e,i,s;try{e=cast.framework.CastContext.getInstance(),i=chrome.cast.media.DEFAULT_MEDIA_RECEIVER_APP_ID,s=chrome.cast.AutoJoinPolicy.ORIGIN_SCOPED}catch(t){return}try{e.setOptions({receiverApplicationId:null!==(t=this.params.receiverApplicationId)&&void 0!==t?t:i,autoJoinPolicy:s}),this.initListeners()}catch(t){this.errorEvent$.next({id:'ChromecastInitializer',message:'[initializeCastApi] failed',thrown:t})}}}const x=t=>{switch(t){case cast.framework.CastState.NO_DEVICES_AVAILABLE:return _.NOT_AVAILABLE;case cast.framework.CastState.NOT_CONNECTED:return _.AVAILABLE;case cast.framework.CastState.CONNECTING:return _.CONNECTING;case cast.framework.CastState.CONNECTED:return _.CONNECTED;default:return n(t)}};function O(t,e,i,s){return new(i||(i=Promise))((function(r,a){function n(t){try{d(s.next(t))}catch(t){a(t)}}function o(t){try{d(s.throw(t))}catch(t){a(t)}}function d(t){var e;t.done?r(t.value):(e=t.value,e instanceof i?e:new i((function(t){t(e)}))).then(n,o)}d((s=s.apply(t,e||[])).next())}))}var C='undefined'!=typeof globalThis?globalThis:'undefined'!=typeof window?window:'undefined'!=typeof global?global:'undefined'!=typeof self?self:{},N=function(t){return t&&t.Math==Math&&t},M=N('object'==typeof globalThis&&globalThis)||N('object'==typeof window&&window)||N('object'==typeof self&&self)||N('object'==typeof C&&C)||function(){return this}()||Function('return this')(),B=function(t){try{return!!t()}catch(t){return!0}},U=!B((function(){var t=function(){}.bind();return'function'!=typeof t||t.hasOwnProperty('prototype')})),V=U,F=Function.prototype,H=F.apply,q=F.call,G='object'==typeof Reflect&&Reflect.apply||(V?q.bind(H):function(){return q.apply(H,arguments)}),Y=U,j=Function.prototype,z=j.bind,Q=j.call,W=Y&&z.bind(Q,Q),J=Y?function(t){return t&&W(t)}:function(t){return t&&function(){return Q.apply(t,arguments)}},K=function(t){return'function'==typeof t},X={},Z=!B((function(){return 7!=Object.defineProperty({},1,{get:function(){return 7}})[1]})),tt=U,et=Function.prototype.call,it=tt?et.bind(et):function(){return et.apply(et,arguments)},st={},rt={}.propertyIsEnumerable,at=Object.getOwnPropertyDescriptor,nt=at&&!rt.call({1:2},1);st.f=nt?function(t){var e=at(this,t);return!!e&&e.enumerable}:rt;var ot,dt,ut=function(t,e){return{enumerable:!(1&t),configurable:!(2&t),writable:!(4&t),value:e}},ht=J,ct=ht({}.toString),lt=ht(''.slice),pt=function(t){return lt(ct(t),8,-1)},ft=J,mt=B,vt=pt,gt=M.Object,St=ft(''.split),bt=mt((function(){return!gt('z').propertyIsEnumerable(0)}))?function(t){return'String'==vt(t)?St(t,''):gt(t)}:gt,yt=M.TypeError,Tt=function(t){if(null==t)throw yt('Can\'t call method on '+t);return t},Et=bt,wt=Tt,$t=function(t){return Et(wt(t))},Pt=K,At=function(t){return'object'==typeof t?null!==t:Pt(t)},kt={},_t=kt,Dt=M,Rt=K,It=function(t){return Rt(t)?t:void 0},Lt=function(t,e){return arguments.length<2?It(_t[t])||It(Dt[t]):_t[t]&&_t[t][e]||Dt[t]&&Dt[t][e]},xt=J({}.isPrototypeOf),Ot=Lt('navigator','userAgent')||'',Ct=M,Nt=Ot,Mt=Ct.process,Bt=Ct.Deno,Ut=Mt&&Mt.versions||Bt&&Bt.version,Vt=Ut&&Ut.v8;Vt&&(dt=(ot=Vt.split('.'))[0]>0&&ot[0]<4?1:+(ot[0]+ot[1])),!dt&&Nt&&(!(ot=Nt.match(/Edge\/(\d+)/))||ot[1]>=74)&&(ot=Nt.match(/Chrome\/(\d+)/))&&(dt=+ot[1]);var Ft=dt,Ht=Ft,qt=B,Gt=!!Object.getOwnPropertySymbols&&!qt((function(){var t=Symbol();return!String(t)||!(Object(t)instanceof Symbol)||!Symbol.sham&&Ht&&Ht<41})),Yt=Gt&&!Symbol.sham&&'symbol'==typeof Symbol.iterator,jt=Lt,zt=K,Qt=xt,Wt=Yt,Jt=M.Object,Kt=Wt?function(t){return'symbol'==typeof t}:function(t){var e=jt('Symbol');return zt(e)&&Qt(e.prototype,Jt(t))},Xt=M.String,Zt=function(t){try{return Xt(t)}catch(t){return'Object'}},te=K,ee=Zt,ie=M.TypeError,se=function(t){if(te(t))return t;throw ie(ee(t)+' is not a function')},re=se,ae=function(t,e){var i=t[e];return null==i?void 0:re(i)},ne=it,oe=K,de=At,ue=M.TypeError,he={exports:{}},ce=M,le=Object.defineProperty,pe=function(t,e){try{le(ce,t,{value:e,configurable:!0,writable:!0})}catch(i){ce[t]=e}return e},fe=M['__core-js_shared__']||pe('__core-js_shared__',{}),me=fe;(he.exports=function(t,e){return me[t]||(me[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 ve=Tt,ge=M.Object,Se=function(t){return ge(ve(t))},be=Se,ye=J({}.hasOwnProperty),Te=Object.hasOwn||function(t,e){return ye(be(t),e)},Ee=J,we=0,$e=Math.random(),Pe=Ee(1..toString),Ae=function(t){return'Symbol('+(void 0===t?'':t)+')_'+Pe(++we+$e,36)},ke=M,_e=he.exports,De=Te,Re=Ae,Ie=Gt,Le=Yt,xe=_e('wks'),Oe=ke.Symbol,Ce=Oe&&Oe.for,Ne=Le?Oe:Oe&&Oe.withoutSetter||Re,Me=function(t){if(!De(xe,t)||!Ie&&'string'!=typeof xe[t]){var e='Symbol.'+t;Ie&&De(Oe,t)?xe[t]=Oe[t]:xe[t]=Le&&Ce?Ce(e):Ne(e)}return xe[t]},Be=it,Ue=At,Ve=Kt,Fe=ae,He=function(t,e){var i,s;if('string'===e&&oe(i=t.toString)&&!de(s=ne(i,t)))return s;if(oe(i=t.valueOf)&&!de(s=ne(i,t)))return s;if('string'!==e&&oe(i=t.toString)&&!de(s=ne(i,t)))return s;throw ue('Can\'t convert object to primitive value')},qe=Me,Ge=M.TypeError,Ye=qe('toPrimitive'),je=function(t,e){if(!Ue(t)||Ve(t))return t;var i,s=Fe(t,Ye);if(s){if(void 0===e&&(e='default'),i=Be(s,t,e),!Ue(i)||Ve(i))return i;throw Ge('Can\'t convert object to primitive value')}return void 0===e&&(e='number'),He(t,e)},ze=Kt,Qe=function(t){var e=je(t,'string');return ze(e)?e:e+''},We=At,Je=M.document,Ke=We(Je)&&We(Je.createElement),Xe=function(t){return Ke?Je.createElement(t):{}},Ze=Xe,ti=!Z&&!B((function(){return 7!=Object.defineProperty(Ze('div'),'a',{get:function(){return 7}}).a})),ei=Z,ii=it,si=st,ri=ut,ai=$t,ni=Qe,oi=Te,di=ti,ui=Object.getOwnPropertyDescriptor;X.f=ei?ui:function(t,e){if(t=ai(t),e=ni(e),di)try{return ui(t,e)}catch(t){}if(oi(t,e))return ri(!ii(si.f,t,e),t[e])};var hi=B,ci=K,li=/#|\.prototype\./,pi=function(t,e){var i=mi[fi(t)];return i==gi||i!=vi&&(ci(e)?hi(e):!!e)},fi=pi.normalize=function(t){return String(t).replace(li,'.').toLowerCase()},mi=pi.data={},vi=pi.NATIVE='N',gi=pi.POLYFILL='P',Si=pi,bi=se,yi=U,Ti=J(J.bind),Ei=function(t,e){return bi(t),void 0===e?t:yi?Ti(t,e):function(){return t.apply(e,arguments)}},wi={},$i=Z&&B((function(){return 42!=Object.defineProperty((function(){}),'prototype',{value:42,writable:!1}).prototype})),Pi=M,Ai=At,ki=Pi.String,_i=Pi.TypeError,Di=function(t){if(Ai(t))return t;throw _i(ki(t)+' is not an object')},Ri=Z,Ii=ti,Li=$i,xi=Di,Oi=Qe,Ci=M.TypeError,Ni=Object.defineProperty,Mi=Object.getOwnPropertyDescriptor;wi.f=Ri?Li?function(t,e,i){if(xi(t),e=Oi(e),xi(i),'function'==typeof t&&'prototype'===e&&'value'in i&&'writable'in i&&!i.writable){var s=Mi(t,e);s&&s.writable&&(t[e]=i.value,i={configurable:'configurable'in i?i.configurable:s.configurable,enumerable:'enumerable'in i?i.enumerable:s.enumerable,writable:!1})}return Ni(t,e,i)}:Ni:function(t,e,i){if(xi(t),e=Oi(e),xi(i),Ii)try{return Ni(t,e,i)}catch(t){}if('get'in i||'set'in i)throw Ci('Accessors not supported');return'value'in i&&(t[e]=i.value),t};var Bi=wi,Ui=ut,Vi=Z?function(t,e,i){return Bi.f(t,e,Ui(1,i))}:function(t,e,i){return t[e]=i,t},Fi=M,Hi=G,qi=J,Gi=K,Yi=X.f,ji=Si,zi=kt,Qi=Ei,Wi=Vi,Ji=Te,Ki=function(t){var e=function(i,s,r){if(this instanceof e){switch(arguments.length){case 0:return new t;case 1:return new t(i);case 2:return new t(i,s)}return new t(i,s,r)}return Hi(t,this,arguments)};return e.prototype=t.prototype,e},Xi=function(t,e){var i,s,r,a,n,o,d,u,h=t.target,c=t.global,l=t.stat,p=t.proto,f=c?Fi:l?Fi[h]:(Fi[h]||{}).prototype,m=c?zi:zi[h]||Wi(zi,h,{})[h],v=m.prototype;for(r in e)i=!ji(c?r:h+(l?'.':'#')+r,t.forced)&&f&&Ji(f,r),n=m[r],i&&(o=t.noTargetGet?(u=Yi(f,r))&&u.value:f[r]),a=i&&o?o:e[r],i&&typeof n==typeof a||(d=t.bind&&i?Qi(a,Fi):t.wrap&&i?Ki(a):p&&Gi(a)?qi(a):a,(t.sham||a&&a.sham||n&&n.sham)&&Wi(d,'sham',!0),Wi(m,r,d),p&&(Ji(zi,s=h+'Prototype')||Wi(zi,s,{}),Wi(zi[s],r,a),t.real&&v&&!v[r]&&Wi(v,r,a)))},Zi=Math.ceil,ts=Math.floor,es=function(t){var e=+t;return e!=e||0===e?0:(e>0?ts:Zi)(e)},is=es,ss=Math.min,rs=function(t){return t>0?ss(is(t),9007199254740991):0},as=function(t){return rs(t.length)},ns=Se,os=as,ds=es;Xi({target:'Array',proto:!0},{at:function(t){var e=ns(this),i=os(e),s=ds(t),r=s>=0?s:i+s;return r<0||r>=i?void 0:e[r]}});var us,hs,cs,ls,ps=Lt,fs=ps('Array','at');!function(t){t.VIDEO='video',t.AUDIO='audio',t.TEXT='text'}(us||(us={})),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'}(hs||(hs={})),function(t){t.NONE='none',t.DOWNLOADING='downloading',t.DOWNLOADED='downloaded',t.FED='fed'}(cs||(cs={})),function(t){t.MP4='mp4',t.WEBM='webm'}(ls||(ls={}));var ms=t=>O(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}));const vs=(t,e,s,{equal:a=((t,e)=>t===e),changed$:n,onError:o}={})=>{const d=t.getState(),u=e(),h=r(n),c=new i;return n&&c.add(n.subscribe((e=>{const i=t.getState();a(e,i)&&t.setState(e)}),o)),a(u,d)||(s(d),h&&t.setState(d)),c.add(t.stateChangeStarted$.subscribe((e=>{s(e.to),h&&t.setState(e.to)}),o)),c},gs=(t,e,i)=>vs(e,(()=>t.loop),(e=>{s(e)&&(t.loop=e)}),{onError:i}),Ss=(t,e,i,r)=>vs(e,(()=>({muted:t.muted,volume:t.volume})),(e=>{s(e)&&(t.muted=e.muted,t.volume=e.volume)}),{equal:(t,e)=>t===e||(null==t?void 0:t.muted)===(null==e?void 0:e.muted)&&(null==t?void 0:t.volume)===(null==e?void 0:e.volume),changed$:i,onError:r}),bs=(t,e)=>{if(t.id===e)return!0;const[i,s,r]=e.split('|');return t.language===s&&t.label===r};class ys{constructor(){this.available$=new e,this.current$=new t(void 0),this.error$=new e,this.subscription=new i,this.externalTracks=new Map}connect(t,e,i){this.video=t,this.cueSettings=e.textTrackCuesSettings,this.subscribe();const r=t=>{this.error$.next({id:'TextTracksManager',message:'Generic HtmlVideoTextTrackManager error',thrown:t})};this.subscription.add(this.available$.subscribe(i.availableTextTracks$)),this.subscription.add(this.current$.subscribe(i.currentTextTrack$)),this.subscription.add(this.error$.subscribe(i.error$)),this.subscription.add(vs(e.externalTextTracks,(()=>Object.values(this.externalTracks)),(t=>{s(t)&&this.setExternal(t)}),{equal:(t,e)=>s(t)&&s(e)&&t.length===e.length&&t.every((({id:t},i)=>t===e[i].id)),changed$:this.available$.pipe(u((t=>t.filter((({type:t})=>'external'===t))))),onError:r})),this.subscription.add(vs(e.currentTextTrack,(()=>{if(this.video)return;const t=this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t));return t&&this.htmlTextTrackToITextTrack(t).id}),(t=>this.select(t)),{changed$:this.current$,onError:r})),this.subscription.add(vs(e.textTrackCuesSettings,(()=>({})),(()=>{if(this.video)for(const t of this.htmlTextTracksAsArray())this.applyCueSettings(t.cues),this.applyCueSettings(t.activeCues)})))}subscribe(){l(this.video);const{textTracks:t}=this.video;this.subscription.add(a(t,'addtrack').subscribe((()=>{const t=this.current$.getValue();this.select(t)}))),this.subscription.add(o(a(t,'addtrack'),a(t,'removetrack'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().map((t=>this.htmlTextTrackToITextTrack(t))))),c(((t,e)=>t.length===e.length&&t.every((({id:t},i)=>t===e[i].id))))).subscribe(this.available$)),this.subscription.add(o(a(t,'change'),h(['init'])).pipe(u((()=>this.htmlTextTracksAsArray().find((({mode:t})=>'showing'===t)))),u((t=>t&&this.htmlTextTrackToITextTrack(t).id)),c()).subscribe(this.current$));const e=t=>{var e,i;return this.applyCueSettings(null!==(i=null===(e=t.target)||void 0===e?void 0:e.activeCues)&&void 0!==i?i:null)};this.subscription.add(a(t,'addtrack').subscribe((t=>{var i,s;null===(i=t.track)||void 0===i||i.addEventListener('cuechange',e);const r=t=>{var e,i,s,a,n;const o=null!==(i=null===(e=t.target)||void 0===e?void 0:e.cues)&&void 0!==i?i:null;o&&o.length&&(this.applyCueSettings(null!==(a=null===(s=t.target)||void 0===s?void 0:s.cues)&&void 0!==a?a:null),null===(n=t.target)||void 0===n||n.removeEventListener('cuechange',r))};null===(s=t.track)||void 0===s||s.addEventListener('cuechange',r)}))),this.subscription.add(a(t,'removetrack').subscribe((t=>{var i;null===(i=t.track)||void 0===i||i.removeEventListener('cuechange',e)})))}applyCueSettings(t){if(!t||!t.length)return;const e=this.cueSettings.getState();for(const i of Array.from(t)){const t=i;s(e.align)&&(t.align=e.align),s(e.position)&&(t.position=e.position),s(e.size)&&(t.size=e.size),s(e.line)&&(t.line=e.line)}}htmlTextTracksAsArray(t=!1){l(this.video);const e=[...this.video.textTracks];return t?e:e.filter(ys.isHealthyTrack)}htmlTextTrackToITextTrack(t){const{language:e,label:i}=t,s=''!==t.id?t.id:(t=>['__',t.language,t.label].join('|'))(t);return this.externalTracks.has(s)?{id:s,type:'external',language:e,label:i,url:this.externalTracks.get(s).url}:{id:s,type:'internal',language:e,label:i}}static isHealthyTrack(t){return'metadata'!==t.kind&&(''!==t.id||''!==t.label||''!==t.language)}setExternal(t){t.filter((({id:t})=>!this.externalTracks.has(t))).forEach((t=>this.attach(t))),Array.from(this.externalTracks.keys()).filter((e=>!t.find((t=>t.id===e)))).forEach((t=>this.detach(t)))}select(t){l(this.video);for(const e of this.htmlTextTracksAsArray(!0))s(t)&&bs(e,t)?e.mode='showing':e.mode='disabled'}destroy(){if(this.subscription.unsubscribe(),this.video)for(const t of Array.from(this.video.getElementsByTagName('track'))){const e=t.getAttribute('id');e&&this.externalTracks.has(e)&&this.video.removeChild(t)}this.externalTracks.clear()}attach(t){l(this.video);const e=document.createElement('track');e.setAttribute('src',t.url),e.setAttribute('id',t.id),t.label&&e.setAttribute('label',t.label),t.language&&e.setAttribute('srclang',t.language),this.externalTracks.set(t.id,t),this.video.appendChild(e)}detach(t){l(this.video);const e=Array.prototype.find.call(this.video.getElementsByTagName('track'),(e=>e.getAttribute('id')===t));e&&this.video.removeChild(e),this.externalTracks.delete(t)}}var Ts=t=>{const e=document.createElement('video');return e.setAttribute('crossorigin','anonymous'),e.setAttribute('playsinline','playsinline'),t.appendChild(e),e},Es=t=>new p((e=>{let s=0;return(new i).add(a(t,'loadstart').subscribe((()=>{s=Date.now()}))).add(a(t,'loadeddata').subscribe((()=>{e.next(Date.now()-s)})))})).pipe(f());class ws{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 $s=(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}},Ps=t=>new p((e=>{let s=0;return(new i).add(a(t,'loadstart').subscribe((()=>{s=Date.now()}))).add(a(t,'loadedmetadata').subscribe((()=>{e.next(Date.now()-s)})))})).pipe(f());const As=t=>{const i=(e,i=(()=>{}))=>a(t,e).pipe(u(i)),r=o(...['waiting','pause','canplay','play','canplaythrough','playing','seeking','seeked','ended'].map((e=>a(t,e)))).pipe(u((()=>t.readyState<3)),c()),n=o(a(t,'progress'),a(t,'timeupdate')).pipe(u((()=>$s(t.buffered,t.currentTime)))),d=a(t,'volumechange').pipe(m(0),u((()=>({muted:t.muted,volume:t.volume})))),h=a(t,'error').pipe(u((()=>{const e=t.error;return{id:e?`MediaError#${e.code}`:'HtmlVideoError',message:e?e.message:'Error event from HTML video element'}}))),l=i('timeupdate',(()=>t.currentTime)),p=new e;let f;return l.subscribe((e=>{t.loop&&s(f)&&s(e)&&f>=t.duration-.3&&e<=.3&&p.next(f),f=e})),{playing$:i('playing'),pause$:i('pause'),canplay$:i('canplay'),ended$:i('ended'),looped$:p,error$:h,seeked$:i('seeked'),seeking$:i('seeking'),progress$:i('progress'),loadedMetadata$:i('loadedmetadata'),loadedData$:i('loadeddata'),timeUpdate$:l,durationChange$:i('durationchange',(()=>t.duration)),isBuffering$:r,currentBuffer$:n,volumeState$:d,firstBytes$:Ps(t),firstFrame$:Es(t)}};var ks;!function(t){t.INVARIANT='Invariant quality',t.Q_144P='144p',t.Q_240P='240p',t.Q_360P='360p',t.Q_480P='480p',t.Q_720P='720p',t.Q_1080P='1080p',t.Q_1440P='1440p',t.Q_2160P='2160p',t.Q_4320P='4320p'}(ks||(ks={}));var _s=t=>{switch(t){case'mobile':return ks.Q_144P;case'lowest':return ks.Q_240P;case'low':return ks.Q_360P;case'sd':case'medium':return ks.Q_480P;case'hd':case'high':return ks.Q_720P;case'fullhd':case'full':return ks.Q_1080P;case'quadhd':case'quad':return ks.Q_1440P;case'ultrahd':case'ultra':return ks.Q_2160P}},Ds=(t,e,i=!1)=>{const s=t.getTransition();!i&&s&&s.to!==e||t.setState(e)};const Rs={[ks.Q_144P]:{width:256,height:144},[ks.Q_240P]:{width:428,height:240},[ks.Q_360P]:{width:640,height:360},[ks.Q_480P]:{width:856,height:480},[ks.Q_720P]:{width:1280,height:720},[ks.Q_1080P]:{width:1920,height:1080},[ks.Q_1440P]:{width:2560,height:1440},[ks.Q_2160P]:{width:3840,height:2160},[ks.Q_4320P]:{width:7680,height:4320}},Is=(t,e)=>Rs[t].height>Rs[e].height,Ls=(t,e)=>Rs[t].height<Rs[e].height,xs=Object.keys(Rs).sort(((t,e)=>Ls(t,e)?-1:1)),Os=({width:t,height:e})=>{const i=Math.min(t,e),s=Math.max(t,e);return xs.find((t=>{const e=Rs[t];return e.width>=s&&e.height>=i}))},Cs=t=>t===ks.INVARIANT;let Ns=!1,Ms={};const Bs=t=>{t(Ms)},Us=(t,e)=>{var i;Ns&&(Ms.meta=null!==(i=Ms.meta)&&void 0!==i?i:{},Ms.meta[t]=e)};class Vs{constructor(t){this.name=t}next(t){var e,i;if(!Ns)return;Ms.series=null!==(e=Ms.series)&&void 0!==e?e:{};const s=null!==(i=Ms.series[this.name])&&void 0!==i?i:[];s.push([Date.now(),t]),Ms.series[this.name]=s}}const Fs=new Vs('best_bitrate'),Hs=(t,{container:e,throughput:i,tuning:a,limits:n,forwardBufferHealth:o,currentRepresentation:d})=>{var u,h,c,l;const p=a.usePixelRatio&&null!==(u=window.devicePixelRatio)&&void 0!==u?u:1,f=a.limitByContainer&&e&&e.width>0&&e.height>0&&{width:e.width*p*a.containerSizeFactor,height:e.height*p*a.containerSizeFactor},m=f&&Os(f),v=t.filter((t=>!Cs(t.quality))).sort(((t,e)=>Is(t.quality,e.quality)?-1:1)),g=null===(h=fs(v,-1))||void 0===h?void 0:h.quality,S=null===(c=fs(v,0))||void 0===c?void 0:c.quality,b=r(n)||s(n.min)&&s(n.max)&&Ls(n.max,n.min)||s(n.min)&&S&&Is(n.min,S)||s(n.max)&&g&&Ls(n.max,g),y=v.filter((t=>{var e;const u=!m||Ls(t.quality,m),h=!(s(i)&&isFinite(i)&&s(t.bitrate))||i>=t.bitrate*(c=null!=o?o:.5,l=a.bitrateFactorAtEmptyBuffer,p=a.bitrateFactorAtFullBuffer,(l-p)*Math.pow(2,-10*c)+p);var c,l,p;const f=!a.lazyQualitySwitch||!d||(null!=o?o:.5)>=.5||((null===(e=t.size)||void 0===e?void 0:e.height)||0)<=((null==d?void 0:d.height)||0),v=b||(r(n.max)||(g=t.quality,S=n.max,Rs[g].height<=Rs[S].height))&&(r(n.min)||((t,e)=>Rs[t].height>=Rs[e].height)(t.quality,n.min));var g,S;return u&&h&&f&&v}))[0];return y&&y.bitrate&&Fs.next(y.bitrate),null!==(l=null!=y?y:v[Math.ceil((v.length-1)/2)])&&void 0!==l?l:t[0]};var qs=(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)},Gs=t=>new URL(t).hostname;const Ys=(t,e=300)=>new p((i=>{const{width:r,height:a}=t.getBoundingClientRect();if(i.next({width:r,height:a}),!window.ResizeObserver)return;const n=new ResizeObserver($((t=>{const e=t[0];if(!e)return;let r,a;e.contentBoxSize&&e.contentBoxSize[0]?(a=e.contentBoxSize[0].blockSize,r=e.contentBoxSize[0].inlineSize):e.contentRect&&(r=e.contentRect.width,a=e.contentRect.height),s(r)&&s(a)&&i.next({width:r,height:a})}),e));return n.observe(t),()=>n.disconnect()}));class js{constructor(t){this.transitionStarted$=new e,this.transitionEnded$=new e,this.transitionUpdated$=new e,this.forceChanged$=new e,this.stateChangeStarted$=o(this.transitionStarted$,this.transitionUpdated$),this.stateChangeEnded$=o(this.transitionEnded$,this.forceChanged$),this.state=t}setState(t){const e=this.transition,i=this.state;this.transition=void 0,this.state=t,e?e.to===t?this.transitionEnded$.next(e):this.forceChanged$.next({from:e.from,to:t,canceledTransition:e}):this.forceChanged$.next({from:i,to:t,canceledTransition:e})}startTransitionTo(t){const e=this.transition,i=this.state;i===t||s(e)&&e.to===t||(this.state=t,e?(this.transition={from:e.from,to:t,canceledTransition:e},this.transitionUpdated$.next(this.transition)):(this.transition={from:i,to:t},this.transitionStarted$.next(this.transition)))}getTransition(){return this.transition}getState(){return this.state}}var zs={},Qs=K,Ws=fe,Js=J(Function.toString);Qs(Ws.inspectSource)||(Ws.inspectSource=function(t){return Js(t)});var Ks,Xs,Zs,tr=Ws.inspectSource,er=K,ir=tr,sr=M.WeakMap,rr=er(sr)&&/native code/.test(ir(sr)),ar=he.exports,nr=Ae,or=ar('keys'),dr=function(t){return or[t]||(or[t]=nr(t))},ur={},hr=rr,cr=M,lr=J,pr=At,fr=Vi,mr=Te,vr=fe,gr=dr,Sr=ur,br=cr.TypeError,yr=cr.WeakMap;if(hr||vr.state){var Tr=vr.state||(vr.state=new yr),Er=lr(Tr.get),wr=lr(Tr.has),$r=lr(Tr.set);Ks=function(t,e){if(wr(Tr,t))throw new br('Object already initialized');return e.facade=t,$r(Tr,t,e),e},Xs=function(t){return Er(Tr,t)||{}},Zs=function(t){return wr(Tr,t)}}else{var Pr=gr('state');Sr[Pr]=!0,Ks=function(t,e){if(mr(t,Pr))throw new br('Object already initialized');return e.facade=t,fr(t,Pr,e),e},Xs=function(t){return mr(t,Pr)?t[Pr]:{}},Zs=function(t){return mr(t,Pr)}}var Ar={set:Ks,get:Xs,has:Zs,enforce:function(t){return Zs(t)?Xs(t):Ks(t,{})},getterFor:function(t){return function(e){var i;if(!pr(e)||(i=Xs(e)).type!==t)throw br('Incompatible receiver, '+t+' required');return i}}},kr=Z,_r=Te,Dr=Function.prototype,Rr=kr&&Object.getOwnPropertyDescriptor,Ir=_r(Dr,'name'),Lr={EXISTS:Ir,PROPER:Ir&&'something'===function(){}.name,CONFIGURABLE:Ir&&(!kr||kr&&Rr(Dr,'name').configurable)},xr={},Or=es,Cr=Math.max,Nr=Math.min,Mr=$t,Br=function(t,e){var i=Or(t);return i<0?Cr(i+e,0):Nr(i,e)},Ur=as,Vr=function(t){return function(e,i,s){var r,a=Mr(e),n=Ur(a),o=Br(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}},Fr={includes:Vr(!0),indexOf:Vr(!1)},Hr=Te,qr=$t,Gr=Fr.indexOf,Yr=ur,jr=J([].push),zr=['constructor','hasOwnProperty','isPrototypeOf','propertyIsEnumerable','toLocaleString','toString','valueOf'],Qr=function(t,e){var i,s=qr(t),r=0,a=[];for(i in s)!Hr(Yr,i)&&Hr(s,i)&&jr(a,i);for(;e.length>r;)Hr(s,i=e[r++])&&(~Gr(a,i)||jr(a,i));return a},Wr=zr,Jr=Object.keys||function(t){return Qr(t,Wr)},Kr=Z,Xr=$i,Zr=wi,ta=Di,ea=$t,ia=Jr;xr.f=Kr&&!Xr?Object.defineProperties:function(t,e){ta(t);for(var i,s=ea(e),r=ia(e),a=r.length,n=0;a>n;)Zr.f(t,i=r[n++],s[i]);return t};var sa,ra=Lt('document','documentElement'),aa=Di,na=xr,oa=zr,da=ur,ua=ra,ha=Xe,ca=dr('IE_PROTO'),la=function(){},pa=function(t){return'<script>'+t+'<\/script>'},fa=function(t){t.write(pa('')),t.close();var e=t.parentWindow.Object;return t=null,e},ma=function(){try{sa=new ActiveXObject('htmlfile')}catch(t){}var t,e;ma='undefined'!=typeof document?document.domain&&sa?fa(sa):((e=ha('iframe')).style.display='none',ua.appendChild(e),e.src=String('javascript:'),(t=e.contentWindow.document).open(),t.write(pa('document.F=Object')),t.close(),t.F):fa(sa);for(var i=oa.length;i--;)delete ma.prototype[oa[i]];return ma()};da[ca]=!0;var va,ga,Sa,ba=Object.create||function(t,e){var i;return null!==t?(la.prototype=aa(t),i=new la,la.prototype=null,i[ca]=t):i=ma(),void 0===e?i:na.f(i,e)},ya=!B((function(){function t(){}return t.prototype.constructor=null,Object.getPrototypeOf(new t)!==t.prototype})),Ta=M,Ea=Te,wa=K,$a=Se,Pa=ya,Aa=dr('IE_PROTO'),ka=Ta.Object,_a=ka.prototype,Da=Pa?ka.getPrototypeOf:function(t){var e=$a(t);if(Ea(e,Aa))return e[Aa];var i=e.constructor;return wa(i)&&e instanceof i?i.prototype:e instanceof ka?_a:null},Ra=Vi,Ia=function(t,e,i,s){s&&s.enumerable?t[e]=i:Ra(t,e,i)},La=B,xa=K,Oa=ba,Ca=Da,Na=Ia,Ma=Me('iterator'),Ba=!1;[].keys&&('next'in(Sa=[].keys())?(ga=Ca(Ca(Sa)))!==Object.prototype&&(va=ga):Ba=!0);var Ua=null==va||La((function(){var t={};return va[Ma].call(t)!==t}));xa((va=Ua?{}:Oa(va))[Ma])||Na(va,Ma,(function(){return this}));var Va={IteratorPrototype:va,BUGGY_SAFARI_ITERATORS:Ba},Fa={};Fa[Me('toStringTag')]='z';var Ha='[object z]'===String(Fa),qa=M,Ga=Ha,Ya=K,ja=pt,za=Me('toStringTag'),Qa=qa.Object,Wa='Arguments'==ja(function(){return arguments}()),Ja=Ga?ja: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=Qa(t),za))?i:Wa?ja(e):'Object'==(s=ja(e))&&Ya(e.callee)?'Arguments':s},Ka=Ja,Xa=Ha?{}.toString:function(){return'[object '+Ka(this)+']'},Za=Ha,tn=wi.f,en=Vi,sn=Te,rn=Xa,an=Me('toStringTag'),nn=function(t,e,i,s){if(t){var r=i?t:t.prototype;sn(r,an)||tn(r,an,{configurable:!0,value:e}),s&&!Za&&en(r,'toString',rn)}},on=Va.IteratorPrototype,dn=ba,un=ut,hn=nn,cn=zs,ln=function(){return this},pn=M,fn=(pn.String,pn.TypeError,J);Object.setPrototypeOf||'__proto__'in{}&&function(){var t,e=!1,i={};try{(t=fn(Object.getOwnPropertyDescriptor(Object.prototype,'__proto__').set))(i,[]),e=i instanceof Array}catch(t){}}();var mn=Xi,vn=it,gn=function(t,e,i,s){var r=e+' Iterator';return t.prototype=dn(on,{next:un(+!s,i)}),hn(t,r,!1,!0),cn[r]=ln,t},Sn=Da,bn=nn,yn=Ia,Tn=zs,En=Lr.PROPER,wn=Va.BUGGY_SAFARI_ITERATORS,$n=Me('iterator'),Pn=function(){return this},An=$t,kn=zs,_n=Ar;wi.f;var Dn=function(t,e,i,s,r,a,n){gn(i,e,s);var o,d,u,h=function(t){if(t===r&&m)return m;if(!wn&&t in p)return p[t];switch(t){case'keys':case'values':case'entries':return function(){return new i(this,t)}}return function(){return new i(this)}},c=e+' Iterator',l=!1,p=t.prototype,f=p[$n]||p['@@iterator']||r&&p[r],m=!wn&&f||h(r),v='Array'==e&&p.entries||f;if(v&&(o=Sn(v.call(new t)))!==Object.prototype&&o.next&&(bn(o,c,!0,!0),Tn[c]=Pn),En&&'values'==r&&f&&'values'!==f.name&&(l=!0,m=function(){return vn(f,this)}),r)if(d={values:h('values'),keys:a?m:h('keys'),entries:h('entries')},n)for(u in d)(wn||l||!(u in p))&&yn(p,u,d[u]);else mn({target:e,proto:!0,forced:wn||l},d);return n&&p[$n]!==m&&yn(p,$n,m,{name:r}),Tn[e]=m,d},Rn=_n.set,In=_n.getterFor('Array Iterator');Dn(Array,'Array',(function(t,e){Rn(this,{type:'Array Iterator',target:An(t),index:0,kind:e})}),(function(){var t=In(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'),kn.Arguments=kn.Array;var Ln=zs,xn=Me('iterator'),On=Array.prototype,Cn=Ja,Nn=ae,Mn=zs,Bn=Me('iterator'),Un=function(t){if(null!=t)return Nn(t,Bn)||Nn(t,'@@iterator')||Mn[Cn(t)]},Vn=it,Fn=se,Hn=Di,qn=Zt,Gn=Un,Yn=M.TypeError,jn=it,zn=Di,Qn=ae,Wn=Ei,Jn=it,Kn=Di,Xn=Zt,Zn=function(t){return void 0!==t&&(Ln.Array===t||On[xn]===t)},to=as,eo=xt,io=function(t,e){var i=arguments.length<2?Gn(t):e;if(Fn(i))return Hn(Vn(i,t));throw Yn(qn(t)+' is not iterable')},so=Un,ro=function(t,e,i){var s,r;zn(t);try{if(!(s=Qn(t,'return'))){if('throw'===e)throw i;return i}s=jn(s,t)}catch(t){r=!0,s=t}if('throw'===e)throw i;if(r)throw s;return zn(s),i},ao=M.TypeError,no=function(t,e){this.stopped=t,this.result=e},oo=no.prototype,uo=function(t,e,i){var s,r,a,n,o,d,u,h=i&&i.that,c=!(!i||!i.AS_ENTRIES),l=!(!i||!i.IS_ITERATOR),p=!(!i||!i.INTERRUPTED),f=Wn(e,h),m=function(t){return s&&ro(s,'normal',t),new no(!0,t)},v=function(t){return c?(Kn(t),p?f(t[0],t[1],m):f(t[0],t[1])):p?f(t,m):f(t)};if(l)s=t;else{if(!(r=so(t)))throw ao(Xn(t)+' is not iterable');if(Zn(r)){for(a=0,n=to(t);n>a;a++)if((o=v(t[a]))&&eo(oo,o))return o;return new no(!1)}s=io(t,r)}for(d=s.next;!(u=Jn(d,s)).done;){try{o=v(u.value)}catch(t){ro(s,'throw',t)}if('object'==typeof o&&o&&eo(oo,o))return o}return new no(!1)},ho=Qe,co=wi,lo=ut,po=uo,fo=function(t,e,i){var s=ho(e);s in t?co.f(t,s,lo(0,i)):t[s]=i};Xi({target:'Object',stat:!0},{fromEntries:function(t){var e={};return po(t,(function(t,i){fo(e,t,i)}),{AS_ENTRIES:!0}),e}});var mo=kt.Object.fromEntries,vo={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},go=M,So=Ja,bo=Vi,yo=zs,To=Me('toStringTag');for(var Eo in vo){var wo=go[Eo],$o=wo&&wo.prototype;$o&&So($o)!==To&&bo($o,To,Eo),yo[Eo]=yo.Array}var Po=mo,Ao={};function ko(t,e){if(!(t instanceof e))throw new TypeError('Cannot call a class as a function')}function _o(t,e){for(var i=0;i<e.length;i++){var s=e[i];s.enumerable=s.enumerable||!1,s.configurable=!0,'value'in s&&(s.writable=!0),Object.defineProperty(t,s.key,s)}}function Do(t,e,i){return e&&_o(t.prototype,e),i&&_o(t,i),t}function Ro(t){return(Ro=Object.setPrototypeOf?Object.getPrototypeOf:function(t){return t.__proto__||Object.getPrototypeOf(t)})(t)}function Io(t,e){return(Io=Object.setPrototypeOf||function(t,e){return t.__proto__=e,t})(t,e)}function Lo(t){if(void 0===t)throw new ReferenceError('this hasn\'t been initialised - super() hasn\'t been called');return t}function xo(t,e){return!e||'object'!=typeof e&&'function'!=typeof e?Lo(t):e}function Oo(t){var e=function(){if('undefined'==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if('function'==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(t){return!1}}();return function(){var i,s=Ro(t);if(e){var r=Ro(this).constructor;i=Reflect.construct(s,arguments,r)}else i=s.apply(this,arguments);return xo(this,i)}}function Co(t,e,i){return(Co='undefined'!=typeof Reflect&&Reflect.get?Reflect.get:function(t,e,i){var s=function(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=Ro(t)););return t}(t,e);if(s){var r=Object.getOwnPropertyDescriptor(s,e);return r.get?r.get.call(i):r.value}})(t,e,i||t)}Object.defineProperty(Ao,'__esModule',{value:!0});var No=function(){function t(){ko(this,t),Object.defineProperty(this,'listeners',{value:{},writable:!0,configurable:!0})}return Do(t,[{key:'addEventListener',value:function(t,e,i){t in this.listeners||(this.listeners[t]=[]),this.listeners[t].push({callback:e,options:i})}},{key:'removeEventListener',value:function(t,e){if(t in this.listeners)for(var i=this.listeners[t],s=0,r=i.length;s<r;s++)if(i[s].callback===e)return void i.splice(s,1)}},{key:'dispatchEvent',value:function(t){if(t.type in this.listeners){for(var e=this.listeners[t.type].slice(),i=0,s=e.length;i<s;i++){var r=e[i];try{r.callback.call(this,t)}catch(t){Promise.resolve().then((function(){throw t}))}r.options&&r.options.once&&this.removeEventListener(t.type,r.callback)}return!t.defaultPrevented}}}]),t}(),Mo=function(t){!function(t,e){if('function'!=typeof e&&null!==e)throw new TypeError('Super expression must either be null or a function');t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,writable:!0,configurable:!0}}),e&&Io(t,e)}(i,No);var e=Oo(i);function i(){var t;return ko(this,i),(t=e.call(this)).listeners||No.call(Lo(t)),Object.defineProperty(Lo(t),'aborted',{value:!1,writable:!0,configurable:!0}),Object.defineProperty(Lo(t),'onabort',{value:null,writable:!0,configurable:!0}),t}return Do(i,[{key:'toString',value:function(){return'[object AbortSignal]'}},{key:'dispatchEvent',value:function(t){'abort'===t.type&&(this.aborted=!0,'function'==typeof this.onabort&&this.onabort.call(this,t)),Co(Ro(i.prototype),'dispatchEvent',this).call(this,t)}}]),i}(),Bo=function(){function t(){ko(this,t),Object.defineProperty(this,'signal',{value:new Mo,writable:!0,configurable:!0})}return Do(t,[{key:'abort',value:function(){var t;try{t=new Event('abort')}catch(e){'undefined'!=typeof document?document.createEvent?(t=document.createEvent('Event')).initEvent('abort',!1,!1):(t=document.createEventObject()).type='abort':t={type:'abort',bubbles:!1,cancelable:!1}}this.signal.dispatchEvent(t)}},{key:'toString',value:function(){return'[object AbortController]'}}]),t}();'undefined'!=typeof Symbol&&Symbol.toStringTag&&(Bo.prototype[Symbol.toStringTag]='AbortController',Mo.prototype[Symbol.toStringTag]='AbortSignal');var Uo=Ao.AbortController=Bo;Ao.AbortSignal=Mo;var Vo=Ao.abortableFetch=function(t){'function'==typeof t&&(t={fetch:t});var e=t,i=e.fetch,s=e.Request,r=void 0===s?i.Request:s,a=e.AbortController,n=e.__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL,o=void 0!==n&&n;if(!function(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}({fetch:i,Request:r,AbortController:a,__FORCE_INSTALL_ABORTCONTROLLER_POLYFILL:o}))return{fetch:i,Request:d};var d=r;(d&&!d.prototype.hasOwnProperty('signal')||o)&&((d=function(t,e){var i;e&&e.signal&&(i=e.signal,delete e.signal);var s=new r(t,e);return i&&Object.defineProperty(s,'signal',{writable:!1,enumerable:!1,configurable:!0,value:i}),s}).prototype=r.prototype);var u=i;return{fetch:function(t,e){var i=d&&d.prototype.isPrototypeOf(t)?t.signal:e?e.signal:void 0;if(i){var s;try{s=new DOMException('Aborted','AbortError')}catch(t){(s=new Error('Aborted')).name='AbortError'}if(i.aborted)return Promise.reject(s);var r=new Promise((function(t,e){i.addEventListener('abort',(function(){return e(s)}),{once:!0})}));return e&&e.signal&&delete e.signal,Promise.race([r,u(t,e)])}return u(t,e)},Request:d}},Fo=M.Promise,Ho=Ia,qo=Lt,Go=wi,Yo=Z,jo=Me('species'),zo=xt,Qo=M.TypeError,Wo=Me('iterator'),Jo=!1;try{var Ko=0,Xo={next:function(){return{done:!!Ko++}},return:function(){Jo=!0}};Xo[Wo]=function(){return this},Array.from(Xo,(function(){throw 2}))}catch(t){}var Zo=J,td=B,ed=K,id=Ja,sd=tr,rd=function(){},ad=[],nd=Lt('Reflect','construct'),od=/^\s*(?:class|function)\b/,dd=Zo(od.exec),ud=!od.exec(rd),hd=function(t){if(!ed(t))return!1;try{return nd(rd,ad,t),!0}catch(t){return!1}},cd=function(t){if(!ed(t))return!1;switch(id(t)){case'AsyncFunction':case'GeneratorFunction':case'AsyncGeneratorFunction':return!1}try{return ud||!!dd(od,sd(t))}catch(t){return!0}};cd.sham=!0;var ld,pd,fd,md,vd=!nd||td((function(){var t;return hd(hd.call)||!hd(Object)||!hd((function(){t=!0}))||t}))?cd:hd,gd=Zt,Sd=M.TypeError,bd=Di,yd=function(t){if(vd(t))return t;throw Sd(gd(t)+' is not a constructor')},Td=Me('species'),Ed=function(t,e){var i,s=bd(t).constructor;return void 0===s||null==(i=bd(s)[Td])?e:yd(i)},wd=J([].slice),$d=M.TypeError,Pd=/(?:ipad|iphone|ipod).*applewebkit/i.test(Ot),Ad='process'==pt(M.process),kd=M,_d=G,Dd=Ei,Rd=K,Id=Te,Ld=B,xd=ra,Od=wd,Cd=Xe,Nd=function(t,e){if(t<e)throw $d('Not enough arguments');return t},Md=Pd,Bd=Ad,Ud=kd.setImmediate,Vd=kd.clearImmediate,Fd=kd.process,Hd=kd.Dispatch,qd=kd.Function,Gd=kd.MessageChannel,Yd=kd.String,jd=0,zd={};try{ld=kd.location}catch(t){}var Qd=function(t){if(Id(zd,t)){var e=zd[t];delete zd[t],e()}},Wd=function(t){return function(){Qd(t)}},Jd=function(t){Qd(t.data)},Kd=function(t){kd.postMessage(Yd(t),ld.protocol+'//'+ld.host)};Ud&&Vd||(Ud=function(t){Nd(arguments.length,1);var e=Rd(t)?t:qd(t),i=Od(arguments,1);return zd[++jd]=function(){_d(e,void 0,i)},pd(jd),jd},Vd=function(t){delete zd[t]},Bd?pd=function(t){Fd.nextTick(Wd(t))}:Hd&&Hd.now?pd=function(t){Hd.now(Wd(t))}:Gd&&!Md?(md=(fd=new Gd).port2,fd.port1.onmessage=Jd,pd=Dd(md.postMessage,md)):kd.addEventListener&&Rd(kd.postMessage)&&!kd.importScripts&&ld&&'file:'!==ld.protocol&&!Ld(Kd)?(pd=Kd,kd.addEventListener('message',Jd,!1)):pd='onreadystatechange'in Cd('script')?function(t){xd.appendChild(Cd('script')).onreadystatechange=function(){xd.removeChild(this),Qd(t)}}:function(t){setTimeout(Wd(t),0)});var Xd,Zd,tu,eu,iu,su,ru,au,nu={set:Ud,clear:Vd},ou=M,du=/ipad|iphone|ipod/i.test(Ot)&&void 0!==ou.Pebble,uu=/web0s(?!.*chrome)/i.test(Ot),hu=M,cu=Ei,lu=X.f,pu=nu.set,fu=Pd,mu=du,vu=uu,gu=Ad,Su=hu.MutationObserver||hu.WebKitMutationObserver,bu=hu.document,yu=hu.process,Tu=hu.Promise,Eu=lu(hu,'queueMicrotask'),wu=Eu&&Eu.value;wu||(Xd=function(){var t,e;for(gu&&(t=yu.domain)&&t.exit();Zd;){e=Zd.fn,Zd=Zd.next;try{e()}catch(t){throw Zd?eu():tu=void 0,t}}tu=void 0,t&&t.enter()},fu||gu||vu||!Su||!bu?!mu&&Tu&&Tu.resolve?((ru=Tu.resolve(void 0)).constructor=Tu,au=cu(ru.then,ru),eu=function(){au(Xd)}):gu?eu=function(){yu.nextTick(Xd)}:(pu=cu(pu,hu),eu=function(){pu(Xd)}):(iu=!0,su=bu.createTextNode(''),new Su(Xd).observe(su,{characterData:!0}),eu=function(){su.data=iu=!iu}));var $u=wu||function(t){var e={fn:t,next:void 0};tu&&(tu.next=e),Zd||(Zd=e,eu()),tu=e},Pu={},Au=se,ku=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=Au(e),this.reject=Au(i)};Pu.f=function(t){return new ku(t)};var _u=Di,Du=At,Ru=Pu,Iu=function(t,e){if(_u(t),Du(e)&&e.constructor===t)return e;var i=Ru.f(t);return(0,i.resolve)(e),i.promise},Lu=M,xu=function(){this.head=null,this.tail=null};xu.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 Ou,Cu,Nu,Mu='object'==typeof window,Bu=Xi,Uu=M,Vu=Lt,Fu=it,Hu=Fo,qu=function(t,e,i){for(var s in e)i&&i.unsafe&&t[s]?t[s]=e[s]:Ho(t,s,e[s],i);return t},Gu=nn,Yu=function(t){var e=qo(t),i=Go.f;Yo&&e&&!e[jo]&&i(e,jo,{configurable:!0,get:function(){return this}})},ju=se,zu=K,Qu=At,Wu=function(t,e){if(zo(e,t))return t;throw Qo('Incorrect invocation')},Ju=tr,Ku=uo,Xu=function(t,e){if(!e&&!Jo)return!1;var i=!1;try{var s={};s[Wo]=function(){return{next:function(){return{done:i=!0}}}},t(s)}catch(t){}return i},Zu=Ed,th=nu.set,eh=$u,ih=Iu,sh=function(t,e){var i=Lu.console;i&&i.error&&(1==arguments.length?i.error(t):i.error(t,e))},rh=Pu,ah=function(t){try{return{error:!1,value:t()}}catch(t){return{error:!0,value:t}}},nh=xu,oh=Ar,dh=Si,uh=Mu,hh=Ad,ch=Ft,lh=Me('species'),ph='Promise',fh=oh.getterFor(ph),mh=oh.set,vh=oh.getterFor(ph),gh=Hu&&Hu.prototype,Sh=Hu,bh=gh,yh=Uu.TypeError,Th=Uu.document,Eh=Uu.process,wh=rh.f,$h=wh,Ph=!!(Th&&Th.createEvent&&Uu.dispatchEvent),Ah=zu(Uu.PromiseRejectionEvent),kh=dh(ph,(function(){var t=Ju(Sh),e=t!==String(Sh);if(!e&&66===ch)return!0;if(!bh.finally)return!0;if(ch>=51&&/native code/.test(t))return!1;var i=new Sh((function(t){t(1)})),s=function(t){t((function(){}),(function(){}))};return(i.constructor={})[lh]=s,!(i.then((function(){}))instanceof s)||!e&&uh&&!Ah})),_h=kh||!Xu((function(t){Sh.all(t).catch((function(){}))})),Dh=function(t){var e;return!(!Qu(t)||!zu(e=t.then))&&e},Rh=function(t,e){var i,s,r,a=e.value,n=1==e.state,o=n?t.ok:t.fail,d=t.resolve,u=t.reject,h=t.domain;try{o?(n||(2===e.rejection&&Ch(e),e.rejection=1),!0===o?i=a:(h&&h.enter(),i=o(a),h&&(h.exit(),r=!0)),i===t.promise?u(yh('Promise-chain cycle')):(s=Dh(i))?Fu(s,i,d,u):d(i)):u(a)}catch(t){h&&!r&&h.exit(),u(t)}},Ih=function(t,e){t.notified||(t.notified=!0,eh((function(){for(var i,s=t.reactions;i=s.get();)Rh(i,t);t.notified=!1,e&&!t.rejection&&xh(t)})))},Lh=function(t,e,i){var s,r;Ph?((s=Th.createEvent('Event')).promise=e,s.reason=i,s.initEvent(t,!1,!0),Uu.dispatchEvent(s)):s={promise:e,reason:i},!Ah&&(r=Uu['on'+t])?r(s):'unhandledrejection'===t&&sh('Unhandled promise rejection',i)},xh=function(t){Fu(th,Uu,(function(){var e,i=t.facade,s=t.value;if(Oh(t)&&(e=ah((function(){hh?Eh.emit('unhandledRejection',s,i):Lh('unhandledrejection',i,s)})),t.rejection=hh||Oh(t)?2:1,e.error))throw e.value}))},Oh=function(t){return 1!==t.rejection&&!t.parent},Ch=function(t){Fu(th,Uu,(function(){var e=t.facade;hh?Eh.emit('rejectionHandled',e):Lh('rejectionhandled',e,t.value)}))},Nh=function(t,e,i){return function(s){t(e,s,i)}},Mh=function(t,e,i){t.done||(t.done=!0,i&&(t=i),t.value=e,t.state=2,Ih(t,!0))},Bh=function(t,e,i){if(!t.done){t.done=!0,i&&(t=i);try{if(t.facade===e)throw yh('Promise can\'t be resolved itself');var s=Dh(e);s?eh((function(){var i={done:!1};try{Fu(s,e,Nh(Bh,i,t),Nh(Mh,i,t))}catch(e){Mh(i,e,t)}})):(t.value=e,t.state=1,Ih(t,!1))}catch(e){Mh({done:!1},e,t)}}};kh&&(bh=(Sh=function(t){Wu(this,bh),ju(t),Fu(Ou,this);var e=fh(this);try{t(Nh(Bh,e),Nh(Mh,e))}catch(t){Mh(e,t)}}).prototype,(Ou=function(t){mh(this,{type:ph,done:!1,notified:!1,parent:!1,reactions:new nh,rejection:!1,state:0,value:void 0})}).prototype=qu(bh,{then:function(t,e){var i=vh(this),s=wh(Zu(this,Sh));return i.parent=!0,s.ok=!zu(t)||t,s.fail=zu(e)&&e,s.domain=hh?Eh.domain:void 0,0==i.state?i.reactions.add(s):eh((function(){Rh(s,i)})),s.promise},catch:function(t){return this.then(void 0,t)}}),Cu=function(){var t=new Ou,e=fh(t);this.promise=t,this.resolve=Nh(Bh,e),this.reject=Nh(Mh,e)},rh.f=wh=function(t){return t===Sh||t===Nu?new Cu(t):$h(t)}),Bu({global:!0,wrap:!0,forced:kh},{Promise:Sh}),Gu(Sh,ph,!1,!0),Yu(ph),Nu=Vu(ph),Bu({target:ph,stat:!0,forced:kh},{reject:function(t){var e=wh(this);return Fu(e.reject,void 0,t),e.promise}}),Bu({target:ph,stat:!0,forced:true},{resolve:function(t){return ih(this===Nu?Sh:this,t)}}),Bu({target:ph,stat:!0,forced:_h},{all:function(t){var e=this,i=wh(e),s=i.resolve,r=i.reject,a=ah((function(){var i=ju(e.resolve),a=[],n=0,o=1;Ku(t,(function(t){var d=n++,u=!1;o++,Fu(i,e,t).then((function(t){u||(u=!0,a[d]=t,--o||s(a))}),r)})),--o||s(a)}));return a.error&&r(a.value),i.promise},race:function(t){var e=this,i=wh(e),s=i.reject,r=ah((function(){var r=ju(e.resolve);Ku(t,(function(t){Fu(r,e,t).then(i.resolve,s)}))}));return r.error&&s(r.value),i.promise}});var Uh=Fo,Vh=Lt,Fh=K,Hh=Ed,qh=Iu;Xi({target:'Promise',proto:!0,real:!0,forced:!!Uh&&B((function(){Uh.prototype.finally.call({then:function(){}},(function(){}))}))},{finally:function(t){var e=Hh(this,Vh('Promise')),i=Fh(t);return this.then(i?function(i){return qh(e,t()).then((function(){return i}))}:t,i?function(i){return qh(e,t()).then((function(){throw i}))}:t)}});var Gh,Yh=ps('Promise','finally'),jh=t=>{var e,i;const s=t.get('X-Delivery-Type'),r=t.get('X-Reused');return{type:null===s?R.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}};!function(t){t[t.HEADER=0]='HEADER',t[t.PARAM=1]='PARAM'}(Gh||(Gh={}));class zh{constructor({throughputEstimator:e}={}){this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.abortAllController=new Uo,this.subscription=new i,this.fetchRepresentation=(t,e,i=0)=>O(this,void 0,void 0,(function*(){const{from:s,to:r}=t.initRange;let a,n,o=s,d=r,u=!1;t.indexRange&&(a=t.indexRange.from,n=t.indexRange.to,u=r+1===a,u&&(o=Math.min(a,s),d=Math.max(n,r))),o=Math.min(o,0),d+=i;const h=yield this.fetchRange(t.url,o,d,{method:Gh.PARAM});if(!h)return null;const c=new DataView(h,s-o,r-o);if(!e.validateData(c))throw new Error('Invalid media file');const l=e.parseInit(c);let p;if(u&&void 0!==a&&void 0!==n)p=new DataView(h,a-o,n-a);else{const i=e.getIndexRange(l);if(i){const e=yield this.fetchRange(t.url,i.from,i.to,{method:Gh.PARAM});if(!e)return null;p=new DataView(e)}}if(!p)throw new ReferenceError('No way to load representation index');const f=e.parseSegments(p,l);return{dataView:new DataView(h),segments:f}})),this.throughputEstimator=e}onHeadersReceived(t){const{type:e,reused:i}=jh(t);this.lastConnectionType$.next(e),this.lastConnectionReused$.next(i)}fetchManifest(t){return O(this,void 0,void 0,(function*(){const e=yield Vo(fetch).fetch(t,{signal:this.abortAllController.signal}).catch(Qh);return e?(this.onHeadersReceived(e.headers),e.text()):null}))}fetchRange(t,e,i,{method:s=Gh.HEADER,onProgress:r,signal:d}={}){var u,h,c;return O(this,void 0,void 0,(function*(){let l=t;const p=new Headers;switch(s){case Gh.HEADER:p.append('Range',`${e}-${i}`);break;case Gh.PARAM:{const t=new URL(l,location.href);t.searchParams.append('bytes',`${e}-${i}`),l=t.toString();break}default:n(s)}let f=this.abortAllController.signal;if(d){const t=new Uo;this.subscription.add(o(a(this.abortAllController.signal,'abort'),a(d,'abort')).subscribe((()=>{t.abort()}))),(this.abortAllController.signal.aborted||d.aborted)&&t.abort(),f=t.signal}const m=v(),g=yield Vo(fetch).fetch(l,{headers:p,signal:f}).catch(Qh);if(null===(u=this.throughputEstimator)||void 0===u||u.addRawRtt(v()-m),!g)return null;if(!g.ok||!g.body)return Promise.reject(new Error(`Fetch error ${g.status}: ${g.statusText}`));this.onHeadersReceived(g.headers);const[S,b]=g.body.tee(),y=S.getReader();null===(h=this.throughputEstimator)||void 0===h||h.trackStream(b);const T=parseInt(null!==(c=g.headers.get('Content-Length'))&&void 0!==c?c:'',10);let E=0;const w=new ArrayBuffer(T),$=new Uint8Array(w),P=new DataView(w);let A=!1;const k=t=>{A=!0,Qh(t)},_=({done:t,value:e})=>O(this,void 0,void 0,(function*(){0===E&&this.lastRequestFirstBytes$.next(v()-m),t?null==r||r(P,E):e&&($.set(e,E),E+=e.byteLength,null==r||r(P,E),yield null==y?void 0:y.read().then(_,k))}));return yield null==y?void 0:y.read().then(_,k),A?null:w}))}destroy(){this.abortAllController.abort(),this.subscription.unsubscribe()}}const Qh=t=>{if(!(t instanceof DOMException)||'AbortError'!==t.name&&20!==t.code)throw t};var Wh,Jh;!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.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'}(Wh||(Wh={})),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'}(Jh||(Jh={}));const Kh={[Wh.EBML]:{type:Jh.Master},[Wh.EBMLVersion]:{type:Jh.UnsignedInteger},[Wh.EBMLReadVersion]:{type:Jh.UnsignedInteger},[Wh.EBMLMaxIDLength]:{type:Jh.UnsignedInteger},[Wh.EBMLMaxSizeLength]:{type:Jh.UnsignedInteger},[Wh.DocType]:{type:Jh.String},[Wh.DocTypeVersion]:{type:Jh.UnsignedInteger},[Wh.DocTypeReadVersion]:{type:Jh.UnsignedInteger},[Wh.Void]:{type:Jh.Binary},[Wh.Segment]:{type:Jh.Master},[Wh.SeekHead]:{type:Jh.Master},[Wh.Seek]:{type:Jh.Master},[Wh.SeekID]:{type:Jh.Binary},[Wh.SeekPosition]:{type:Jh.UnsignedInteger},[Wh.Info]:{type:Jh.Master},[Wh.TimestampScale]:{type:Jh.UnsignedInteger},[Wh.Duration]:{type:Jh.Float},[Wh.Tracks]:{type:Jh.Master},[Wh.Chapters]:{type:Jh.Master},[Wh.Cluster]:{type:Jh.Master},[Wh.Attachments]:{type:Jh.Master},[Wh.Tags]:{type:Jh.Master},[Wh.Cues]:{type:Jh.Master},[Wh.CuePoint]:{type:Jh.Master},[Wh.CueTime]:{type:Jh.UnsignedInteger},[Wh.CueTrackPositions]:{type:Jh.Master},[Wh.CueTrack]:{type:Jh.UnsignedInteger},[Wh.CueClusterPosition]:{type:Jh.UnsignedInteger},[Wh.CueRelativePosition]:{type:Jh.UnsignedInteger},[Wh.CueDuration]:{type:Jh.UnsignedInteger},[Wh.CueBlockNumber]:{type:Jh.UnsignedInteger},[Wh.CueCodecState]:{type:Jh.UnsignedInteger},[Wh.CueReference]:{type:Jh.Master},[Wh.CueRefTime]:{type:Jh.UnsignedInteger}},Xh=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=Zh(t,i),r=s in Kh,a=r?Kh[s].type:Jh.Binary,n=t.getUint8(i);let o=0;128&n?o=1:64&n?o=2:32&n?o=3:16&n?o=4:8&n?o=5:4&n?o=6:2&n?o=7:1&n&&(o=8);const d=new DataView(t.buffer,t.byteOffset+i+1,o-1),u=((n&255>>o)<<8*(o-1))+Zh(d),h=i+o;let c;return c=h+u>t.byteLength?new DataView(t.buffer,t.byteOffset+h):new DataView(t.buffer,t.byteOffset+h,u),{tag:r?s:'0x'+s.toString(16).toUpperCase(),type:a,value:c,valueSize:u}},Zh=(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},tc=(t,e)=>{switch(e){case Jh.SignedInteger:return t.getInt8(0);case Jh.UnsignedInteger:return Zh(t);case Jh.Float:return 4===t.byteLength?t.getFloat32(0):t.getFloat64(0);case Jh.String:return new TextDecoder('ascii').decode(t);case Jh.UTF8:return new TextDecoder('utf-8').decode(t);case Jh.Date:return new Date(Date.UTC(2001,0)+t.getInt8(0)).getTime();case Jh.Master:case Jh.Binary:return t;default:n(e)}},ec=(t,e)=>{let i=0;for(;i<t.byteLength;){const s=new DataView(t.buffer,t.byteOffset+i),r=Xh(s);if(!e(r))return;r.type===Jh.Master&&ec(r.value,e),i=r.value.byteOffset-t.byteOffset+r.valueSize}},ic=[Wh.Info,Wh.SeekHead,Wh.Tracks,Wh.Chapters,Wh.Cluster,Wh.Cues,Wh.Attachments,Wh.Tags],sc={validateData:t=>{if(t.getUint32(0)!==Wh.EBML)return!1;let e,i,s;const r=Xh(t);return ec(r.value,(({tag:t,type:r,value:a})=>(t===Wh.EBMLReadVersion?e=tc(a,r):t===Wh.DocType?i=tc(a,r):t===Wh.DocTypeReadVersion&&(s=tc(a,r)),!0))),(void 0===e||e<=1)&&void 0!==i&&'webm'===i&&(void 0===s||s<=2)},parseInit:t=>{let e,i,s,r,a,n,o=!1,d=!1,u=!1;return ec(t,(({tag:t,type:h,value:c,valueSize:l})=>{if(t===Wh.SeekID){const t=tc(c,h);n=Zh(t)}else t!==Wh.SeekPosition&&(n=void 0);return t===Wh.Segment?(e=c.byteOffset,i=c.byteOffset+l):t===Wh.Info?o=!0:t===Wh.SeekHead?d=!0:t===Wh.TimestampScale?s=tc(c,h):t===Wh.Duration?r=tc(c,h):t===Wh.SeekPosition&&n===Wh.Cues?a=tc(c,h):o&&d&&ic.includes(t)&&(u=!0),!u})),l(e,'Failed to parse webm Segment start'),l(i,'Failed to parse webm Segment end'),l(r,'Failed to parse webm Segment duration'),s=null!=s?s:1e6,{segmentStart:Math.round(e/1e9*s*1e3),segmentEnd:Math.round(i/1e9*s*1e3),timeScale:s,segmentDuration:Math.round(r/1e9*s*1e3),cuesSeekPosition:a}},getIndexRange:t=>{if(r(t.cuesSeekPosition))return;const e=t.segmentStart+t.cuesSeekPosition;return{from:e,to:e+1048576}},parseSegments:(t,e)=>{let i=!1,r=!1;const a=t=>s(t.time)&&s(t.position),n=[];let o;return ec(t,(({tag:t,type:e,value:s})=>{switch(t){case Wh.Cues:i=!0;break;case Wh.CuePoint:o&&a(o)&&n.push(o),o={};break;case Wh.CueTime:o&&(o.time=tc(s,e));break;case Wh.CueTrackPositions:break;case Wh.CueClusterPosition:o&&(o.position=tc(s,e));break;default:i&&ic.includes(t)&&(r=!0)}return!(i&&r)})),o&&a(o)&&n.push(o),n.map(((t,i)=>{const{time:s,position:r}=t,a=n[i+1];return{status:cs.NONE,time:{from:s,to:a?a.time:e.segmentDuration},byte:{from:e.segmentStart+r,to:a?e.segmentStart+a.position-1:e.segmentEnd-1}}}))}},rc=new TextDecoder('ascii'),ac={validateData:t=>'ftyp'===rc.decode(new DataView(t.buffer,t.byteOffset+4,4)),parseInit:()=>null,getIndexRange:()=>{},parseSegments:t=>{const e=(t=>{let e=0,i=t.getUint32(e);e+=4;const s=new DataView(t.buffer,t.byteOffset+e,4),r=rc.decode(s);e+=4,0===i?i=1/0:1===i&&(e+=8,i=1/0);const a=Math.min(i,t.byteLength)-e+1;return{id:r,size:i,contents:new DataView(t.buffer,t.byteOffset+e,a)}})(t),i=[];let s=0;const r=()=>{const t=e.contents.getUint32(s);return s+=4,t};if(0!==(4278190080&r()))throw new SyntaxError('Unsupported sidx version');r();const a=r(),n=r(),o=r(),d=255&r();let u=n/a*1e3,h=t.byteOffset+t.byteLength+o+1;for(let t=0;t<d;t++){const t=r(),e=t>>>31,s=t<<1>>>1,n=r();if(r(),0!==e)throw new Error('Unsupported multilevel sidx');const o=n/a*1e3;i.push({status:cs.NONE,time:{from:u,to:u+o},byte:{from:h,to:h+s-1}}),u+=o,h+=s}return i}};class nc{constructor(s,r,a,o,{fetcher:d,tuning:u}){switch(this.onLastSegment$=new t(!1),this.fullyBuffered$=new t(!1),this.playingRepresentation$=new t(void 0),this.error$=new e,this.gaps=[],this.subscription=new i,this.abortController=new Uo,this.allInitsLoaded=!1,this.bufferUpdateQueue=[],this.bufferUpdateQueueInProgress=!1,this.fetcher=d,this.tuning=u,this.container=a,a){case ls.MP4:this.containerParser=ac;break;case ls.WEBM:this.containerParser=sc;break;default:n(a)}this.initData=new Map,this.segments=new Map,this.representations=new Map(o.map((t=>[t.id,t]))),this.kind=s,this.mediaSource=r,this.sourceBuffer=null,this.segmentDownloadPromise=Promise.resolve()}startWith(t){return O(this,void 0,void 0,(function*(){const e=this.representations.get(t);l(e,`Cannot find representation ${t}`);const i=Math.ceil(1e3*e.bitrate/8*(this.tuning.extraInitSize/1e3)*1.1);this.playingRepresentationId=t,this.downloadingRepresentationId=t,this.sourceBuffer=this.mediaSource.addSourceBuffer(`${e.mime}; codecs="${e.codecs}"`),this.subscription.add(a(this.sourceBuffer,'updateEnd').subscribe((()=>this.checkEjectedSegments()),(t=>this.error$.next({id:'SegmentEjection',message:'Error when trying to clear segments ejecte by browser',thrown:t})))),this.subscription.add(a(this.sourceBuffer,'error').subscribe((t=>this.error$.next({id:'SourceBuffer',message:'SourceBuffer Error event fired',thrown:t}))));const s=yield this.fetcher.fetchRepresentation(e,this.containerParser,i).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!s)return!1;const{dataView:r,segments:n}=s,o=r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength-i);this.initData.set(t,o);const d=n.filter((t=>t.byte.from>=r.byteOffset&&t.byte.to<r.byteOffset+r.byteLength)),u=fs(d,-1),h=new DataView(r.buffer,r.byteOffset,d.length&&u?Math.min(u.byte.to-r.byteOffset+1,r.byteLength):r.byteLength-i);return yield this.appendDataToBuffer(h),this.segments.set(t,n.map((t=>Object.assign(Object.assign({},t),{status:t.byte.from>=r.byteOffset&&t.byte.to<r.byteOffset+r.byteLength?cs.FED:cs.NONE})))),this.maintain(0),!0}))}switchTo(t){var e;return O(this,void 0,void 0,(function*(){if(t===this.downloadingRepresentationId||t===this.switchingToRepresentationId)return;if(this.switchingToRepresentationId=t,!this.initData.has(t))if(this.loadAllInitsPromise)yield this.loadAllInitsPromise;else{const e=this.representations.get(t);l(e);const i=yield this.fetcher.fetchRepresentation(e,this.containerParser,0).catch((t=>this.error$.next({id:'LoadInit',message:'Failed to init Representation',thrown:t})));if(!i)return;const{dataView:s,segments:r}=i,a=s.buffer.slice(s.byteOffset,s.byteOffset+s.byteLength);this.initData.set(t,a),this.segments.set(t,r)}const i=this.initData.get(t);l(i,`No init buffer for ${t}`),l(this.sourceBuffer),this.switchingToRepresentationId=void 0,this.downloadingRepresentationId=t,this.abortController.abort(),this.abortController=new Uo,this.abortBuffer(),yield this.appendDataToBuffer(i,this.abortController.signal),s(this.playingRepresentationId)&&(null===(e=this.segments.get(this.playingRepresentationId))||void 0===e||e.forEach((t=>{t.status===cs.FED&&(t.status=cs.NONE)})))}))}maintain(t){return O(this,void 0,void 0,(function*(){if(r(this.downloadingRepresentationId)||r(this.playingRepresentationId)||r(this.sourceBuffer)||this.onLastSegment$.getValue())return;const e=this.representations.get(this.downloadingRepresentationId),i=this.segments.get(this.downloadingRepresentationId);l(e),l(i);const s=i.find((e=>t>=e.time.from&&t<e.time.to));let a=t;if(this.playingRepresentationId!==this.downloadingRepresentationId){const e=qs(this.sourceBuffer.buffered,t);a=t+Math.min(e,this.tuning.representationSwitchForwardBufferGap)}const n=this.selectForwardBufferSegments(i,a);n.length&&(yield this.loadSegments(n,e)),!this.allInitsLoaded&&!this.loadAllInitsPromise&&s&&s.status===cs.FED&&!n.length&&qs(this.sourceBuffer.buffered,t)>3e3&&this.loadAllInits().catch((t=>this.error$.next({id:'InitDownload',message:'Error when trying to load all inits',thrown:t})));const o=fs(i,-1);o&&o.status===cs.FED&&(this.fullyBuffered$.next(!0),s===o&&this.onLastSegment$.next(!0))}))}destroy(){this.initData.clear(),this.segments.clear(),this.representations.clear(),this.subscription.unsubscribe(),this.sourceBuffer&&'open'===this.mediaSource.readyState&&(this.abortBuffer(),this.mediaSource.removeSourceBuffer(this.sourceBuffer)),this.abortController.abort()}selectForwardBufferSegments(t,e){const i=t.findIndex((({status:t,time:{from:i,to:s}})=>t===cs.NONE&&(i>e||i<=e&&s>=e)&&s<=e+this.tuning.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===cs.NONE)r.push(i);else if([cs.DOWNLOADING,cs.DOWNLOADED,cs.FED].includes(i.status))break}return r}loadSegments(t,e){return O(this,void 0,void 0,(function*(){if(!t.length)return;const i=fs(t,0).byte.from,s=fs(t,-1).byte.to;for(const e of t)e.status=cs.DOWNLOADING;const{signal:r}=this.abortController,a=(t,i)=>{t.status=cs.DOWNLOADED,this.appendDataToBuffer(i,r).then((i=>{if(!i||r.aborted)t.status=cs.NONE;else if(this.playingRepresentationId=e.id,this.playingRepresentation$.next(this.playingRepresentationId),t.status=cs.FED,this.sourceBuffer){let i={representation:e.id,from:t.time.from,to:t.time.to};for(let e=0;e<this.sourceBuffer.buffered.length;e++){const s=1e3*this.sourceBuffer.buffered.start(e),r=1e3*this.sourceBuffer.buffered.end(e);if(!(r<=t.time.from||s>=t.time.to)){if(s<=t.time.from&&r>=t.time.to){i=void 0;break}r>t.time.from&&r<t.time.to&&(i.from=r),s<t.time.to&&s>t.time.from&&(i.to=s)}}i&&i.to>i.from&&this.gaps.push(i)}}))},n=(e,s)=>{for(const r of t)r.status===cs.DOWNLOADING&&r.byte.from-i>=0&&r.byte.to+1-i<=s&&a(r,new DataView(e.buffer,e.byteOffset+r.byte.from-i,r.byte.to+1-r.byte.from))};return this.segmentDownloadPromise=this.segmentDownloadPromise.then((()=>O(this,void 0,void 0,(function*(){if(r.aborted){for(const e of t)e.status===cs.DOWNLOADING&&(e.status=cs.NONE);return}const o=yield this.fetcher.fetchRange(e.url,i,s,{method:Gh.PARAM,onProgress:n,signal:r}),d=fs(t,-1),u=fs(this.segments.get(e.id),-1);if(!o)for(const e of t)e.status===cs.DOWNLOADING&&(e.status=cs.NONE);o&&!r.aborted&&d&&u&&d.status===cs.DOWNLOADING&&d===u&&a(d,new DataView(o,d.byte.from-i))})))).catch((t=>this.error$.next({id:'SegmentDownload',message:'Error when fetching segments',thrown:t}))),this.segmentDownloadPromise}))}loadAllInits(){return O(this,void 0,void 0,(function*(){return this.loadAllInitsPromise||(this.loadAllInitsPromise=Yh(Promise.all(Array.from(this.representations.entries()).map((([t,e])=>this.initData.has(t)?Promise.resolve():this.fetcher.fetchRepresentation(e,this.containerParser).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,r),this.segments.set(t,s)}))))).then((()=>{this.allInitsLoaded=!0})),(()=>{this.loadAllInitsPromise=null}))),this.loadAllInitsPromise}))}appendDataToBuffer(t,e){return O(this,void 0,void 0,(function*(){if(l(this.sourceBuffer),e&&e.aborted)return!1;if(!this.mediaSource.sourceBuffers.length||!Array.from(this.mediaSource.sourceBuffers).includes(this.sourceBuffer))return!1;const i=()=>{if(this.bufferUpdateQueueInProgress)return;this.bufferUpdateQueueInProgress=!0;const t=this.bufferUpdateQueue.shift();if(!t)return void(this.bufferUpdateQueueInProgress=!1);const{data:e,callback:s}=t;if(!this.sourceBuffer)return this.bufferUpdateQueueInProgress=!1,void s(!1);try{this.sourceBuffer.appendBuffer(e)}catch(t){return this.error$.next({id:'AppendBuffer',message:'Error appending data to buffer',thrown:t}),this.bufferUpdateQueueInProgress=!1,void s(!1)}nc.waitForBufferUpdate(this.sourceBuffer).then((()=>{this.bufferUpdateQueueInProgress=!1,s(!0),i()}))};return new Promise((e=>{this.bufferUpdateQueue.push({data:t,callback:e}),this.sourceBuffer?this.sourceBuffer.updating?nc.waitForBufferUpdate(this.sourceBuffer).then(i):i():e(!1)}))}))}abortBuffer(){if(this.sourceBuffer&&'open'===this.mediaSource.readyState)try{this.sourceBuffer.abort()}catch(t){this.error$.next({id:'SourceBufferAbort',message:'SourceBuffer.abort() threw',thrown:t})}}checkEjectedSegments(){if(r(this.sourceBuffer)||r(this.playingRepresentationId))return;const t=this.segments.get(this.playingRepresentationId);l(t);const e=[];for(let t=0;t<this.sourceBuffer.buffered.length;t++){const i=1e3*this.sourceBuffer.buffered.start(t),s=this.sourceBuffer.buffered.end(t),r=1e3*(s%1>.9?Math.round(s):s);e.push({from:i,to:r})}for(const i of t){const t=e.some((t=>t.from<=i.time.from&&t.to>=i.time.to));i.status!==cs.FED||t||(i.status=cs.NONE)}}static waitForBufferUpdate(t){return O(this,void 0,void 0,(function*(){return new Promise((e=>t?t.addEventListener('updateend',(()=>e())):e()))}))}}const oc=t=>{if(t.includes('/')){const e=t.split('/');return parseInt(e[0])/parseInt(e[1])}return parseFloat(t)},dc=['timeupdate','progress','play','seeked','stalled'];var uc,hc;!function(t){t.NONE='none',t.MANIFEST_LOADED='manifest_loaded',t.REPRESENTATION_SELECTED='representation_selected'}(uc||(uc={}));class cc{constructor(s){this.element=null,this.source=null,this.manifest=null,this.subscription=new i,this.state$=new js(uc.NONE),this.currentVideoRepresentation$=new t(void 0),this.error$=new e,this.lastConnectionType$=new t(void 0),this.lastConnectionReused$=new t(void 0),this.lastRequestFirstBytes$=new t(void 0),this.forceEnded$=new e,this.gapWatchdogStarted=!1,this.tick=()=>{if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime;this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),!this.videoBufferManager.gaps.length&&!this.audioBufferManager.gaps.length||this.gapWatchdogStarted||(this.gapWatchdogStarted=!0,this.gapWatchdogSubscription=g(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=s.throughputEstimator,this.tuning=s.tuning,this.fetcher=new zh({throughputEstimator:this.throughputEstimator})}initManifest(t,e){return O(this,void 0,void 0,(function*(){this.element=t,this.state$.startTransitionTo(uc.MANIFEST_LOADED);const i=yield this.fetcher.fetchManifest(e);let s;try{s=((t,e)=>{var i,s,r,a,n,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$,P;const A={video:[],audio:[],text:[]},k=(new DOMParser).parseFromString(t,'application/xml').children[0],_=k.getElementsByTagName('Period')[0].children;let D=0;const R=null!==(s=null===(i=k.getAttribute('profiles'))||void 0===i?void 0:i.split(','))&&void 0!==s?s:[],I=R.includes(hs.WEBM_AS_IN_FFMPEG)||R.includes(hs.WEBM_AS_IN_SPEC)?ls.WEBM:ls.MP4;for(const t of _){const i=t.getAttribute('mimeType'),s=t.getAttribute('codecs'),k=null!==(r=t.getAttribute('contentType'))&&void 0!==r?r:null==i?void 0:i.split('/')[0],_=null!==(n=null===(a=t.getAttribute('profiles'))||void 0===a?void 0:a.split(','))&&void 0!==n?n:[],I=t.querySelectorAll('Representation');for(const r of I){const a=null!==(o=r.getAttribute('mimeType'))&&void 0!==o?o:i,n=null!==(u=null!==(d=r.getAttribute('codecs'))&&void 0!==d?d:s)&&void 0!==u?u:'',I=null!==(c=null!==(h=r.getAttribute('contentType'))&&void 0!==h?h:null==a?void 0:a.split('/')[0])&&void 0!==c?c:k,L=null!==(p=null===(l=t.getAttribute('profiles'))||void 0===l?void 0:l.split(','))&&void 0!==p?p:[],x=parseInt(null!==(f=r.getAttribute('width'))&&void 0!==f?f:'',10),O=parseInt(null!==(m=r.getAttribute('height'))&&void 0!==m?m:'',10),C=parseInt(null!==(v=r.getAttribute('bandwidth'))&&void 0!==v?v:'',10)/1e3,N=null!==(g=r.getAttribute('frameRate'))&&void 0!==g?g:'',M=null!==(S=r.getAttribute('quality'))&&void 0!==S?S:void 0,B=N?oc(N):void 0,U=`${null!==(b=r.getAttribute('id'))&&void 0!==b?b:(D++).toString(10)}@${'video'===I?`${O}p`:'audio'===I?`${C}Kbps`:n}`,V=null!==(E=null===(T=null===(y=r.querySelector('BaseURL'))||void 0===y?void 0:y.textContent)||void 0===T?void 0:T.trim())&&void 0!==E?E:'',F=new URL(V,e).toString(),H=[...R,..._,...L],q=null!==($=null===(w=r.querySelector('SegmentBase Initialization'))||void 0===w?void 0:w.getAttribute('range'))&&void 0!==$?$:'',[G,Y]=q.split('-').map((t=>parseInt(t,10))),j={from:G,to:Y},z=null===(P=r.querySelector('SegmentBase'))||void 0===P?void 0:P.getAttribute('indexRange'),[Q,W]=z?z.split('-').map((t=>parseInt(t,10))):[],J=z?{from:Q,to:W}:void 0;if(!I||!a)continue;const K={video:us.VIDEO,audio:us.AUDIO,text:us.TEXT}[I];K&&A[K].push({id:U,kind:K,profiles:H,initRange:j,indexRange:J,bitrate:C,mime:a,codecs:n,width:x,height:O,fps:B,quality:M,url:F})}}return{container:I,representations:A}})(null!=i?i:'',e)}catch(t){this.error$.next({id:'ManifestParsing',message:'Failed to parse MPD manifest',thrown:t})}l(s);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:Po(Object.entries(s.representations).map((([t,e])=>[t,e.filter(r)])))}),this.manifest.representations.video.length?this.state$.setState(uc.MANIFEST_LOADED):this.error$.next({id:'NoRepresentations',message:'No playable video representations'}),this.manifest}))}initRepresentations(t,e){return O(this,void 0,void 0,(function*(){l(this.manifest),l(this.element),this.state$.startTransitionTo(uc.REPRESENTATION_SELECTED),this.source=new MediaSource,this.element.src=URL.createObjectURL(this.source);const i={fetcher:this.fetcher,tuning:this.tuning.dash};this.videoBufferManager=new nc(us.VIDEO,this.source,this.manifest.container,this.manifest.representations.video,i),this.audioBufferManager=new nc(us.AUDIO,this.source,this.manifest.container,this.manifest.representations.audio,i),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$)),this.subscription.add(o(this.forceEnded$,o(this.videoBufferManager.onLastSegment$,this.audioBufferManager.onLastSegment$,this.videoBufferManager.fullyBuffered$,this.audioBufferManager.fullyBuffered$).pipe(S((()=>!(!this.videoBufferManager||!this.audioBufferManager)&&[this.videoBufferManager.fullyBuffered$.getValue(),this.audioBufferManager.fullyBuffered$.getValue()].every((t=>t))&&[this.videoBufferManager.onLastSegment$.getValue(),this.audioBufferManager.onLastSegment$.getValue()].some((t=>t)))))).subscribe((()=>{var t,e;if('open'===(null===(t=this.source)||void 0===t?void 0:t.readyState))try{null===(e=this.source)||void 0===e||e.endOfStream()}catch(t){this.error$.next({id:'EndOfStream',message:'Failed to end MediaSource stream',thrown:t})}}))),this.subscription.add(o(this.videoBufferManager.error$,this.audioBufferManager.error$).subscribe(this.error$)),this.subscription.add(this.videoBufferManager.playingRepresentation$.subscribe(this.currentVideoRepresentation$)),'open'!==this.source.readyState&&(yield new Promise((t=>{var e;return null===(e=this.source)||void 0===e?void 0:e.addEventListener('sourceopen',t)})));(yield Promise.all([this.videoBufferManager.startWith(t),this.audioBufferManager.startWith(e)])).some((t=>!t))||(this.state$.setState(uc.REPRESENTATION_SELECTED),l(this.element),this.subscription.add(o(...dc.map((t=>a(this.element,t))),a(window,'online')).subscribe(this.tick,(t=>{this.error$.next({id:'DashVKPlayer',message:'Internal logic error',thrown:t})}))),this.subscription.add(a(this.element,'progress').subscribe((()=>{this.element&&2===this.element.readyState&&!this.element.seeking&&(this.element.currentTime=this.element.currentTime)}))),this.subscription.add(a(this.element,'waiting').subscribe((()=>{if(this.element&&2===this.element.readyState&&!this.element.seeking)for(let t=0;t<this.element.buffered.length;t++){if(this.element.buffered.start(t)<=this.element.currentTime&&this.element.buffered.end(t)>this.element.currentTime){this.element.currentTime=this.element.currentTime;break}}}))),this.tick())}))}switchRepresentation(t,e){return O(this,void 0,void 0,(function*(){const i={[us.VIDEO]:this.videoBufferManager,[us.AUDIO]:this.audioBufferManager,[us.TEXT]:null}[t];return l(i),i.switchTo(e)}))}seek(t){l(this.element),l(this.videoBufferManager),l(this.audioBufferManager),this.videoBufferManager.maintain(t),this.audioBufferManager.maintain(t),this.element.currentTime=t/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.state$.setState(uc.NONE)}destroy(){this.subscription.unsubscribe(),this.fetcher.destroy(),this.stop(),this.source=null}jumGap(){if(!this.element||!this.videoBufferManager||!this.audioBufferManager)return;const t=1e3*this.element.currentTime;for(const e of[this.videoBufferManager,this.audioBufferManager])for(const i of e.gaps)if(i.from<=t&&i.to>t&&e.playingRepresentation$.getValue()===i.representation){if(1e3*this.element.duration-i.to<this.tuning.endGapTolerance)return this.forceEnded$.next(),this.gapWatchdogSubscription.unsubscribe(),void(this.gapWatchdogStarted=!1);this.element.currentTime=i.to/1e3;break}}}!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(hc||(hc={}));const lc=({id:t,width:e,height:i,bitrate:s,fps:r,quality:a})=>{var n;const o=null!==(n=a?_s(a):void 0)&&void 0!==n?n:Os({width:e,height:i});return o&&{id:t,quality:o,bitrate:s,size:{width:e,height:i},fps:r}},pc=(t,e,i)=>{var s;const r=Array.from(e).sort(((t,e)=>e.bitrate-t.bitrate)).indexOf(i);return null!==(s=fs(t,Math.round(t.length*r/e.length)))&&void 0!==s?s:fs(t,-1)};class fc{constructor(e){this.subscription=new i,this.videoState=new js(hc.STOPPED),this.elementSize$=new t(void 0),this.textTracksManager=new ys,this.videoTracks=[],this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(this.videoState.getTransition())return;const a=null==r?void 0:r.to;if((null==i?void 0:i.to)!==P.PAUSED&&s(a)&&t!==hc.STOPPED&&e!==P.STOPPED&&this.seek(a),e!==P.STOPPED){if(t===hc.STOPPED)return this.videoState.startTransitionTo(hc.READY),void this.prepare();switch(t){case hc.READY:return void(e===P.PAUSED?(this.videoState.setState(hc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(hc.PLAYING),this.playIfAllowed()));case hc.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(hc.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Ds(this.params.desiredState.playbackState,P.PLAYING));case hc.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(hc.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Ds(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}}else t!==hc.STOPPED&&(this.videoState.startTransitionTo(hc.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(hc.STOPPED),Ds(this.params.desiredState.playbackState,P.STOPPED,!0))},this.params=e,this.video=Ts(this.params.container),this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Gs(this.params.source.url)),this.params.output.isLive$.next(!1),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.player=new cc({throughputEstimator:this.params.dependencies.throughputEstimator,tuning:this.params.tuning}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=As(this.video),r=e=>{t.error$.next({id:'DashVKProvider',message:'DashVKProvider internal logic error',thrown:e})},n=(t,e)=>this.subscription.add(t.subscribe(e,r));n(i.timeUpdate$,t.position$),n(i.durationChange$,t.duration$),n(i.ended$,t.endedEvent$),n(i.looped$,t.loopedEvent$),n(i.error$,t.error$),n(i.isBuffering$,t.isBuffering$),n(i.currentBuffer$,t.currentBuffer$),n(i.firstFrame$,t.firstFrameEvent$),n(this.player.error$,t.error$),n(this.player.lastConnectionType$,t.httpConnectionType$),n(this.player.lastConnectionReused$,t.httpConnectionReused$),n(this.player.lastRequestFirstBytes$.pipe(S(s),f()),t.firstBytesEvent$),this.subscription.add(i.seeked$.subscribe(t.seekedEvent$,r)),this.subscription.add(gs(this.video,e.isLooped,r)),this.subscription.add(Ss(this.video,e.volume,i.volumeState$,r)),this.subscription.add(i.volumeState$.subscribe(this.params.output.volume$,r)),n(Ys(this.video),this.elementSize$),this.subscription.add(i.playing$.subscribe((()=>{this.videoState.setState(hc.PLAYING),Ds(e.playbackState,P.PLAYING)}),r)).add(i.pause$.subscribe((()=>{this.videoState.setState(hc.PAUSED),Ds(e.playbackState,P.PAUSED)}),r)).add(i.canplay$.subscribe((()=>{this.videoState.getState()===hc.PLAYING&&this.playIfAllowed()}),r)),this.subscription.add(this.player.state$.stateChangeEnded$.pipe(S((({to:t})=>t===uc.REPRESENTATION_SELECTED))).subscribe((()=>{this.videoState.setState(hc.READY)}))),this.subscription.add(o(this.player.state$.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.transitionStarted$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,e.autoVideoTrackLimits.stateChangeEnded$,this.elementSize$,a(this.video,'progress')).subscribe((()=>{var t,i,s;const r=this.player.state$.getState(),a=this.player.state$.getTransition();if(r===uc.NONE||!this.videoTracks.length)return;const n=r===uc.MANIFEST_LOADED&&!a,o=e.autoVideoTrackSwitching.getState(),d=e.videoTrack.getState(),u=null===(t=this.videoTracks.find((({track:{id:t}})=>t===d)))||void 0===t?void 0:t.track;e.autoVideoTrackSwitching.getTransition()&&e.autoVideoTrackSwitching.setState(o);const h=qs(this.video.buffered,1e3*this.video.currentTime),c=Math.min(h/Math.min(this.params.tuning.dash.forwardBufferTarget,(1e3*this.video.duration||1/0)-1e3*this.video.currentTime),1),p=Hs(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState(),forwardBufferHealth:c}),f=o?null!=p?p:u:null!=u?u:p;if(n){const t=f&&(null===(i=this.videoTracks.find((({track:t})=>t===f)))||void 0===i?void 0:i.representation);l(t);const e=pc(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);l(e),this.player.initRepresentations(t.id,e.id)}else{const t=f&&(null===(s=this.videoTracks.find((({track:t})=>t===f)))||void 0===s?void 0:s.representation);if(t){const e=pc(this.audioRepresentations,this.videoTracks.map((({representation:t})=>t)),t);this.player.switchRepresentation(us.VIDEO,t.id),e&&this.player.switchRepresentation(us.AUDIO,e.id)}}}),r)),this.subscription.add(this.player.currentVideoRepresentation$.pipe(c(),u((t=>{var e;return t&&(null===(e=this.videoTracks.find((({representation:{id:e}})=>e===t)))||void 0===e?void 0:e.track)}))).subscribe(t.currentVideoTrack$,r)),this.textTracksManager.connect(this.video,e,t);const d=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(d.subscribe(this.syncPlayback,r))}prepare(){return O(this,void 0,void 0,(function*(){const t=yield this.player.initManifest(this.video,this.params.source.url);this.videoTracks=[];for(const e of t.representations.video){const t=lc(e);t&&this.videoTracks.push({track:t,representation:e})}this.audioRepresentations=Array.from(t.representations.audio).sort(((t,e)=>e.bitrate-t.bitrate)),this.params.output.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t)))}))}seek(t){this.params.output.willSeekEvent$.next(),this.player.seek(1e3*t)}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.player.destroy()}playIfAllowed(){ms(this.video).then((t=>{t||(this.videoState.setState(hc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var mc;!function(t){t[t.OFFSET_P=0]='OFFSET_P',t[t.PLAYBACK_SHIFT=1]='PLAYBACK_SHIFT'}(mc||(mc={}));var vc=(t,e=0,i=mc.OFFSET_P)=>{switch(i){case mc.OFFSET_P:return t.replace('_offset_p',0===e?'':'_'+e.toFixed(0));case mc.PLAYBACK_SHIFT:{if(0===e)return t;const i=new URL(t);return i.searchParams.append('playback_shift',e.toFixed(0)),i.toString()}default:n(i)}return t};var gc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(gc||(gc={}));class Sc{constructor(t){this.subscription=new i,this.loadMediaTimeoutSubscription=new i,this.videoState=new js(gc.STOPPED),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; desiredPlaybackStateTransition: ${this.params.desiredState.playbackState.getTransition()}; seekPositionTransition: ${JSON.stringify(a)};`}),i===P.STOPPED)return void(t!==gc.STOPPED&&(this.videoState.startTransitionTo(gc.STOPPED),this.stop()));if(e)return;const o=null==a?void 0:a.to;if((null==r?void 0:r.to)!==P.PAUSED&&s(o)&&t!==gc.STOPPED)this.seek(o);else switch(i){case P.PLAYING:switch(t){case gc.PLAYING:break;case gc.PAUSED:case gc.READY:this.videoState.startTransitionTo(gc.PLAYING),this.params.connection.remotePlayerController.playOrPause();break;case gc.STOPPED:this.videoState.startTransitionTo(gc.READY),this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case gc.PLAYING:this.videoState.startTransitionTo(gc.PAUSED),this.params.connection.remotePlayerController.playOrPause();break;case gc.PAUSED:break;case gc.READY:this.videoState.startTransitionTo(gc.PAUSED),this.videoState.setState(gc.PAUSED);break;case gc.STOPPED:this.videoState.startTransitionTo(gc.READY),this.prepare();break;default:n(t)}break;default:n(i)}},this.params=t,this.log=this.params.dependencies.logger.createComponentLog('ChromecastProvider'),this.log({message:`constructor, format: ${t.format}`}),this.params.output.isLive$.next((t=>{switch(t){case A.MPEG:case A.DASH:case A.DASH_SEP:case A.DASH_SEP_VK:case A.DASH_ONDEMAND:case A.DASH_WEBM:case A.DASH_WEBM_VK:case A.HLS:case A.HLS_JS:case A.HLS_ONDEMAND:return!1;case A.HLS_LIVE:case A.DASH_LIVE:case A.DASH_LIVE_WEBM:return!0;default:return n(t)}})(t.format)),this.handleRemoteVolumeChange({volume:this.params.connection.remotePlayer.volumeLevel,muted:this.params.connection.remotePlayer.isMuted});const e=this.params.connection.session.getMediaSession();e&&this.restoreSession(e),this.subscribe()}destroy(){this.log({message:'[destroy]'}),this.subscription.unsubscribe()}subscribe(){this.subscription.add(this.loadMediaTimeoutSubscription);const t=new i;this.subscription.add(t),this.subscription.add(o(this.videoState.stateChangeStarted$.pipe(u((t=>`stateChangeStarted$ ${JSON.stringify(t)}`))),this.videoState.stateChangeEnded$.pipe(u((t=>`stateChangeEnded$ ${JSON.stringify(t)}`)))).subscribe((t=>this.log({message:`[videoState] ${t}`}))));const d=(t,e)=>this.subscription.add(t.subscribe(e));if(this.params.output.isLive$.getValue())this.params.output.position$.next(0),this.params.output.duration$.next(0);else{const i=new e;t.add(i.pipe(m(500)).subscribe((()=>{this.params.output.seekedEvent$.next()})));let n=NaN;t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.CURRENT_TIME_CHANGED).subscribe((t=>{this.logRemoteEvent(t);const e=t.value;this.params.output.position$.next(e);const a=this.params.desiredState.seekPosition.getTransition();(s(a)&&r(a.to)||Math.abs(e-n)>5)&&i.next(e),n=e}))),t.add(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.DURATION_CHANGED).subscribe((t=>{this.logRemoteEvent(t),this.params.output.duration$.next(t.value)})))}d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MEDIA_LOADED_CHANGED),(e=>{this.logRemoteEvent(e),e.value?this.handleRemoteReady():(this.handleRemoteStop(),t.unsubscribe())})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_PAUSED_CHANGED),(t=>{this.logRemoteEvent(t),t.value?this.handleRemotePause():this.handleRemotePlay()})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.PLAYER_STATE_CHANGED),(t=>{this.logRemoteEvent(t);const{remotePlayer:e}=this.params.connection,i=t.value,s=this.params.output.isBuffering$.getValue(),r=i===chrome.cast.media.PlayerState.BUFFERING;switch(s!==r&&this.params.output.isBuffering$.next(r),i){case chrome.cast.media.PlayerState.IDLE:!this.params.output.isLive$.getValue()&&e.duration-e.currentTime<5&&this.params.output.endedEvent$.next(),this.handleRemoteStop(),Ds(this.params.desiredState.playbackState,P.STOPPED);break;case chrome.cast.media.PlayerState.PAUSED:this.handleRemotePause();break;case chrome.cast.media.PlayerState.PLAYING:this.handleRemotePlay();break;case chrome.cast.media.PlayerState.BUFFERING:break;default:n(i)}})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.VOLUME_LEVEL_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({volume:t.value})})),d(a(this.params.connection.remotePlayerController,cast.framework.RemotePlayerEventType.IS_MUTED_CHANGED),(t=>{this.logRemoteEvent(t),this.handleRemoteVolumeChange({muted:t.value})}));d(o(this.params.desiredState.playbackState.stateChangeStarted$,this.params.desiredState.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(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(gc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED)):(this.videoState.setState(gc.PLAYING),Ds(this.params.desiredState.playbackState,P.PLAYING));const t=this.params.output.isLive$.getValue();this.params.output.duration$.next(t?0:e.duration),this.params.output.position$.next(t?0:e.currentTime),this.params.desiredState.seekPosition.setState(void 0)}}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)!==gc.PAUSED&&t!==gc.PLAYING||(this.videoState.setState(gc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED))}handleRemotePlay(){const t=this.videoState.getState(),e=this.videoState.getTransition();(null==e?void 0:e.to)!==gc.PLAYING&&t!==gc.PAUSED||(this.videoState.setState(gc.PLAYING),Ds(this.params.desiredState.playbackState,P.PLAYING))}handleRemoteReady(){const t=this.videoState.getTransition();(null==t?void 0:t.to)===gc.READY&&this.videoState.setState(gc.READY)}handleRemoteStop(){this.videoState.getState()!==gc.STOPPED&&this.videoState.setState(gc.STOPPED)}handleRemoteVolumeChange(t){var e,i;const s=this.params.output.volume$.getValue(),r={volume:null!==(e=t.volume)&&void 0!==e?e:s.volume,muted:null!==(i=t.muted)&&void 0!==i?i:s.muted};r.volume===s.volume&&r.muted==r.muted||this.params.output.volume$.next(r)}seek(t){this.params.output.willSeekEvent$.next();const{remotePlayer:e,remotePlayerController:i}=this.params.connection;e.currentTime=t,i.seek()}stop(){const{remotePlayerController:t}=this.params.connection;t.stop()}createMediaInfo(t){var e;const i=this.params.source;let r,a,o;switch(t){case A.MPEG:{const e=i[t];l(e);const s=Object.keys(e).sort(((t,e)=>t===e?0:t===ks.INVARIANT?1:e===ks.INVARIANT?-1:Ls(t,e)?1:-1))[0];l(s);const n=e[s];l(n),r=n,a='video/mp4',o=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS:case A.HLS_ONDEMAND:{const e=i[t];l(e),r=e.url,a='application/x-mpegurl',o=chrome.cast.media.StreamType.BUFFERED;break}case A.DASH_SEP:case A.DASH_SEP_VK:case A.DASH_ONDEMAND:case A.DASH_WEBM_VK:case A.DASH_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.BUFFERED;break}case A.HLS_LIVE:{const e=i[t];l(e),r=vc(e.url),a='application/x-mpegurl',o=chrome.cast.media.StreamType.LIVE;break}case A.DASH_LIVE_WEBM:{const e=i[t];l(e),r=e.url,a='application/dash+xml',o=chrome.cast.media.StreamType.LIVE;break}case A.HLS_JS:case A.DASH:case A.DASH_LIVE:{const t='Unsupported format for Chromecast',e=new Error(t);throw this.params.output.error$.next({id:'ChromecastProvider.createMediaInfo()',message:t,thrown:e}),e}default:return n(t)}const d=new chrome.cast.media.MediaInfo(null!==(e=this.params.meta.videoId)&&void 0!==e?e:r,a);d.contentUrl=r,d.streamType=o,d.metadata=new chrome.cast.media.GenericMediaMetadata;const{title:u,subtitle:h}=this.params.meta;return s(u)&&(d.metadata.title=u),s(h)&&(d.metadata.subtitle=h),d}createLoadRequest(t){var e;const i=new chrome.cast.media.LoadRequest(t);i.autoplay=!1;const s=this.params.desiredState.seekPosition.getTransition();return i.currentTime=s?this.params.output.isLive$.getValue()?0:null!==(e=s.to)&&void 0!==e?e:0:0,i}loadMedia(t){const e=this.params.connection.session.loadMedia(t),i=new Promise(((t,e)=>{this.loadMediaTimeoutSubscription.add(b(7e3).subscribe((()=>e('timeout(7000)'))))}));Yh(Promise.race([e,i]).then((()=>{this.log({message:`[loadMedia] completed, format: ${this.params.format}`});const t=this.params.desiredState.seekPosition;t.getTransition()&&t.setState(void 0),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)}`})}}var bc;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(bc||(bc={}));class yc{constructor(t){this.subscription=new i,this.videoState=new js(bc.STOPPED),this.trackUrls={},this.textTracksManager=new ys,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition();if(e===P.STOPPED)return void(t!==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),Ds(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const r=this.params.desiredState.videoTrack.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(t===bc.STOPPED)return this.videoState.startTransitionTo(bc.READY),void this.prepare();if(r){const{currentTime:t}=this.video;return this.prepare(),void(a||this.params.desiredState.seekPosition.startTransitionTo(t))}const o=null==a?void 0:a.to;switch((null==i?void 0:i.to)!==P.PAUSED&&s(o)&&this.seek(o),t){case bc.READY:return void(e===P.PAUSED?(this.videoState.setState(bc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(bc.PLAYING),this.playIfAllowed()));case bc.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(bc.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Ds(this.params.desiredState.playbackState,P.PLAYING));case bc.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(bc.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Ds(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}},this.params=t,this.video=Ts(t.container),this.params.output.element$.next(this.video),Object.entries(this.params.source).forEach((([t,e],i)=>{const s=i.toString(10);this.trackUrls[s]={track:{quality:t,id:s},url:e}})),this.params.output.availableVideoTracks$.next(Object.values(this.trackUrls).map((({track:t})=>t))),this.params.output.isLive$.next(!1),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'MpegProvider',message:'MpegProvider internal logic error',thrown:e})},r=As(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.firstBytes$,t.firstBytesEvent$),a(r.firstFrame$,t.firstFrameEvent$),a(r.seeked$,t.seekedEvent$),this.subscription.add(gs(this.video,e.isLooped,i)),this.subscription.add(Ss(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(bc.PLAYING),Ds(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(bc.PAUSED),Ds(e.playbackState,P.PAUSED)}),i)).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);const e=this.params.desiredState.videoTrack.getTransition();e&&s(e.to)&&(this.params.desiredState.videoTrack.setState(e.to),this.params.output.currentVideoTrack$.next(this.trackUrls[e.to].track)),this.videoState.getState()===bc.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(e.autoVideoTrackSwitching.stateChangeStarted$.subscribe((()=>e.autoVideoTrackSwitching.setState(!1)),i)),this.textTracksManager.connect(this.video,e,t);const n=o(e.playbackState.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.trackUrls={},this.video.remove(),this.params.output.element$.next(void 0)}prepare(){var t,e;const i=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState();l(i,'MpegProvider: track is not selected');const{url:s}=this.trackUrls[i];l(s,`MpegProvider: No url for ${i}`),this.video.setAttribute('src',s),this.video.load(),this.params.output.hostname$.next(Gs(s))}playIfAllowed(){ms(this.video).then((t=>{t||(this.videoState.setState(bc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}class Tc{constructor(t,e=[],i,s,r,a){this._failoverIndex=0,this._failoverCount=0,this._xhr=null,this._retryTimeout=0,this._url=t,this._failoverHosts=e,this._completeCb=i,this._progressCb=s,this._headersCb=r,this._errorCb=a,this._request()}_request(){this._xhr=new XMLHttpRequest,this._xhr.open('GET',this._url,!0),this._xhr.overrideMimeType('text/plain; charset=x-user-defined');let t=!1;this._xhr.onreadystatechange=()=>{var e,i,s,r,a,n,o,d;if(l(this._xhr),(null===(e=this._xhr)||void 0===e?void 0:e.status)>=400)return null===(i=this._errorCb)||void 0===i||i.call(this,`Http${null===(s=this._xhr)||void 0===s?void 0:s.status}`,`XHR response code ${null===(r=this._xhr)||void 0===r?void 0:r.status}`),void this.abort();if(4!==this._xhr.readyState||0!==this._xhr.status)try{if(this._xhr.readyState>=2&&!t){t=!0;const e=Po(this._xhr.getAllResponseHeaders().trim().split(/[\n\r]+/).map((t=>t.split(':').map((t=>t.trim())))));null===(a=this._headersCb)||void 0===a||a.call(this,new Headers(e))}else 4===this._xhr.readyState?null===(n=this._completeCb)||void 0===n||n.call(this,this._xhr.response):3===this._xhr.readyState&&(null===(o=this._progressCb)||void 0===o||o.call(this,this._xhr.response))}catch(t){throw null===(d=this._errorCb)||void 0===d||d.call(this,'XHR2CallbackError',`xhr2 callback threw ${String(t)}`,t),t}},this._xhr.onerror=()=>{var t;null===(t=this._xhr)||void 0===t||t.abort(),this._retryTimeout=window.setTimeout((()=>{var t;if(this._xhr)if(++this._failoverCount>=30)this._xhr=null,null===(t=this._errorCb)||void 0===t||t.call(this,'XHR2Failover','XHR failed, retrying failover host');else{let t;this._failoverIndex>=this._failoverHosts.length?(t=this._url,this._failoverIndex=0):(t=this._url.replace((t=>{const e=document.createElement('a');return e.href=t,e.host})(this._url),this._failoverHosts[this._failoverIndex]),this._failoverIndex++),this._xhr.open('GET',t,!0),this._xhr.send(null)}}),500)},this._xhr.send(null)}abort(){window.clearTimeout(this._retryTimeout),this._completeCb=this._progressCb=this._errorCb=void 0,this._xhr&&(this._xhr.abort(),this._xhr=null)}}class Ec{constructor(t){this._maxBufferDuration=Number.POSITIVE_INFINITY,this._isFull=!1,this._params=t,this._mediaSource=t.mediaSource,this._sourceBuffer=t.sourceBuffer,this._onDashCallback=t.onDashCallback}_appendBuffer(t,e){try{this._isFull=!1;(this._sourceBuffer.appendBuffer||this._sourceBuffer.append).bind(this._sourceBuffer)(t),null==e||e()}catch(t){if('QuotaExceededError'!==t.name)throw this._params.onError('AppendBuffer','Unknown Buffer error',t),t;{this._isFull=!0;const t=this._sourceBuffer.buffered;let e=0;for(let i=0,s=t.length;i<s;i++)e+=t.end(i)-t.start(i);e&&(this._maxBufferDuration=Math.round(e))}}}getMaxBufferDuration(){return this._maxBufferDuration}isFull(){return this._isFull}load(t,e,i,s,r,a,n){this.abort((()=>{let o=0;const d=Date.now();let u=0,h=0,c=0;const l=t=>{s(Ec._str2ua(t.substr(o))),o=t.length};this._lastXhr=new Tc(t.baseURL+'&bytes='+e+'-'+i,t.failoverHosts,(t=>{this._lastXhr=void 0,l(t);const e=Date.now()-d;this._params.onBandwidthChange({size:t.length,duration:e,speed:8*t.length/(e/1e3)}),this._onDashCallback('loading',{size:t.length,done:!0}),null==r||r()}),(t=>{if(t.length-o>n&&l(t),0===h)return void(h=Date.now());c=t.length-u;const e=Date.now()-h;c>=102400&&e>=1e3&&(this._params.onBandwidthChange({size:c,duration:e,speed:8*c/(e/1e3)}),c=0,u=t.length,h=Date.now()),this._onDashCallback('loading',{size:t.length,done:!1})}),a,((t,e,i)=>this._params.onError(t,e,i)))}))}abort(t){var e;null===(e=this._lastXhr)||void 0===e||e.abort(),this._lastXhr=void 0,this._sbUpdatingStop(this._lastStreamUpdatingCallback),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{this._appendPromiseUint8Array&&(this._appendBuffer(this._appendPromiseUint8Array),this._appendPromiseUint8Array=void 0),this._lastStreamUpdatingCallback=this._sbUpdatingWatch((()=>{'open'===this._mediaSource.readyState&&this._sourceBuffer.abort(),null==t||t()}))}))}_sbUpdatingWatch(t){if(this._sourceBuffer.updating){const e=()=>{try{this._sbUpdatingStop(e),this._sbUpdatingWatch(t)}catch(t){throw this._params.onError('SourceBuffer','Source Buffer update error',t),t}};return this._sourceBuffer.addEventListener('updateend',e,!1),e}t()}_sbUpdatingStop(t){t&&this._sourceBuffer.removeEventListener('updateend',t,!1)}append(t,e){this._appendPromiseUint8Array?this._appendPromiseUint8Array=Ec._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 wc{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){new Tc(t,e,(i=>{this.attachManifest(i,e,(t=>{const e=document.createElement('a');return e.href=t,e.origin})(t))}),void 0,(t=>{this._params.onResponseHeaders(t)}),((t,e,i)=>this._params.onError(t,e,i)))}attachManifest(t,e,i){const s=(new DOMParser).parseFromString(t,'text/xml').documentElement,r=(t,e)=>{const i=t.attributes.getNamedItem(e);return i?i.value:null};this._duration=this._parseDurationFromISO8601(String(r(s,'mediaPresentationDuration')));const a=[],n=[];Array.prototype.forEach.call(s.getElementsByTagName('Representation'),(t=>{var s,o,d,u,h,c,l,p,f,m,v,g,S,b,y,T,E,w,$;const P=t.getElementsByTagName('SegmentBase')[0],A=P&&r(P,'indexRange').split('-'),k=P&&P.getElementsByTagName('Initialization')[0],_=k&&r(k,'range').split('-');if(!_||!A){const e=t.parentElement;if('text'===(null==e?void 0:e.getAttribute('contentType'))){const r=null!==(s=t.getAttribute('id'))&&void 0!==s?s:void 0,a=(i?i+'/':'')+(null===(h=null===(u=null===(d=null===(o=t.getElementsByTagName('BaseURL'))||void 0===o?void 0:o[0])||void 0===d?void 0:d.childNodes)||void 0===u?void 0:u[0])||void 0===h?void 0:h.data),l=null!==(c=e.getAttribute('lang'))&&void 0!==c?c:void 0;a&&n.push({id:r,url:a,language:l})}return}const D=Number(null===(l=t.attributes.getNamedItem('bandwidth'))||void 0===l?void 0:l.value),R=(i?i+'/':'')+t.getElementsByTagName('BaseURL')[0].childNodes[0].data;let I;const L=null!==(f=null===(p=t.attributes.getNamedItem('frameRate'))||void 0===p?void 0:p.value)&&void 0!==f?f:void 0;I=L?oc(L):void 0,a.push({width:Number(null===(m=t.attributes.getNamedItem('width'))||void 0===m?void 0:m.value),height:Number(null===(v=t.attributes.getNamedItem('height'))||void 0===v?void 0:v.value),bandwidth:D,baseURL:R,failoverHosts:e,indexFrom:Number(A[0]),indexTo:Number(A[1]),initFrom:Number(_[0]),initTo:Number(_[1]),codecs:null!==(S=null===(g=t.attributes.getNamedItem('codecs'))||void 0===g?void 0:g.value)&&void 0!==S?S:void 0,mimeType:null!==(y=null===(b=t.attributes.getNamedItem('mimeType'))||void 0===b?void 0:b.value)&&void 0!==y?y:void 0,fps:I,bufferSize:.1*D/8,bufferLength:.1,name:null!==(E=null===(T=t.attributes.getNamedItem('okQuality'))||void 0===T?void 0:T.value)&&void 0!==E?E:void 0,id:null!==($=null===(w=t.attributes.getNamedItem('id'))||void 0===w?void 0:w.value)&&void 0!==$?$:void 0})})),a.length?(this._representations=a,n.forEach((({id:t,language:e,url:i})=>{const s=document.createElement('track');s.setAttribute('src',i),t&&s.setAttribute('id',t),e&&s.setAttribute('srclang',e),this._video.appendChild(s)})),this._representations.sort(((t,e)=>e.bandwidth-t.bandwidth)),this._params.onManifestReady(this._representations)):this._onDashCallback('error')}_loadInitAndSidx(t,e){if(t===this._currentRepresentation)return void(e&&e());if(t.refs)return void this._stream.abort((()=>{this._stream.append(t.initMessage,e)}));const i=Date.now();this._stream.load(t,t.initFrom,t.indexTo,(i=>{let s=t.initTo-t.initFrom+1;if(!i.byteLength)return void this._params.onError('EmptyResponse','Empty response');t.initMessage=new Uint8Array(i.buffer,0,s);const r=new DataView(i.buffer);s+=12;const a=r.getUint32(s+4,!1);s+=8;let n=r.getUint32(s,!1),o=r.getUint32(s+4,!1)+(t.indexTo+1);s+=8;const d=r.getUint16(s+2,!1);s+=4,t.refs=[];for(let e=0;e<d;e+=1){const e=o+(2147483647&r.getUint32(s,!1)),i=n+r.getUint32(s+4,!1);s+=12,t.refs.push({fromTime:n/a,toTime:i/a,fromOffset:o,toOffset:e-1}),o=e,n=i}const u=t.refs[t.refs.length-1];u.toTime-u.fromTime<.3&&t.refs.pop(),this._stream.append(t.initMessage,e)}),void 0,(t=>{this._params.onResponseHeaders(t),this._params.onIdxRequestPing(Date.now()-i)}),t.indexTo-t.initFrom+1)}startPlay(t){const e=window.MediaSource||window.WebKitMediaSource;if(!e)return void this._params.onError('MediaSourceNotSupported','MediaSource is not supported');const i=new e;let s,r;const a=()=>{const e=this._findRef(this._video.currentTime);if(!e||this._video.paused)return;if(!this._cachingPaused&&void 0!==this._lastLoadOffset&&this._lastLoadOffset-this._video.currentTime<this._config.FRONT_CACHE_DURATION&&this._lastLoadOffset-this._video.currentTime<this._stream.getMaxBufferDuration()){const t=this._stream.isFull()?this._findBufferRangeEnd(this._video.currentTime):this._lastLoadOffset;this._loadRef(this._params.selectRepresentation(this._representations),t)}const i=this._appendVector[String(e.fromTime)];let a;i!==s&&(s=i,this._params.onRepresentationPlay(i));if(this._findRef(e.toTime)){const e=this._buffer.getByTime(this._video.currentTime);if(!e)return void this._onDashCallback('buffering');a=e.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 Ec({mediaSource:i,sourceBuffer:e,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){this._lastLoadOffset=void 0,this._loadInitAndSidx(t,(()=>{this._currentRepresentation=t;const s=this._findRef(e);if(s){if(i){this._isLastRef(s)&&e>=s.toTime&&(e=s.fromTime);const t=this._findRef(this._video.currentTime),i=Math.abs(this._video.currentTime-e),r=this._video.duration<this._config.SEEK_IN_SEGMENT_THRESHOLD/1e3||s===t||i<=this._config.SEEK_IN_SEGMENT_DELTA/1e3;this._video.currentTime=r?e:s.fromTime}this._appendVector[String(s.fromTime)]=t,this._stream.load(t,s.fromOffset,s.toOffset,((t,e)=>this._stream.append(t,e)),(()=>{this._lastLoadOffset=s.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=!1){this._stream&&this._buffer.getByTime(t)&&!e?this._video.currentTime=t:this._loadRef(this._params.selectRepresentation(this._representations),t,!0)}updateRefsForCurrentTime(){const t=this._video.currentTime;this._stream&&!r(this._buffer.getByTime(t))||this._loadRef(this._params.selectRepresentation(this._representations),t,!1)}_findRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return;if(Array.isArray(i)&&0===i.length)return void this._params.onError('emptyrefs','Empty refs');let s;for(let e=0;e<i.length;e++){const r=i[e];if(r.fromTime<=t&&r.toTime>t)return r;r.fromTime>t&&(!s||r.fromTime<s.fromTime)&&(s=r)}if(!s){const e=i[i.length-1];if(t>e.toTime)return e}return s}_isLastRef(t){var e;const i=null===(e=this._currentRepresentation)||void 0===e?void 0:e.refs;if(!i)return!1;const s=i[i.length-1];return t.fromTime===s.fromTime}_findBufferRangeEnd(t){let e=this._video.buffered.length;for(;e-- >0;){const i=this._video.buffered.start(e),s=this._video.buffered.end(e);if(t>i&&t<s)return Math.round(10*s)/10}return t}destroy(){this._stream&&this._stream.destroy(),clearTimeout(this._loopTimeout),this._loopTimeout=void 0}}var $c;!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'}($c||($c={}));const Pc=[$c.PAUSED,$c.PLAYING];class Ac{constructor(r){this.videoState=new js($c.STOPPED),this.subscription=new i,this.representations$=new t([]),this.currentRepresentation$=new t(void 0),this.textTracksManager=new ys,this.elementSize$=new t(void 0),this.dashLiteEvents={idxRequestPing$:new e,responseHeaders$:new e,manifestReady$:new e,representationPlay$:new e,error$:new e},this.handleManifestReady=t=>{var e,i,s;const r=[];for(const a of t){const t=null!==(i=null!==(e=a.name)&&void 0!==e?e:a.id)&&void 0!==i?i:a.height.toString(10),n=null!==(s=a.name&&_s(a.name))&&void 0!==s?s:Os(a),o=a.bandwidth/1e3,d={width:a.width,height:a.height},u=a.fps;if(!n)continue;const h={id:t,quality:n,bitrate:o,size:d,fps:u};r.push({track:h,representation:a})}this.representations$.next(r),this.params.output.availableVideoTracks$.next(r.map((({track:t})=>t))),this.videoState.setState($c.MANIFEST_LOADED)},this.handleRepresentationPlay=t=>{var e;const i=null===(e=this.representations$.getValue().find((({representation:e})=>e===t)))||void 0===e?void 0:e.track;if(i){this.params.output.currentVideoTrack$.next(i);this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(i.id)}},this.selectRepresentation=()=>{const t=this.currentRepresentation$.getValue();return l(t,'Can\'t select representation. something went wrong'),t},this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.videoState.getTransition(),i=this.params.desiredState.playbackState.getState(),r=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${t}; videoTransition: ${JSON.stringify(e)}; desiredPlaybackState: ${i}; seekPositionTransition: ${JSON.stringify(a)};`}),i===P.STOPPED)return void(t!==$c.STOPPED&&(this.videoState.startTransitionTo($c.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($c.STOPPED),Ds(this.params.desiredState.playbackState,P.STOPPED,!0)));if(e)return;const o=null==a?void 0:a.to;switch((null==r?void 0:r.to)!==P.PAUSED&&s(o)&&Pc.includes(t)&&this.seek(o),t){case $c.STOPPED:return this.videoState.startTransitionTo($c.MANIFEST_LOADED),void this.prepare();case $c.MANIFEST_LOADED:return void this.videoState.startTransitionTo($c.INITIAL_REPRESENTATION_SELECTED);case $c.INITIAL_REPRESENTATION_SELECTED:return this.videoState.startTransitionTo($c.METADATA_LOADED),void this.dash.startPlay(this.selectRepresentation());case $c.METADATA_LOADED:return this.videoState.startTransitionTo($c.READY),void this.dash.seek(null!=o?o:0);case $c.READY:return void(i===P.PAUSED?(this.videoState.setState($c.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED)):i===P.PLAYING&&(this.videoState.startTransitionTo($c.PLAYING),this.playIfAllowed()));case $c.PLAYING:return void(i===P.PAUSED?(this.videoState.startTransitionTo($c.PAUSED),this.video.pause()):(null==r?void 0:r.to)===P.PLAYING&&Ds(this.params.desiredState.playbackState,P.PLAYING));case $c.PAUSED:return void(i===P.PLAYING?(this.videoState.startTransitionTo($c.PLAYING),this.playIfAllowed()):(null==r?void 0:r.to)===P.PAUSED&&Ds(this.params.desiredState.playbackState,P.PAUSED));default:return n(t)}},this.params=r,this.log=this.params.dependencies.logger.createComponentLog('DashProvider'),o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Ts(r.container),this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),'url'===this.params.source.type&&this.params.output.hostname$.next(Gs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.buffer=new ws(this.video),this.dash=new wc({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}}),this.subscribe()}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashProvider',message:'DashProvider internal logic error',thrown:e})},n=()=>{const t=this.params.desiredState.autoVideoTrackSwitching.getState(),e=this.params.desiredState.autoVideoTrackSwitching.getTransition();return e?e.to:t},d=As(this.video),l=(t,e)=>this.subscription.add(t.subscribe(e,i));l(d.timeUpdate$,t.position$),l(d.durationChange$,t.duration$),l(d.ended$,t.endedEvent$),l(d.looped$,t.loopedEvent$),l(d.error$,t.error$),l(d.isBuffering$,t.isBuffering$),l(d.firstFrame$,t.firstFrameEvent$),this.subscription.add(d.seeking$.subscribe((()=>{r(this.params.desiredState.seekPosition.getTransition())&&(this.videoState.getState()===$c.PLAYING||this.videoState.getState()===$c.PAUSED)&&this.dash.updateRefsForCurrentTime()}))),this.subscription.add(d.seeked$.subscribe(t.seekedEvent$,i)),this.subscription.add(gs(this.video,e.isLooped,i)),this.subscription.add(Ss(this.video,e.volume,d.volumeState$,i)),this.subscription.add(d.volumeState$.subscribe(this.params.output.volume$)),this.textTracksManager.connect(this.video,e,t),l(Ys(this.video),this.elementSize$),this.subscription.add(d.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===$c.READY&&this.videoState.setState($c.READY)}),i)).add(d.pause$.subscribe((()=>{this.videoState.setState($c.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED)}))).add(d.playing$.subscribe((()=>{this.videoState.setState($c.PLAYING),Ds(this.params.desiredState.playbackState,P.PLAYING)}),i)).add(d.loadedMetadata$.subscribe((()=>{this.videoState.setState($c.METADATA_LOADED)}),i)).add(d.currentBuffer$.subscribe((e=>{this.buffer.fill(),t.currentBuffer$.next(e)}),i)).add(this.dashLiteEvents.error$.pipe(u((({id:t,message:e,thrown:i})=>({id:`DashLite_${t}`,message:e,thrown:i})))).subscribe(this.params.output.error$)).add(o(this.params.desiredState.videoTrack.transitionStarted$,this.params.desiredState.autoVideoTrackSwitching.transitionStarted$,this.representations$,this.params.dependencies.throughputEstimator.rttAdjustedThroughput$,this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$,this.params.output.element$,this.elementSize$,a(this.video,'progress')).pipe(u((()=>{var t,e;const i=this.currentRepresentation$.getValue(),r=this.representations$.getValue(),a=this.params.desiredState.autoVideoTrackSwitching.getTransition(),o=this.params.desiredState.videoTrack.getState(),d=this.params.dependencies.throughputEstimator.rttAdjustedThroughput$.getValue(),u=this.elementSize$.getValue(),h=n();let c;if(a&&this.params.desiredState.autoVideoTrackSwitching.setState(a.to),!h&&s(o))c=o;else{const e=qs(this.video.buffered,1e3*this.video.currentTime),s=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);c=null===(t=Hs(r.map((({track:t})=>t)),{container:u,throughput:d,tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:s,currentRepresentation:i}))||void 0===t?void 0:t.id}return s(c)?null===(e=r.find((({track:t})=>t.id===c)))||void 0===e?void 0:e.representation:void 0})),c()).subscribe(this.currentRepresentation$,i)).add(y({needToSelectRepresentation:this.videoState.stateChangeStarted$.pipe(S((t=>t.to===$c.INITIAL_REPRESENTATION_SELECTED))),currentRepresentationSelected:this.currentRepresentation$.pipe(S(s))}).pipe(f()).subscribe((()=>this.videoState.setState($c.INITIAL_REPRESENTATION_SELECTED)),i)).add(this.currentRepresentation$.pipe(S(s),c(((t,e)=>this.params.tuning.autoTrackSelection.lazyQualitySwitch&&n()?t.height<=e.height:t===e))).subscribe((t=>{const e=qs(this.video.buffered,1e3*this.video.currentTime),i=Math.min(e/this.params.tuning.dash.forwardBufferTarget,1);(!this.params.tuning.autoTrackSelection.lazyQualitySwitch||i<=.5||!n())&&(this.dash.setQualityByRepresentation(t,!0),this.params.output.hostname$.next(Gs(t.baseURL)))}),i)).add(this.dashLiteEvents.responseHeaders$.subscribe((t=>{const{type:e,reused:i}=jh(t);this.params.output.httpConnectionType$.next(e),this.params.output.httpConnectionReused$.next(i)}))).add(this.dashLiteEvents.idxRequestPing$.pipe(f()).subscribe(this.params.output.firstBytesEvent$)).add(this.dashLiteEvents.idxRequestPing$.subscribe((t=>this.params.dependencies.throughputEstimator.addRawRtt(t)))).add(this.dashLiteEvents.manifestReady$.subscribe(this.handleManifestReady,i)).add(this.dashLiteEvents.representationPlay$.pipe(S(s)).subscribe(this.handleRepresentationPlay,i)).add(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0)).subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.buffer.destroy(),this.dash.destroy()}prepare(){const t=this.params.source;switch(t.type){case'url':this.dash.attachSource(t.url);break;case'raw':this.dash.attachManifest(t.raw);break;default:return n(t)}}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next(),this.dash.seek(t)}playIfAllowed(){ms(this.video).then((t=>{t||(this.videoState.setState($c.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED,!0))}))}}var kc=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)},_c=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 Dc=t=>t.range?t.range.split('-').map((t=>parseInt(t,10))):[NaN,NaN];class Rc{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 O(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]=Dc(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(Dc),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 Uo,d=o.signal,u={url:t,from:s,to:r,loaded:0,data:null,abortController:o};d.addEventListener('abort',(()=>this.onBigRequestAbort(u)));const h=t=>{var e,i;throw null===(i=(e=this.params).onError)||void 0===i||i.call(e,{id:'BigRequestParsing',message:'Error parsing response data',thrown:t}),t};return Vo(fetch).fetch(n,{signal:d}).then((t=>{var e,i,s;if(!t.ok||!t.body)return void this.onBigRequestError(u);const[r,a]=t.body.tee();null===(i=(e=this.params).onDownloadStream)||void 0===i||i.call(e,a);const n=r.getReader(),o=parseInt(null!==(s=t.headers.get('Content-Length'))&&void 0!==s?s:'',10);u.data=new ArrayBuffer(o);const d=new Uint8Array(u.data),c=({done:t,value:e})=>O(this,void 0,void 0,(function*(){t?this.onBigRequestProgress(u):e&&(d.set(e,u.loaded),u.loaded+=e.byteLength,this.onBigRequestProgress(u),yield null==n?void 0:n.read().then(c,Rc.suppressStreamErrors).catch(h))}));null==n||n.read().then(c,Rc.suppressStreamErrors).catch(h)}),Rc.suppressAbort).catch((t=>this.onBigRequestError(u,t))),u}onBigRequestProgress({url:t,from:e,to:i,loaded:s,data:r}){var a,n,o,d,u,h,c;if(!this.activeRequests.has(t)||!r)return;const l=null!==(a=this.dashJsRequestQueue.get(t))&&void 0!==a?a:[];for(const a of l){const{request:l}=a,[p,f]=Dc(l),m=p>=e&&f<=e+s,v=e>=p&&e+s<f,g=r.slice(p-e,Math.min(f-e+1,s));(m||v)&&(l.requestStartDate=null!==(n=l.requestStartDate)&&void 0!==n?n:new Date,l.firstByteDate=null!==(o=l.firstByteDate)&&void 0!==o?o:new Date,l.bytesLoaded=g.byteLength,l.bytesTotal=i-e),m?(l.requestEndDate=new Date,this.dashJsRequestQueue.set(t,(null!==(d=this.dashJsRequestQueue.get(t))&&void 0!==d?d:[]).filter((t=>t!==a))),null===(u=a.success)||void 0===u||u.call(a,g,'',t),null===(h=this.dashMetrics)||void 0===h||h.addHttpRequest(l,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 d=null!==(n=this.dashJsRequestQueue.get(t))&&void 0!==n?n:[];for(const t of d){const[r,a]=Dc(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]=Dc(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 Ic{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(Ic.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;Ic.shouldDelegateToBase(e)?this.baseLoader.abort(t):this.bigRequest.abort(t)}}const Lc=(t,e)=>{const i=new Rc(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 Ic(r,e,s)}}))(e(t),i)}}),!0),()=>i.destroy()};var xc=i=>{const r=new t(1/0),a=new e;let n=NaN,o=!1;return i.extend('XHRLoader',(function(){const{parent:t}=this,e=t.load.bind(t);return{load:function(t){if('MPD'===t.request.type){const e=t.onload,i=t.progress;t.onload=function(...t){return(t=>{var e,i,a;if(!t.getAllResponseHeaders().includes('x-playback-duration'))return;const n=parseInt(null!==(e=t.getResponseHeader('X-Playback-Duration'))&&void 0!==e?e:'',10),o=parseInt(null!==(i=t.getResponseHeader('X-Playback-Duration-Millis'))&&void 0!==i?i:'',10),d=null!==(a=null!=o?o:1e3*n)&&void 0!==a?a:NaN;s(d)&&!isNaN(d)&&r.next(d)})(this),e(...t)},t.progress=function(...t){return this.readyState>=2&&!o&&(o=!0,a.next(Date.now()-n)),i(...t)},n=Date.now(),o=!1}return e(t)}}}),!0),{playbackDuration$:r,ping$:a}};class Oc{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}}const Cc={};var Nc;!function(t){t.DOWNLOADING_LIB='downloading_lib',t.STOPPED='stopped',t.STREAM_INITIALIZED='stream_initialized',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(Nc||(Nc={}));const Mc=(t,e)=>new p((i=>{const s=t=>i.next(t);return t.on(e,s),()=>t.off(e,s)}));class Bc{constructor(e){this.subscription=new i,this.videoState=new js(Nc.DOWNLOADING_LIB),this.textTracksManager=new ys,this.videoTracks=[],this.frameRatesByFrameHeight={},this.isLive$=new t(void 0),this.maxSeekBackTime$=new t(1/0),this.availableFrom$=new t(void 0),this.elementSize$=new t(void 0),this.liveOffset=new Oc,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition(),a=this.isLive$.getValue();if(this.videoState.getTransition())return;if(t===Nc.DOWNLOADING_LIB||t===Nc.STREAM_INITIALIZED)return;const o=null==r?void 0:r.to;switch((null==i?void 0:i.to)!==P.PAUSED&&s(o)&&t!==Nc.STOPPED&&e!==P.STOPPED&&(a?this.seek(o+Uc(this.liveOffset.getTotalPausedTime())):this.seek(o)),e){case P.STOPPED:switch(t){case Nc.STOPPED:break;case Nc.PLAYING:case Nc.PAUSED:case Nc.READY:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case Nc.PLAYING:break;case Nc.PAUSED:a&&(this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.params.output.position$.next(Uc(this.liveOffset.getTotalOffset()))):this.seek(Uc(this.liveOffset.getTotalOffset()))),this.play();break;case Nc.READY:this.play();break;case Nc.STOPPED:this.prepare();break;default:n(t)}break;case P.PAUSED:switch(t){case Nc.PLAYING:this.pause(),this.liveOffset.pause();break;case Nc.PAUSED:break;case Nc.READY:this.videoState.setState(Nc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED);break;case Nc.STOPPED:this.prepare();break;default:n(t)}break;default:n(e)}},this.video=Ts(e.container),this.params=e,this.params.output.element$.next(this.video),this.params.output.availableVideoTracks$.next([]),this.params.output.hostname$.next(Gs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.loadDashJs()}loadDashJs(){let t=!1;const e=e=>{var i;t||this.params.output.error$.next({id:'timeout'===e?'DashJSTimedOut':'DashJSLoadingError',message:`Dash.js failed to load: ${null===(i=null==e?void 0:e.toString)||void 0===i?void 0:i.call(e)}`,thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Yh(import('dashjs/dist/dash.mediaplayer.min.js').then((e=>{t||(Cc.MediaPlayer=e.MediaPlayer,Cc.Debug=e.Debug,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(Cc.MediaPlayer,'dashjs not loaded'),l(Cc.Debug,'dashjs not loaded'),this.player=Cc.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?oc(t.frameRate+''):void 0),!0)));(this.params.format===A.DASH_WEBM||this.params.format===A.DASH_LIVE_WEBM)&&this.params.tuning.useWebmBigRequest?this.destroyBigRequest=Lc(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&&_c(this.player),kc(this.player),this.player.clearDefaultUTCTimingSources(),this.subscribe(),this.videoState.setState(Nc.STOPPED)}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'DashIFProvider',message:'DashIFProvider internal logic error',thrown:e})},a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(Ys(this.video),this.elementSize$),a(Mc(this.player,'error').pipe(u((t=>({id:`DashJS#${'object'==typeof t.error?t.error.code:t.error}`,message:'object'==typeof t.error?t.error.message:void 0})))),t.error$),a(Mc(this.player,'playbackError').pipe(u((t=>({id:'DashJSPlayback',message:t.error})))),t.error$);const n=Mc(this.player,'qualityChangeRendered').pipe(S((({mediaType:t})=>'video'===t)),u((({newQuality:t})=>{var e;return null===(e=this.videoTracks.find((({bitrateInfo:e})=>e.qualityIndex===t)))||void 0===e?void 0:e.track})));n.pipe(S(s)).subscribe(t.currentVideoTrack$),this.subscription.add(this.videoState.transitionEnded$.pipe(S((({to:t})=>t===Nc.STREAM_INITIALIZED)),f()).subscribe((()=>{this.subscription.add(vs(e.videoTrack,(()=>{var t,e;const i=this.player.getQualityFor('video');return null===(e=null===(t=this.videoTracks.find((({bitrateInfo:t})=>t.qualityIndex===i)))||void 0===t?void 0:t.track)||void 0===e?void 0:e.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.videoTracks.find((({track:e})=>e.id===t)))||void 0===e?void 0:e.bitrateInfo;i&&this.player.setQualityFor('video',i.qualityIndex)}),{changed$:n.pipe(u((t=>null==t?void 0:t.id))),onError:i}))}),i)),this.subscription.add(vs(e.autoVideoTrackSwitching,(()=>{var t,e,i;return null===(i=null===(e=null===(t=this.player.getSettings().streaming)||void 0===t?void 0:t.abr)||void 0===e?void 0:e.autoSwitchBitrate)||void 0===i?void 0:i.video}),(t=>this.player.updateSettings({streaming:{abr:{autoSwitchBitrate:{video:t}}}})),{onError:i})),a(Mc(this.player,'bufferStateChanged').pipe(S((({mediaType:t})=>'video'===t)),u((({state:t})=>'bufferStalled'===t))),t.isBuffering$),a(Mc(this.player,'fragmentLoadingStarted').pipe(u((t=>Gs(t.request.url)))),t.hostname$),a(Mc(this.player,'streamInitialized'),(({streamInfo:{duration:e,manifestInfo:{isDynamic:i,availableFrom:s}}})=>{this.isLive$.next(i),this.availableFrom$.next(s.getTime()),i||t.duration$.next(e),this.videoTracks=[];const r=this.player.getQualityFor('video');let a;for(const t of this.player.getBitrateInfoListFor('video')){const e=t.qualityIndex.toString(10),i=Os(t),s=t.bitrate/1e3,n={width:t.width,height:t.height},o=this.frameRatesByFrameHeight[t.height];if(i){const d={id:e,quality:i,bitrate:s,size:n,fps:o};this.videoTracks.push({track:d,bitrateInfo:t}),t.qualityIndex===r&&(a=d)}}t.availableVideoTracks$.next(this.videoTracks.map((({track:t})=>t))),a&&t.currentVideoTrack$.next(a),this.videoState.setState(Nc.STREAM_INITIALIZED),this.videoState.startTransitionTo(Nc.READY)})),a(Mc(this.player,'fragmentLoadingCompleted'),(({request:t})=>{if(!t.requestEndDate||!t.firstByteDate||!t.bytesLoaded)return;const e=t.requestEndDate.getTime()-t.firstByteDate.getTime(),i=t.bytesLoaded;this.params.dependencies.throughputEstimator.addRawSpeed(i,e)})),a(o(this.params.dependencies.throughputEstimator.throughput$,this.elementSize$,e.autoVideoTrackLimits.stateChangeEnded$),(()=>{if(!this.params.desiredState.autoVideoTrackSwitching.getState()||!this.videoTracks.length)return;const t=this.params.dependencies.throughputEstimator.throughput$.getValue(),i=Hs(this.videoTracks.map((({track:t})=>t)),{container:this.elementSize$.getValue(),throughput:t,tuning:this.params.tuning.autoTrackSelection,limits:e.autoVideoTrackLimits.getState()}),s=this.videoTracks.find((({track:t})=>t===i));(null==s?void 0:s.bitrateInfo)&&this.player.setQualityFor('video',null==s?void 0:s.bitrateInfo.qualityIndex,!1)})),a(y({maxSeekBackTime:this.maxSeekBackTime$,isLive:this.isLive$.pipe(S(s))}).pipe(S((({isLive:t})=>t)),u((({maxSeekBackTime:t})=>Uc(t)))),this.params.output.duration$);const d=Mc(this.player,'playbackTimeUpdated').pipe(u((({time:t})=>null!=t?t:0)));a(y({availableFrom:this.availableFrom$.pipe(S(s)),currentTime:d}),(({availableFrom:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e))),a(d.pipe(S((()=>!1===this.isLive$.getValue()))),t.position$),a(Mc(this.player,'playbackSeeked'),(()=>t.seekedEvent$.next())),a(Mc(this.player,'playbackEnded'),t.endedEvent$),a(Mc(this.player,'playbackProgress').pipe(u((()=>$s(this.video.buffered,this.video.currentTime)))),t.currentBuffer$),a(Mc(this.player,'playbackPlaying'),(()=>{this.videoState.setState(Nc.PLAYING),Ds(e.playbackState,P.PLAYING)})),a(Mc(this.player,'playbackNotAllowed'),(()=>{this.player.isMuted()?(this.player.setMute(!1),this.videoState.setState(Nc.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED,!0)):(this.player.setMute(!0),this.player.play())})),a(Mc(this.player,'playbackPaused'),(()=>{this.videoState.setState(Nc.PAUSED),Ds(e.playbackState,P.PAUSED)})),a(Mc(this.player,'canPlay'),(()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===Nc.READY&&this.videoState.setState(Nc.READY)})),a(this.isLive$,t.isLive$),a(Ys(this.video),(()=>{this.player.isReady()&&this.player.updatePortalSize()}));a(o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0)),this.syncPlayback);const{playbackDuration$:c,ping$:l}=xc(this.player);a(c,this.maxSeekBackTime$),a(l.pipe(f()),t.firstBytesEvent$),this.params.tuning.flushShortLoopedBuffers&&a(y({isLive:this.isLive$,isShort:t.duration$.pipe(u((t=>t<60)))}),(({isLive:t,isShort:e})=>{const i=!t&&e;this.player.updateSettings({streaming:{buffer:{flushBufferAtTrackSwitch:i}}})})),a(d.pipe(S((t=>t>this.params.tuning.insufficientBufferRuleMargin)),f()),(()=>this.player.updateSettings({streaming:{abr:{additionalAbrRules:{insufficientBufferRule:!0}}}}))),this.textTracksManager.connect(this.video,e,t),this.subscription.add(Mc(this.player,'manifestLoaded').pipe(f()).subscribe((()=>{const e=Date.now();this.subscription.add(Mc(this.player,'playbackPlaying').pipe(f()).subscribe((()=>t.firstFrameEvent$.next(Date.now()-e)),i))}),i)),this.subscription.add(gs(this.video,e.isLooped,i));const{volumeState$:p,looped$:v}=As(this.video);this.subscription.add(Ss(this.video,e.volume,p,i)),this.subscription.add(p.subscribe(t.volume$,i)),this.subscription.add(v.subscribe(t.loopedEvent$))}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.player.attachSource(null),this.player.attachView(null),this.player.initialize(),this.player.clearDefaultUTCTimingSources(),this.videoState.setState(Nc.STOPPED),Ds(this.params.desiredState.playbackState,P.STOPPED,!0)}prepare(){this.videoState.startTransitionTo(Nc.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=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Uc(i));const s=vc(this.params.source.url,this.liveOffset.getTotalOffset()/1e3,mc.PLAYBACK_SHIFT);this.player.attachSource(s)}else this.player.seek(t)}play(){this.videoState.startTransitionTo(Nc.PLAYING),this.player.play()}pause(){this.videoState.startTransitionTo(Nc.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)}}const Uc=t=>-t/1e3;function Vc(){return v()}function Fc(t){return Vc()-t}function Hc(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 qc(t,e,i,r){const a=window.XMLHttpRequest;let n,o,d,u,h,c=!1,p=0,f=!1,m='arraybuffer',v=7e3,g=2e3,S=()=>{if(c)return;l(u);const t=Fc(u);let e;if(t<g)return e=g-t,void setTimeout(S,e);g*=2,g>v&&(g=v),o&&o.abort(),o=new a,y()};const b=()=>{if(!c){if(--p>=0)return S(),void(r&&r());c=!0,h&&h(),i&&i()}},y=()=>{u=Vc(),o=new a,o.open('get',t);let i,s=0,r=0;const p=()=>(l(u),Math.max(u,Math.max(i||0,r||0)));if(n&&o.addEventListener('progress',(t=>{const e=Vc();n.updateChunk&&t.loaded>s&&(n.updateChunk(p(),t.loaded-s),s=t.loaded,i=e)})),d&&(o.timeout=d,o.addEventListener('timeout',(()=>b()))),o.addEventListener('load',(()=>{if(c)return;l(o);const t=o.status;if(t>=200&&t<300){if(o.response.byteLength&&n){const t=o.response.byteLength-s;t&&n.updateChunk&&n.updateChunk(p(),t)}h&&h(),o&&e(o.response)}else b()})),o.addEventListener('error',(()=>{b()})),f){const t=()=>{l(o),o.readyState===XMLHttpRequest.HEADERS_RECEIVED&&(r=Vc(),o.removeEventListener('readystatechange',t))};o.addEventListener('readystatechange',t)}return o.responseType=m,o.send(),T},T={withBitrateReporting:t=>(n=t,T),withParallel:t=>(f=t,T),withJSONResponse:()=>(m='json',T),withRetryCount:t=>(p=t,T),withRetryInterval:(t,e)=>(s(t)&&(g=t),s(e)&&(v=e),T),withTimeout:t=>(d=t,T),withFinally:t=>(h=t,T),send:y,abort:()=>{o&&(o.abort(),o=void 0),c=!0,h&&h()}};return T}class Gc{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 Yc{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=Vc(),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=qc(e,(s=>{t._complete=1,t._responseData=s,t._downloadTime=Vc()-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=Vc()}_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=Vc();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 jc{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 Gc(this.params.logger),this._initVideo()}attachSource(t){this.manifestUrl=t,this.urlResolver=Hc(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=Hc(t),this.catchUp()}_handleNetworkError(){this.params.logger('Fatal network error'),this.params.playerCallback({name:'error',type:'network'})}_retryCallback(){this.params.playerCallback({name:'retry'})}_getBufferSizeSec(){const t=this.params.videoElement;let e=0;const i=t.buffered.length;return 0!==i&&(e=t.buffered.end(i-1)-Math.max(t.currentTime,t.buffered.start(0))),e}_notifyBuffering(t){this.destroyed||(this.params.logger(`buffering: ${t}`),this.params.playerCallback({name:'buffering',isBuffering:t}),this.buffering=t)}_initVideo(){const{videoElement:t,logger:e}=this.params;t.addEventListener('error',(i=>{var s;this.destroyed||(e(`Video element error: ${null===(s=t.error)||void 0===s?void 0:s.code}`),this.params.playerCallback({name:'error',type:'media'}))})),t.addEventListener('timeupdate',(()=>{const e=this._getBufferSizeSec();!this.paused&&e<.3?this.buffering||(this.buffering=!0,window.setTimeout((()=>{!this.paused&&this.buffering&&this._notifyBuffering(!0),t.pause(),this.videoPlayStarted=!1}),1e3*(e+.1))):this.buffering&&this.videoPlayStarted&&this._notifyBuffering(!1)})),t.addEventListener('playing',(()=>{e('playing')})),t.addEventListener('stalled',(()=>this._fixupStall())),t.addEventListener('waiting',(()=>this._fixupStall()))}_fixupStall(){const{logger:t,videoElement:e}=this.params,i=e.buffered.length;let s;0!==i&&(s=e.buffered.start(i-1),e.currentTime<s&&(t('Fixup stall'),e.currentTime=s))}_selectQuality(t){const{videoElement:e}=this.params;let i,s,r;const a=e&&1.62*(window.devicePixelRatio||1)*e.offsetHeight||520;for(let e=0;e<this.manifest.length;++e)r=this.manifest[e],this.maxAutoQuality&&r.video.height>this.maxAutoQuality||(r.bitrate<t&&a>Math.min(r.video.height,r.video.width)?(!s||r.bitrate>s.bitrate)&&(s=r):(!i||i.bitrate>r.bitrate)&&(i=r));return s||i}shouldPlay(){if(this.paused)return!1;const t=this._getBufferSizeSec()-Math.max(1,this.sourceJitter);return t>3||s(this.downloadRate)&&(this.downloadRate>1.5&&t>2||this.downloadRate>2&&t>1)}_setVideoSrc(t,e){const{logger:i,videoElement:s,playerCallback:r}=this.params;this.mediaSource=new window.MediaSource,i('setting video src'),s.src=URL.createObjectURL(this.mediaSource),this.mediaSource.addEventListener('sourceopen',(()=>{l(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 Yc(3,1e4,this.bitrateSwitcher,this.params.config.MAX_PARALLEL_REQUESTS,this.params.logger),this._setVideoSrc(t,(()=>this._switchToQuality(t)))}_representation(t){const{logger:e,videoElement:i,playerCallback:a}=this.params;let n=!1,o=null,d=null,u=null,h=null,c=!1;const p=()=>{const t=n&&(!c||c===this.rep);return t||e('Not running!'),t},f=(t,e,i)=>{u&&u.abort(),u=qc(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withTimeout(1e4).withBitrateReporting(this.bitrateSwitcher).withRetryCount(3).withFinally((()=>{u=null})).send()},m=(t,e,i)=>{l(this.filesFetcher),null==d||d.abort(),d=this.filesFetcher.requestData(this.urlResolver.resolve(t,!1),e,i,(()=>this._retryCallback())).withFinally((()=>{d=null})).send()},v=t=>{const s=i.playbackRate;i.playbackRate!==t&&(e(`Playback rate switch: ${s}=>${t}`),i.playbackRate=t)},g=t=>{this.lowLatency=t,e(`lowLatency changed to ${t}`),S()},S=()=>{if(this.lowLatency){let t=this._getBufferSizeSec();if(this.bufferStates.length<5)return void v(1);const i=Vc()-6e4;let s=0;for(let e=0;e<this.bufferStates.length;e++){const r=this.bufferStates[e];t=Math.min(t,r.buf),r.ts<i&&s++}this.bufferStates.splice(0,s),e(`update playback rate; minBuffer=${t} drop=${s} jitter=${this.sourceJitter}`);let r=t-1;this.sourceJitter>=0?r-=this.sourceJitter/2:this.sourceJitter-=1,v(r>3?1.15:r>1?1.1:r>.3?1.01:1)}else v(1)},b=t=>{let i;const r=()=>i&&i.start?i.start.length:0,n=t=>i.start[t]/1e3,o=t=>i.dur[t]/1e3,d=t=>i.fragIndex+t,u=(t,e)=>({chunkIdx:d(t),startTS:n(t),dur:o(t),discontinuity:e}),c=()=>{let t=0;if(i&&i.dur){let e=Math.max(this.sourceJitter,1);for(this.lowLatency||(e+=2),t=i.dur.length-1;t>=0&&(e-=i.dur[t]/1e3,!(e<=0));--t);}return u(t,!0)},f=(t,e,i)=>{h&&h.abort(),h=qc(this.urlResolver.resolve(t,!0,this.lowLatency),e,i,(()=>this._retryCallback())).withTimeout(1e4).withRetryCount(3).withFinally((()=>{h=null})).withJSONResponse().send()};return{seek:(e,o)=>{f(t,(t=>{if(!p())return;i=t;const d=Boolean(i.lowLatency);d!==this.lowLatency&&g(d);let h=0;for(let t=0;t<i.dur.length;++t)h+=i.dur[t];h>0&&(l(this.filesFetcher),this.filesFetcher.optimizeForSegDuration(h/i.dur.length)),a({name:'index',zeroTime:i.zeroTime,shiftDuration:i.shiftDuration}),this.sourceJitter=i.hasOwnProperty('jitter')?Math.min(10,Math.max(.01,i.jitter/1e3)):1,e((t=>{const e=r();if(!(e<=0)){if(s(t))for(let i=0;i<e;i++)if(n(i)>t)return u(i);return c()}})(o))}),(()=>this._handleNetworkError()))},nextChunk:t=>{const s=r(),a=t?t.chunkIdx+1:0,n=a-i.fragIndex;if(!(s<=0)){if(!t||n<0||n-s>10)return e(`Resync: offset=${n} bChunks=${s} chunk=`+JSON.stringify(t)),c();if(!(n>=s))return u(a-i.fragIndex,!1)}}}},y=()=>{n=!1,d&&d.abort(),u&&u.abort(),h&&h.abort(),l(this.filesFetcher),this.filesFetcher.abortAll()};return c={start:e=>{const{videoElement:i,logger:s}=this.params;let a,d,u,c,v,g,T,E=b(t.jidxUrl),w=0;const $=()=>{v&&(clearTimeout(v),v=void 0);const t=Math.max(500,1e3*(this._getBufferSizeSec()-this.sourceJitter-5)),e=w+t,i=Vc(),s=Math.min(1e4,e-i);w=i;const r=()=>{h||p()&&E.seek((()=>{p()&&(w=Vc(),P(),$())}))};s>0?v=window.setTimeout((()=>{this.paused?$():r()}),s):r()},P=()=>{let e;for(;e=E.nextChunk(c);)c=e,R(e);const i=E.nextChunk(u);if(i){if(u&&i.discontinuity)return s('Detected discontinuity; restarting playback'),void(this.paused?$():(y(),this._initPlayerWith(t)));D(i)}else $()},A=(t,e)=>{if(!p()||!this.sourceBuffer)return;let r,a,n;const o=i=>{window.setTimeout((()=>{p()&&A(t,e)}),i)};if(this.sourceBuffer.updating)s('Source buffer is updating; delaying appendBuffer'),o(100);else{const d=Vc(),u=i.currentTime;!this.paused&&i.buffered.length>1&&g===u&&d-T>500&&(s('Stall suspected; trying to fix'),this._fixupStall()),g!==u&&(g=u,T=d);const h=this._getBufferSizeSec();if(h>30)s(`Buffered ${h} seconds; delaying appendBuffer`),o(2e3);else try{this.sourceBuffer.appendBuffer(t),this.videoPlayStarted?(this.bufferStates.push({ts:d,buf:h}),S(),this.bufferStates.length>200&&this.bufferStates.shift()):this.shouldPlay()&&(this.videoPlayStarted=!0,this._playVideoElement()),e&&e()}catch(t){if('QuotaExceededError'!==t.name)throw t;s('QuotaExceededError; delaying appendBuffer'),n=this.sourceBuffer.buffered.length,0!==n&&(r=this.sourceBuffer.buffered.start(0),a=u,a-r>4&&this.sourceBuffer.remove(r,a-3)),o(1e3)}}},k=()=>{d&&a&&(s([`Appending chunk, sz=${d.byteLength}:`,JSON.stringify(u)]),A(d,(function(){d=null,P()})))},_=e=>t.fragUrlTemplate.replace('%%id%%',e.chunkIdx),D=t=>{p()&&m(_(t),((e,i)=>{if(p()){if(i/=1e3,d=e,u=t,o=t.startTS,i){const e=Math.min(10,t.dur/i);this.downloadRate=this.downloadRate?.7*this.downloadRate+.3*e:e}k()}}),(()=>this._handleNetworkError()))},R=t=>{p()&&(l(this.filesFetcher),this.filesFetcher.prefetch(this.urlResolver.resolve(_(t),!1)))},I=e=>{p()&&(t.cachedHeader=e,A(e,(()=>{a=!0,k()})))};n=!0,E.seek((t=>{p()&&(w=Vc(),t?(c=t,!r(e)||t.startTS>e?D(t):(u=t,P())):$())}),e),t.cachedHeader?I(t.cachedHeader):f(t.headerUrl,I,(()=>this._handleNetworkError()))},stop:y,getTimestampSec:()=>o},c}_switchToQuality(t){const{logger:e,playerCallback:i}=this.params;let r;t.bitrate!==this.bitrate&&(this.rep&&(r=this.rep.getTimestampSec(),s(r)&&(r+=.1),this.rep.stop()),this.currentManifestEntry=t,this.rep=this._representation(t),e(`switch to quality: codecs=${t.codecs}; headerUrl=${t.headerUrl}; bitrate=${t.bitrate}`),this.bitrate=t.bitrate,l(this.bitrateSwitcher),this.bitrateSwitcher.notifySwitch(this.bitrate),this.rep.start(r),i({name:'qualitySwitch',quality:t}))}_qualityAvailable(t){return s(this.manifest.find((e=>e.name===t)))}_initBitrateSwitcher(){const{logger:t,playerCallback:e}=this.params,i=e=>{if(!this.autoQuality)return;let i,s,r;this.currentManifestEntry&&this._qualityAvailable(this.currentManifestEntry.name)&&e<this.bitrate&&(s=this._getBufferSizeSec(),r=e/this.bitrate,s>10&&r>.8||s>15&&r>.5||s>20&&r>.3)?t(`Not switching: buffer=${Math.floor(s)}; bitrate=${this.bitrate}; newRate=${Math.floor(e)}`):(i=this._selectQuality(e),i?this._switchToQuality(i):t(`Could not find quality by bitrate ${e}`))},s=(()=>({updateChunk:(t,i)=>{const s=Vc();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&&Fc(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=Vc();t<r&&(a=e),r=t}}}_fetchManifest(t,e,i){this.manifestRequest=qc(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;ms(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 zc;!function(t){t.STOPPED='stopped',t.MANIFEST_READY='manifest_ready',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(zc||(zc={}));const Qc=[zc.PAUSED,zc.PLAYING,zc.READY],Wc=[zc.PAUSED,zc.PLAYING,zc.READY];class Jc{constructor(e){this.subscription=new i,this.videoState=new js(zc.STOPPED),this.representations$=new t([]),this.textTracksManager=new ys,this.maxSeekBackTime$=new t(1/0),this.zeroTime$=new t(void 0),this.liveOffset=new Oc,this._dashCb=t=>{var e,i,r,a;switch(t.name){case'buffering':{const e=t.isBuffering;this.params.output.isBuffering$.next(e);break}case'error':this.params.output.error$.next({id:`DashLiveProviderInternal:${t.type}`,message:'LiveDashPlayer reported error'});break;case'manifest':{const s=t.manifest,a=[];for(const t of s){const s=null!==(e=t.name)&&void 0!==e?e:t.index.toString(10),r=null!==(i=_s(t.name))&&void 0!==i?i:Os(t.video),n=t.bitrate/1e3,o=Object.assign({},t.video);if(!r)continue;const d={id:s,quality:r,bitrate:n,size:o};a.push({track:d,representation:t})}this.representations$.next(a),this.params.output.availableVideoTracks$.next(a.map((({track:t})=>t))),(null===(r=this.videoState.getTransition())||void 0===r?void 0:r.to)===zc.MANIFEST_READY&&this.videoState.setState(zc.MANIFEST_READY);break}case'qualitySwitch':{const e=t.quality,i=null===(a=this.representations$.getValue().find((({representation:t})=>t===e)))||void 0===a?void 0:a.track;this.params.output.hostname$.next(new URL(e.headerUrl,this.params.source.url).hostname),s(i)&&this.params.output.currentVideoTrack$.next(i);break}case'bandwidth':{const{size:e,duration:i}=t;this.params.dependencies.throughputEstimator.addRawSpeed(e,i);break}case'index':this.maxSeekBackTime$.next(t.shiftDuration),this.zeroTime$.next(t.zeroTime)}},this.syncPlayback=()=>{var t;const e=this.videoState.getState(),i=this.videoState.getTransition(),r=this.params.desiredState.playbackState.getState(),a=this.params.desiredState.playbackState.getTransition(),o=this.params.desiredState.seekPosition.getTransition();if(this.log({message:`[syncPlayback] videoState: ${e}; videoTransition: ${JSON.stringify(i)}; desiredPlaybackState: ${r}; seekPositionTransition: ${JSON.stringify(o)};`}),r===P.STOPPED)return void(e!==zc.STOPPED&&(this.videoState.startTransitionTo(zc.STOPPED),this.dash.destroy(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(zc.STOPPED)));if(i)return;if(Wc.includes(e)){const e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to;s(e)&&this.setVideoTrack(e);const i=this.params.desiredState.autoVideoTrackSwitching.getTransition();i&&this.setAutoQuality(i.to)}const d=null==o?void 0:o.to;if((null==a?void 0:a.to)!==P.PAUSED&&s(d)&&Qc.includes(e))this.seek(d+Kc(this.liveOffset.getTotalPausedTime()));else switch(e){case zc.STOPPED:return this.videoState.startTransitionTo(zc.MANIFEST_READY),void this.dash.attachSource(vc(this.params.source.url));case zc.MANIFEST_READY:this.videoState.startTransitionTo(zc.READY),this.prepare();break;case zc.READY:return void(r===P.PAUSED?this.videoState.setState(zc.PAUSED):r===P.PLAYING&&(this.videoState.startTransitionTo(zc.PLAYING),this.dash.play((()=>{this.liveOffset.pause(),this.videoState.setState(zc.PAUSED)}))));case zc.PLAYING:return void(r===P.PAUSED&&(this.videoState.startTransitionTo(zc.PAUSED),this.liveOffset.pause(),this.dash.pause()));case zc.PAUSED:return void(r===P.PLAYING&&(this.videoState.startTransitionTo(zc.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(zc.PAUSED)})),this.params.output.position$.next(Kc(this.liveOffset.getTotalOffset()))):this.seek(Kc(this.liveOffset.getTotalOffset()))));default:return n(e)}},this.params=e,this.log=this.params.dependencies.logger.createComponentLog('DashLiveProvider');const r=t=>{e.output.error$.next({id:'DashLiveProvider',message:'DashLiveProvider internal logic error',thrown:t})};o(this.videoState.stateChangeStarted$.pipe(u((t=>({transition:t,type:'start'})))),this.videoState.stateChangeEnded$.pipe(u((t=>({transition:t,type:'end'}))))).subscribe((({transition:t,type:e})=>{this.log({message:`[videoState change] ${e}: ${JSON.stringify(t)}`})})),this.video=Ts(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(Gs(this.params.source.url)),this.params.output.autoVideoTrackLimitingAvailable$.next(!0),this.textTracksManager.connect(this.video,this.params.desiredState,this.params.output);const a=As(this.video);this.subscription.add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===zc.READY&&this.videoState.setState(zc.READY)}),r)).add(a.pause$.subscribe((()=>{this.videoState.setState(zc.PAUSED)}),r)).add(a.playing$.subscribe((()=>{this.videoState.setState(zc.PLAYING)}),r)).add(a.error$.subscribe(this.params.output.error$)).add(this.maxSeekBackTime$.pipe(c(),u(Kc)).subscribe(this.params.output.duration$)).add(y({zeroTime:this.zeroTime$.pipe(S(s)),position:a.timeUpdate$}).subscribe((({zeroTime:t,position:e})=>this.params.output.liveTime$.next(t+1e3*e)),r)).add(gs(this.video,this.params.desiredState.isLooped,r)).add(Ss(this.video,this.params.desiredState.volume,a.volumeState$,r)).add(a.volumeState$.subscribe(this.params.output.volume$,r)).add(Ps(this.video).subscribe(this.params.output.firstBytesEvent$)).add(Es(this.video).subscribe(this.params.output.firstFrameEvent$)).add(this.params.desiredState.autoVideoTrackLimits.stateChangeEnded$.subscribe((({to:{max:t}})=>{const e=t&&Rs[t].height;this.dash.setMaxAutoQuality(e)}))).add(this.videoState.stateChangeEnded$.subscribe((t=>{switch(t.to){case zc.STOPPED:this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.desiredState.playbackState.setState(P.STOPPED);break;case zc.MANIFEST_READY:case zc.READY:break;case zc.PAUSED:this.params.desiredState.playbackState.setState(P.PAUSED);break;case zc.PLAYING:this.params.desiredState.playbackState.setState(P.PLAYING);break;default:return n(t.to)}}),r)).add(o(e.desiredState.playbackState.stateChangeStarted$,e.desiredState.seekPosition.stateChangeStarted$,e.desiredState.videoTrack.stateChangeStarted$,e.desiredState.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0)).subscribe(this.syncPlayback,r))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0),this.dash.destroy()}createLiveDashPlayer(){const t=new jc({videoElement:this.video,config:{CHUNK_DURATION:this.params.config.chunkDuration,BUFFER_OPTIMAL_DURATION:this.params.config.optimalBufferDuration,MAX_PARALLEL_REQUESTS:this.params.config.maxParallelRequests},playerCallback:this._dashCb,logger:t=>{this.params.dependencies.logger.log({message:String(t),component:'LiveDashPlayer'})}});return t.pause(),t}prepare(){var t,e,i,r,a,n;const o=this.representations$.getValue(),d=null!==(e=null===(t=this.params.desiredState.videoTrack.getTransition())||void 0===t?void 0:t.to)&&void 0!==e?e:this.params.desiredState.videoTrack.getState(),u=null!==(r=null===(i=this.params.desiredState.autoVideoTrackSwitching.getTransition())||void 0===i?void 0:i.to)&&void 0!==r?r:this.params.desiredState.autoVideoTrackSwitching.getState(),h=!u&&s(d)?d:null===(a=Hs(o.map((({track:t})=>t)),{container:{width:this.video.offsetWidth,height:this.video.offsetHeight},throughput:this.params.dependencies.throughputEstimator.throughput$.getValue(),tuning:this.params.tuning.autoTrackSelection,limits:this.params.desiredState.autoVideoTrackLimits.getState()}))||void 0===a?void 0:a.id,c=null===(n=o.find((({track:t})=>t.id===h)))||void 0===n?void 0:n.representation;l(c),this.dash.startPlay(c,u),this.params.desiredState.videoTrack.getTransition()&&this.params.desiredState.videoTrack.setState(h),this.params.desiredState.autoVideoTrackSwitching.getTransition()&&this.params.desiredState.autoVideoTrackSwitching.setState(u)}setVideoTrack(t){var e;const i=null===(e=this.representations$.getValue().find((({track:e})=>e.id===t)))||void 0===e?void 0:e.representation;l(i),this.dash.switchByName(i.name),this.params.desiredState.videoTrack.setState(t)}setAutoQuality(t){this.dash.setAutoQualityEnabled(t),this.params.desiredState.autoVideoTrackSwitching.setState(t)}seek(t){this.log({message:`[seek] position: ${t}`}),this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(Kc(i)),this.dash.reinit(vc(this.params.source.url,i)),this.params.output.seekedEvent$.next()}}const Kc=t=>-t/1e3,Xc=t=>{let e=null;if(t.QUALITY&&(e=_s(t.QUALITY)),!e&&t.RESOLUTION){const[i,s]=t.RESOLUTION.split('x').map((t=>parseInt(t,10)));e=Os({width:i,height:s})}return null!=e?e:null},Zc=(t,e=t)=>O(void 0,void 0,void 0,(function*(){var i;const s=yield Vo(fetch).fetch(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=Po(s[1].split(',').map((t=>t.split('=')))),o=null!==(i=n.QUALITY)&&void 0!==i?i:`stream-${n.BANDWIDTH}`,d=Xc(n);let u;n.BANDWIDTH&&(u=parseInt(n.BANDWIDTH,10)/1e3||void 0),!u&&n['AVERAGE-BANDWIDTH']&&(u=parseInt(n['AVERAGE-BANDWIDTH'],10)/1e3||void 0);const h=n['FRAME-RATE']?parseFloat(n['FRAME-RATE']):void 0;let c;if(n.RESOLUTION){const[t,e]=n.RESOLUTION.split('x').map((t=>parseInt(t,10)));t&&e&&(c={width:t,height:e})}const l=new URL(r[++t],e).toString();d&&a.push({id:o,quality:d,url:l,bandwidth:u,size:c,fps:h})}return a}));var tl;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(tl||(tl={}));class el{constructor(e){this.subscription=new i,this.videoState=new js(tl.STOPPED),this.textTracksManager=new ys,this.manifests$=new t([]),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==tl.STOPPED&&(this.videoState.startTransitionTo(tl.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(tl.STOPPED),Ds(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===tl.STOPPED)return this.videoState.startTransitionTo(tl.READY),void this.prepare();if(a||o){const t=this.videoState.getState();this.videoState.setState(tl.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const{currentTime:e}=this.video;return this.prepare(),void(d&&!r(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const u=null==d?void 0:d.to;switch((null==i?void 0:i.to)!==P.PAUSED&&s(u)&&this.seek(u),t){case tl.READY:return void(e===P.PAUSED?(this.videoState.setState(tl.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(tl.PLAYING),this.playIfAllowed()));case tl.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(tl.PAUSED),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Ds(this.params.desiredState.playbackState,P.PLAYING));case tl.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(tl.PLAYING),this.playIfAllowed()):(null==i?void 0:i.to)===P.PAUSED&&Ds(this.params.desiredState.playbackState,P.PAUSED));case tl.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=Ts(e.container),this.params.output.element$.next(this.video);const a={id:'master',quality:ks.INVARIANT,url:this.params.source.url};this.manifests$.next([a]),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Gs(this.params.source.url)),Zc(this.params.source.url).then((t=>{this.manifests$.next([a,...t])}),(t=>this.params.output.error$.next({id:'ExtractHlsQualities',message:'Error fetching manifest and extracting qualities',thrown:t}))),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsProvider',message:'HlsProvider internal logic error',thrown:e})},r=As(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e));a(r.timeUpdate$,t.position$),a(r.durationChange$,t.duration$),a(r.ended$,t.endedEvent$),a(r.looped$,t.loopedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.firstBytes$,t.firstBytesEvent$),a(r.firstFrame$,t.firstFrameEvent$),a(r.seeked$,t.seekedEvent$),this.subscription.add(gs(this.video,e.isLooped,i)),this.subscription.add(Ss(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(tl.PLAYING),Ds(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(tl.PAUSED),Ds(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===tl.READY&&this.videoState.setState(tl.READY),this.videoState.getState()===tl.PLAYING&&this.playIfAllowed()}),i).add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Gs(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===tl.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&s(t.to)&&this.seek(t.to)}),i))),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();r(t)||(this.video.setAttribute('src',t.url),this.video.load())}playIfAllowed(){ms(this.video).then((t=>{t||(this.videoState.setState(tl.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}}var il;!function(t){t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.CHANGING_MANIFEST='changing_manifest',t.PAUSED='paused'}(il||(il={}));class sl{constructor(e){var a;this.subscription=new i,this.videoState=new js(il.STOPPED),this.textTracksManager=new ys,this.manifests$=new t([]),this.liveOffset=new Oc,this.manifestStartTime$=new t(void 0),this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),a=this.params.desiredState.videoTrack.getTransition(),o=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(e===P.STOPPED)return void(t!==il.STOPPED&&(this.videoState.startTransitionTo(il.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(il.STOPPED),Ds(this.params.desiredState.playbackState,P.STOPPED,!0)));if(this.videoState.getTransition())return;const d=this.params.desiredState.seekPosition.getTransition();if(t===il.STOPPED)return this.videoState.startTransitionTo(il.READY),void this.prepare();if(a||o){const t=this.videoState.getState();this.videoState.setState(il.CHANGING_MANIFEST),this.videoState.startTransitionTo(t);const e=rl(this.liveOffset.getTotalOffset());return this.prepare(),void(d&&!r(d.to)||this.params.desiredState.seekPosition.startTransitionTo(e))}const u=null==d?void 0:d.to;if((null==i?void 0:i.to)!==P.PAUSED&&s(u))return this.videoState.startTransitionTo(il.READY),this.seek(u+rl(this.liveOffset.getTotalPausedTime())),void this.prepare();switch(t){case il.READY:return void(e===P.PAUSED?(this.videoState.setState(il.PAUSED),this.liveOffset.pause(),Ds(this.params.desiredState.playbackState,P.PAUSED)):e===P.PLAYING&&(this.videoState.startTransitionTo(il.PLAYING),this.playIfAllowed()));case il.PLAYING:return void(e===P.PAUSED?(this.videoState.startTransitionTo(il.PAUSED),this.liveOffset.pause(),this.video.pause()):(null==i?void 0:i.to)===P.PLAYING&&Ds(this.params.desiredState.playbackState,P.PLAYING));case il.PAUSED:return void(e===P.PLAYING?(this.videoState.startTransitionTo(il.PLAYING),this.liveOffset.getTotalPausedTime()<this.params.config.maxPausedTime&&this.liveOffset.getTotalOffset()<this.maxSeekBackTime$.getValue()?(this.liveOffset.resume(),this.playIfAllowed(),this.params.output.position$.next(rl(this.liveOffset.getTotalOffset()))):this.seek(rl(this.liveOffset.getTotalOffset()))):(null==i?void 0:i.to)===P.PAUSED&&(Ds(this.params.desiredState.playbackState,P.PAUSED),this.liveOffset.pause()));case il.CHANGING_MANIFEST:break;default:return n(t)}},this.params=e,this.video=Ts(e.container),this.params.output.element$.next(this.video);const o={id:'master',quality:ks.INVARIANT,url:this.params.source.url};this.manifests$.next([o]),Zc(vc(this.params.source.url)).then((t=>{this.manifests$.next([o,...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(Gs(this.params.source.url)),this.maxSeekBackTime$=new t(null!==(a=e.source.maxSeekBackTime)&&void 0!==a?a:1/0),this.subscribe()}selectManifest(){var t,e;const{autoVideoTrackSwitching:i,videoTrack:s}=this.params.desiredState,r=i.getState(),a=s.getTransition(),n=null!==(e=null!==(t=null==a?void 0:a.to)&&void 0!==t?t:s.getState())&&void 0!==e?e:'master',o=this.manifests$.getValue();if(!o)return;const d=r?'master':n;return r&&!a&&s.startTransitionTo('master'),o.find((t=>t.id===d))}subscribe(){const{output:t,desiredState:e}=this.params,i=e=>{t.error$.next({id:'HlsLiveProvider',message:'HlsLiveProvider internal logic error',thrown:e})},r=As(this.video),a=(t,e)=>this.subscription.add(t.subscribe(e,i));a(r.ended$,t.endedEvent$),a(r.error$,t.error$),a(r.isBuffering$,t.isBuffering$),a(r.currentBuffer$,t.currentBuffer$),a(r.firstBytes$,t.firstBytesEvent$),a(r.firstFrame$,t.firstFrameEvent$),this.subscription.add(e.isLooped.stateChangeStarted$.subscribe((()=>e.isLooped.setState(!1)),i)),this.subscription.add(Ss(this.video,e.volume,r.volumeState$,i)),this.subscription.add(r.volumeState$.subscribe(this.params.output.volume$,i)),this.textTracksManager.connect(this.video,e,t),this.subscription.add(r.playing$.subscribe((()=>{this.videoState.setState(il.PLAYING),Ds(e.playbackState,P.PLAYING)}),i)).add(r.pause$.subscribe((()=>{this.videoState.setState(il.PAUSED),Ds(e.playbackState,P.PAUSED)}),i)).add(r.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===il.READY&&this.videoState.setState(il.READY),this.videoState.getState()===il.PLAYING&&this.playIfAllowed()}),i)),this.subscription.add(this.maxSeekBackTime$.pipe(c(),u(rl)).subscribe(this.params.output.duration$,i)),this.subscription.add(r.loadedMetadata$.subscribe((()=>{const t=this.params.desiredState.seekPosition.getTransition(),e=this.videoState.getTransition(),i=this.params.desiredState.videoTrack.getTransition(),r=this.params.desiredState.autoVideoTrackSwitching.getTransition();if(i&&s(i.to)){const t=i.to;this.params.desiredState.videoTrack.setState(t);const e=this.manifests$.getValue().find((e=>e.id===t));e&&(this.params.output.currentVideoTrack$.next(e),this.params.output.hostname$.next(Gs(e.url)))}r&&this.params.desiredState.autoVideoTrackSwitching.setState(r.to),e&&e.from===il.CHANGING_MANIFEST&&this.videoState.setState(e.to),t&&s(t.to)&&this.seek(t.to)}),i)),this.subscription.add(r.loadedData$.subscribe((()=>{var t,e;const i=null===(e=null===(t=this.video)||void 0===t?void 0:t.getStartDate())||void 0===e?void 0:e.getTime();this.manifestStartTime$.next(i||void 0)}),i)),this.subscription.add(y({startTime:this.manifestStartTime$.pipe(S(s)),currentTime:r.timeUpdate$}).subscribe((({startTime:t,currentTime:e})=>this.params.output.liveTime$.next(t+1e3*e)),i)),this.subscription.add(this.manifests$.pipe(u((t=>t.map((({id:t,quality:e,size:i,bandwidth:s,fps:r})=>({id:t,quality:e,size:i,fps:r,bitrate:s})))))).subscribe(this.params.output.availableVideoTracks$,i));const n=o(e.playbackState.stateChangeStarted$,e.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,e.videoTrack.stateChangeStarted$,e.autoVideoTrackSwitching.stateChangeStarted$,h(['init'])).pipe(m(0));this.subscription.add(n.subscribe(this.syncPlayback,i))}destroy(){this.subscription.unsubscribe(),this.textTracksManager.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}prepare(){const t=this.selectManifest();if(r(t))return;const e=vc(t.url,this.liveOffset.getTotalOffset());var i;this.video.setAttribute('src',e),this.video.load(),(i=e,O(void 0,void 0,void 0,(function*(){const t=yield Vo(fetch).fetch(i,{method:'HEAD'});return t.headers.has('X-Playback-Duration')?parseInt(t.headers.get('X-Playback-Duration'),10):void 0}))).then((t=>{r(t)||this.maxSeekBackTime$.next(t)}))}playIfAllowed(){ms(this.video).then((t=>{t||(this.videoState.setState(il.PAUSED),this.liveOffset.pause(),Ds(this.params.desiredState.playbackState,P.PAUSED,!0))}))}seek(t){this.params.output.willSeekEvent$.next();const e=-Math.round(1e3*t),i=e<this.maxSeekBackTime$.getValue()?e:0;this.liveOffset.resetTo(i),this.params.output.position$.next(rl(i)),this.params.output.seekedEvent$.next()}}const rl=t=>-t/1e3,al={};var nl;!function(t){t.INITIALIZING='initializing',t.STOPPED='stopped',t.READY='ready',t.PLAYING='playing',t.PAUSED='paused'}(nl||(nl={}));const ol=(t,e)=>new p((i=>{const s=(t,e)=>i.next(e);return t.on(e,s),()=>t.off(e,s)}));class dl{constructor(t){this.subscription=new i,this.videoState=new js(nl.INITIALIZING),this.textTracksManager=new ys,this.trackLevels=new Map,this.syncPlayback=()=>{const t=this.videoState.getState(),e=this.params.desiredState.playbackState.getState(),i=this.params.desiredState.playbackState.getTransition(),r=this.params.desiredState.seekPosition.getTransition();if(t===nl.INITIALIZING)return;const a=null==r?void 0:r.to;switch((null==i?void 0:i.to)!==P.PAUSED&&s(a)&&this.seek(a),e){case P.STOPPED:switch(t){case nl.STOPPED:break;case nl.READY:case nl.PLAYING:case nl.PAUSED:this.stop();break;default:n(t)}break;case P.PLAYING:switch(t){case nl.PLAYING:break;case nl.STOPPED:this.prepare();break;case nl.READY:case nl.PAUSED:this.playIfAllowed();break;default:n(t)}break;case P.PAUSED:switch(t){case nl.PAUSED:break;case nl.STOPPED:this.prepare();break;case nl.READY:this.videoState.setState(nl.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED);break;case nl.PLAYING:this.pause();break;default:n(t)}break;default:n(e)}},this.video=Ts(t.container),this.params=t,this.params.output.element$.next(this.video),this.params.output.isLive$.next(!1),this.params.output.hostname$.next(Gs(this.params.source.url)),this.loadHlsJs()}destroy(){var t,e;this.subscription.unsubscribe(),this.trackLevels.clear(),this.textTracksManager.destroy(),null===(t=this.hls)||void 0===t||t.detachMedia(),null===(e=this.hls)||void 0===e||e.destroy(),this.video.remove(),this.params.output.element$.next(void 0)}loadHlsJs(){let t=!1;const e=e=>{t||this.params.output.error$.next({id:'timeout'===e?'HlsJsTimeout':'HlsJsLoadError',message:'Failed to load Hls.js',thrown:e}),t=!0},i=window.setTimeout((()=>e('timeout')),5e3);Yh(import('hls.js').then((e=>{t||(al.Hls=e.default,al.Events=e.default.Events,this.init())}),e),(()=>{window.clearTimeout(i),t=!0}))}init(){l(al.Hls,'hls.js not loaded'),this.hls=new al.Hls({fragLoadingMaxRetry:5,levelLoadingMaxRetry:2,manifestLoadingMaxRetry:2,fragLoadingMaxRetryTimeout:16e3,manifestLoadingMaxRetryTimeout:2e3,levelLoadingMaxRetryTimeout:2e3}),this.subscribe(),this.videoState.setState(nl.STOPPED)}subscribe(){l(al.Events,'hls.js not loaded');const{desiredState:t,output:e}=this.params,i=t=>{e.error$.next({id:'HlsJsProvider',message:'HlsJsProvider internal logic error',thrown:t})},a=As(this.video),n=(t,e)=>this.subscription.add(t.subscribe(e,i));n(a.timeUpdate$,e.position$),n(a.durationChange$,e.duration$),n(a.ended$,e.endedEvent$),n(a.looped$,e.loopedEvent$),n(a.error$,e.error$),n(a.isBuffering$,e.isBuffering$),n(a.currentBuffer$,e.currentBuffer$),n(a.firstBytes$,e.firstBytesEvent$),n(a.firstFrame$,e.firstFrameEvent$),n(a.seeked$,e.seekedEvent$),this.subscription.add(gs(this.video,t.isLooped,i)),this.subscription.add(Ss(this.video,t.volume,a.volumeState$,i)),this.subscription.add(a.volumeState$.subscribe(this.params.output.volume$)),this.subscription.add(ol(this.hls,al.Events.ERROR).subscribe((t=>{var i;t.fatal&&e.error$.next({id:['HlsJsFatal',t.type,t.details].join('_'),message:`HlsJs fatal ${t.type} ${t.details}, ${null===(i=t.err)||void 0===i?void 0:i.message} ${t.reason}`,thrown:t.error})}))),this.subscription.add(a.playing$.subscribe((()=>{this.videoState.setState(nl.PLAYING),Ds(t.playbackState,P.PLAYING)}),i)).add(a.pause$.subscribe((()=>{this.videoState.setState(nl.PAUSED),Ds(t.playbackState,P.PAUSED)}),i)).add(a.canplay$.subscribe((()=>{var t;(null===(t=this.videoState.getTransition())||void 0===t?void 0:t.to)===nl.READY&&this.videoState.setState(nl.READY),this.videoState.getState()===nl.PLAYING&&this.playIfAllowed()}),i)),n(ol(this.hls,al.Events.MANIFEST_PARSED).pipe(u((({levels:t})=>t.reduce(((t,e)=>{var i,s;const r=e.name||e.height.toString(10),{width:a,height:n}=e,o=null!==(s=_s(null!==(i=e.attrs.QUALITY)&&void 0!==i?i:''))&&void 0!==s?s:Os({width:a,height:n});if(!o)return t;const d=e.attrs['FRAME-RATE']?parseFloat(e.attrs['FRAME-RATE']):void 0,u={id:r.toString(),quality:o,bitrate:e.bitrate/1e3,size:{width:a,height:n},fps:d};return this.trackLevels.set(r,{track:u,level:e}),t.push(u),t}),[])))),e.availableVideoTracks$),n(ol(this.hls,al.Events.LEVEL_LOADING).pipe(u((({url:t})=>Gs(t)))),e.hostname$),this.subscription.add(vs(t.autoVideoTrackSwitching,(()=>this.hls.autoLevelEnabled),(t=>{this.hls.nextLevel=t?-1:this.hls.currentLevel,this.hls.loadLevel=t?-1:this.hls.loadLevel}),{onError:i}));const d=t=>{var e;return null===(e=Array.from(this.trackLevels.values()).find((({level:e})=>e===t)))||void 0===e?void 0:e.track},c=ol(this.hls,al.Events.LEVEL_SWITCHED).pipe(u((({level:t})=>d(this.hls.levels[t]))));c.pipe(S(s)).subscribe(e.currentVideoTrack$,i),this.subscription.add(vs(t.videoTrack,(()=>{var t;return null===(t=d(this.hls.levels[this.hls.currentLevel]))||void 0===t?void 0:t.id}),(t=>{var e;if(r(t))return;const i=null===(e=this.trackLevels.get(t))||void 0===e?void 0:e.level;if(!i)return;const s=this.hls.levels.indexOf(i),a=this.hls.currentLevel,n=this.hls.levels[a];!n||i.bitrate>n.bitrate?this.hls.nextLevel=s:(this.hls.loadLevel=s,this.hls.loadLevel=s)}),{changed$:c.pipe(u((t=>null==t?void 0:t.id))),onError:i})),n(a.progress$,(()=>{this.params.dependencies.throughputEstimator.addRawThroughput(this.hls.bandwidthEstimate/1e3)})),this.textTracksManager.connect(this.video,t,e);const p=o(t.playbackState.stateChangeStarted$,t.videoTrack.stateChangeStarted$,t.seekPosition.stateChangeStarted$,this.videoState.stateChangeEnded$,h(['init'])).pipe(m(0));this.subscription.add(p.subscribe(this.syncPlayback,i))}prepare(){this.videoState.startTransitionTo(nl.READY),this.hls.attachMedia(this.video),this.hls.loadSource(this.params.source.url)}playIfAllowed(){return O(this,void 0,void 0,(function*(){this.videoState.startTransitionTo(nl.PLAYING);(yield ms(this.video))||(this.videoState.setState(nl.PAUSED),Ds(this.params.desiredState.playbackState,P.PAUSED,!0))}))}pause(){this.videoState.startTransitionTo(nl.PAUSED),this.video.pause()}seek(t){this.params.output.willSeekEvent$.next(),this.video.currentTime=t}stop(){this.params.output.position$.next(0),this.params.output.duration$.next(1/0),this.params.output.currentBuffer$.next(void 0),this.params.output.hostname$.next(void 0),this.hls.stopLoad(),this.hls.detachMedia(),this.video.setAttribute('src',''),this.video.load(),this.videoState.setState(nl.STOPPED),Ds(this.params.desiredState.playbackState,P.STOPPED,!0)}}class ul{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 hl,cl,ll,pl,fl,ml,vl,gl,Sl,bl,yl,Tl,El,wl,$l,Pl,Al;const kl=(()=>{const{userAgent:t}=window.navigator;return!/chrome/i.test(t)&&/webkit|safari|khtml/i.test(t)})(),_l=(null===(hl=null===navigator||void 0===navigator?void 0:navigator.userAgentData)||void 0===hl?void 0:hl.mobile)||/Mobile|mini|Fennec|Android|iP(ad|od|hone)/.test(navigator.appVersion),Dl=document.createElement('video'),Rl={mse:Boolean(window.MediaSource&&window.MediaStreamTrack&&(null===(ll=null===(cl=window.SourceBuffer)||void 0===cl?void 0:cl.prototype)||void 0===ll?void 0:ll.appendBuffer)),hls:Boolean((null===(pl=Dl.canPlayType)||void 0===pl?void 0:pl.call(Dl,'application/x-mpegurl'))||(null===(fl=Dl.canPlayType)||void 0===fl?void 0:fl.call(Dl,'vnd.apple.mpegURL')))},Il={mp4:Boolean(null===(ml=Dl.canPlayType)||void 0===ml?void 0:ml.call(Dl,'video/mp4')),webm:Boolean(null===(vl=Dl.canPlayType)||void 0===vl?void 0:vl.call(Dl,'video/webm'))},Ll={h264:Boolean(null===(Sl=null===(gl=window.MediaSource)||void 0===gl?void 0:gl.isTypeSupported)||void 0===Sl?void 0:Sl.call(gl,'video/mp4; codecs="avc1.42000a,mp4a.40.2"')),h265:Boolean(null===(yl=null===(bl=window.MediaSource)||void 0===bl?void 0:bl.isTypeSupported)||void 0===yl?void 0:yl.call(bl,'video/mp4; codecs="hev1.1.6.L93.B0"')),vp9:Boolean(null===(El=null===(Tl=window.MediaSource)||void 0===Tl?void 0:Tl.isTypeSupported)||void 0===El?void 0:El.call(Tl,'video/webm; codecs="vp9"')),aac:Boolean(null===($l=null===(wl=window.MediaSource)||void 0===wl?void 0:wl.isTypeSupported)||void 0===$l?void 0:$l.call(wl,'audio/mp4; codecs="mp4a.40.2"')),opus:Boolean(null===(Al=null===(Pl=window.MediaSource)||void 0===Pl?void 0:Pl.isTypeSupported)||void 0===Al?void 0:Al.call(Pl,'audio/webm; codecs="opus"'))},xl=(Ll.h264||Ll.h265)&&Ll.aac,Ol=!kl,Cl=_l||kl,Nl=!Rl.hls||!Cl,Ml=3e4,Bl=18e4,Ul=3,Vl=100,Fl={cacheDuration:12e4},Hl={maxPausedTime:3e4,chunkDuration:5e3,optimalBufferDuration:1e4,maxParallelRequests:5},ql={maxPausedTime:3e4},Gl={maxPausedTime:3e4};class Yl{constructor(r){this.current$=new t({type:void 0}),this.providerError$=new e,this.noAvailableProvidersError$=new e,this.providerOutput={position$:new t(0),duration$:new t(1/0),volume$:new t({muted:!1,volume:1}),currentVideoTrack$:new t(void 0),availableVideoTracks$:new t([]),autoVideoTrackLimitingAvailable$:new t(!1),currentBuffer$:new t(void 0),isBuffering$:new t(!0),error$:new e,willSeekEvent$:new e,seekedEvent$:new e,loopedEvent$:new e,endedEvent$:new e,firstBytesEvent$:new e,firstFrameEvent$:new e,isLive$:new t(void 0),liveTime$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),element$:new t(void 0)},this.subscription=new i,this.params=r,this.log=this.params.dependencies.logger.createComponentLog('ProviderContainer');const{formatsToAvoid:a}=this.params.tuning,o=a.length?[...r.screenFormatsPriority.filter((t=>!a.includes(t))),...r.screenFormatsPriority.filter((t=>a.includes(t)))]:r.screenFormatsPriority;this.screenFormatsIterator=new ul(o.filter((t=>s(r.sources[t]))).filter((t=>{switch(t){case A.DASH:return Rl.mse&&Il.mp4&&xl&&Ol;case A.DASH_SEP:case A.DASH_SEP_VK:return Rl.mse&&Il.mp4&&xl;case A.DASH_WEBM:case A.DASH_WEBM_VK:case A.DASH_LIVE_WEBM:return Rl.mse&&Il.webm&&Ll.vp9&&Ll.opus;case A.DASH_LIVE:case A.DASH_ONDEMAND:return Rl.mse&&Il.mp4&&xl;case A.HLS:case A.HLS_LIVE:case A.HLS_ONDEMAND:return Rl.hls&&Il.mp4&&Cl;case A.HLS_JS:return Rl.mse&&Il.mp4&&xl&&Nl;case A.MPEG:return Il.mp4;default:return n(t)}}))),this.chromecastFormatsIterator=new ul(r.chromecastFormatsPriority.filter((t=>s(r.sources[t]))))}init(){this.subscription.add(this.initProviderErrorHandling()),this.subscription.add(this.params.dependencies.chromecastInitializer.connection$.subscribe((()=>{this.reinitProvider()})))}destroy(){this.destroyProvider(),this.current$.next({type:void 0}),this.subscription.unsubscribe()}initProvider(){const t=this.chooseDestination(),e=this.chooseFormat(t);if(r(e))return void this.handleNoFormatsError(t);let i;try{i=this.createProvider(t,e)}catch(t){this.providerError$.next({id:'ProviderNotConstructed',message:'Failed to create provider',thrown:t})}i?this.current$.next({type:e,provider:i,destination:t}):this.switchToNextProvider()}reinitProvider(){this.destroyProvider(),this.initProvider()}switchToNextProvider(){this.destroyProvider();const t=this.current$.getValue().destination;l(t),this.skipFormat(t),this.initProvider()}destroyProvider(){const t=this.current$.getValue().provider;if(!t)return;this.log({message:'destroyProvider'});const e=this.params.desiredState.seekPosition,i=e.getTransition();i?s(i.from)&&e.startTransitionTo(i.from):e.startTransitionTo(this.providerOutput.position$.getValue()),t.destroy();const r=this.providerOutput.isBuffering$;r.getValue()||r.next(!0)}createProvider(t,e){switch(this.log({message:`createProvider: ${t}:${e}`}),t){case k.SCREEN:return this.createScreenProvider(e);case k.CHROMECAST:return this.createChromecastProvider(e);default:return n(t)}}createScreenProvider(t){const{sources:e,container:i,desiredState:s}=this.params,r=this.providerOutput;switch(t){case A.DASH:{const a=e[t];return l(a),new Ac({container:i,source:a,desiredState:s,output:r,config:Fl,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_SEP_VK:case A.DASH_WEBM_VK:{const a=e[t];return l(a),new fc({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_SEP:case A.DASH_WEBM:case A.DASH_ONDEMAND:case A.DASH_LIVE_WEBM:{const a=e[t];return l(a),new Bc({container:i,source:a,desiredState:s,output:r,format:t,config:Gl,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.HLS:case A.HLS_ONDEMAND:{const a=e[t];return l(a),new el({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.HLS_LIVE:{const a=e[t];return l(a),new sl({container:i,source:a,desiredState:s,output:r,config:ql,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.HLS_JS:{const a=e[t];return l(a),new dl({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.MPEG:{const a=e[t];return l(a),new yc({container:i,source:a,desiredState:s,output:r,dependencies:this.params.dependencies,tuning:this.params.tuning})}case A.DASH_LIVE:{const a=e[t];return l(a),new Jc({container:i,source:a,desiredState:s,output:r,config:Hl,dependencies:this.params.dependencies,tuning:this.params.tuning})}default:return n(t)}}createChromecastProvider(t){const{sources:e,container:i,desiredState:s,meta:r}=this.params,a=this.providerOutput,n=this.params.dependencies.chromecastInitializer.connection$.getValue();return l(n),new Sc({connection:n,meta:r,container:i,source:e,format:t,desiredState:s,output:a,dependencies:this.params.dependencies,tuning:this.params.tuning})}chooseDestination(){return this.params.dependencies.chromecastInitializer.connection$.getValue()?k.CHROMECAST:k.SCREEN}chooseFormat(t){switch(t){case k.SCREEN:return this.screenFormatsIterator.isCompleted()?void 0:this.screenFormatsIterator.getValue();case k.CHROMECAST:return this.chromecastFormatsIterator.isCompleted()?void 0:this.chromecastFormatsIterator.getValue();default:return n(t)}}skipFormat(t){switch(t){case k.SCREEN:return this.screenFormatsIterator.next();case k.CHROMECAST:return this.chromecastFormatsIterator.next();default:return n(t)}}handleNoFormatsError(t){switch(t){case k.SCREEN:return this.noAvailableProvidersError$.next(),void this.current$.next({type:void 0});case k.CHROMECAST:return void this.params.dependencies.chromecastInitializer.disconnect();default:return n(t)}}initProviderErrorHandling(){let e=[],r=0;const a=new i;var n;return a.add(o(this.providerOutput.error$,(n={desiredPlaybackState$:this.params.desiredState.playbackState,maxTransitionInterval:Ml,position$:this.providerOutput.position$,providerChanged$:this.current$},new p((e=>{const s=new i,r=b(n.maxTransitionInterval),a=new t(void 0);o(n.desiredPlaybackState$.stateChangeStarted$.pipe(T(r)),n.desiredPlaybackState$.stateChangeEnded$.pipe(T(void 0)),n.providerChanged$.pipe(u((()=>a.getValue())))).subscribe(a);const d=new i;return s.add(d),s.add(a.subscribe((t=>{d.unsubscribe(),t&&d.add(t.subscribe(e))}))),s}))).pipe(T({id:'ProviderHangup',message:'An operation failed to complete within reasonable time'}))).subscribe(this.providerError$)),a.add(this.providerError$.pipe(E(Vl,{leading:!1,trailing:!0})).subscribe((()=>{const t=Date.now();this.current$.getValue().destination===k.CHROMECAST?(this.destroyProvider(),this.params.dependencies.chromecastInitializer.stopMedia().then((()=>{this.switchToNextProvider()}),(()=>{this.params.dependencies.chromecastInitializer.disconnect()}))):s(e[r])&&t<e[r]+Bl?(e=[],this.switchToNextProvider()):(e[r]=t,this.reinitProvider()),r=(r+1)%Ul}))),a}}const jl=(t,e,i)=>i*e+(1-i)*t;class zl{constructor(e){var i;this.prevReported=void 0,this.params=e,this.slow=this.fast=this.smoothed=this.prevReported=e.initial,this.smoothed$=new t(e.initial),this.debounced$=new t(e.initial);const s=null!==(i=e.label)&&void 0!==i?i:'value'+Math.random().toString(16).substring(2,6);this.rawSeries$=new Vs(`raw_${s}`),this.smoothedSeries$=new Vs(`smoothed_${s}`),this.reportedSeries$=new Vs(`reported_${s}`)}next(t){this.slow=jl(this.slow,t,this.params.emaAlphaSlow),this.fast=jl(this.fast,t,this.params.emaAlphaFast);const e=this.params.fastDirection>0?Math.max:Math.min;this.smoothed=e(this.slow,this.fast),this.smoothed$.next(this.smoothed),(r(this.prevReported)||Math.abs(this.smoothed-this.prevReported)/this.prevReported>=this.params.changeThreshold)&&(this.prevReported=this.smoothed,this.debounced$.next(this.smoothed),this.reportedSeries$.next(this.smoothed)),this.rawSeries$.next(t),this.smoothedSeries$.next(this.smoothed)}}var Ql;!function(t){t[t.LOCAL_STORAGE=0]='LOCAL_STORAGE',t[t.SESSION_STORAGE=1]='SESSION_STORAGE',t[t.RUNTIME=2]='RUNTIME'}(Ql||(Ql={}));const Wl=new Map;let Jl=Ql.RUNTIME;const Kl=`vk-videoplayer-dummy-key-${Math.random()}`;(()=>{try{localStorage.setItem(Kl,'test'),localStorage.removeItem(Kl),Jl=Ql.LOCAL_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;try{sessionStorage.getItem(Kl),Jl=Ql.SESSION_STORAGE}catch(t){if(!(t instanceof DOMException||t instanceof TypeError))throw t;Jl=Ql.RUNTIME}}})();const Xl=(t,e)=>{switch(Jl){case Ql.LOCAL_STORAGE:try{localStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ql.SESSION_STORAGE:try{sessionStorage.setItem(t,e)}catch(t){if(!(t instanceof DOMException))throw t;console.error(t)}break;case Ql.RUNTIME:return void Wl.set(t,e);default:n(Jl)}},Zl=window.navigator.connection,tp=()=>{const t=null==Zl?void 0:Zl.downlink;if(s(t)&&10!==t)return 1e3*t},ep=()=>{const t=null==Zl?void 0:Zl.rtt;if(s(t)&&3e3!==t)return t},ip=(t,e,i)=>{const s=8*i;return s/(s/t+e)};class sp{constructor(e){var r,n;this.subscription=new i,this.tuningConfig=e;const o=sp.load('one_video_throughput')||(e.useBrowserEstimation?tp():void 0)||5e3,d=null!==(n=null!==(r=sp.load('one_video_rtt'))&&void 0!==r?r:e.useBrowserEstimation?ep():void 0)&&void 0!==n?n:0;if(this.throughput$=new t(o),this.rtt$=new t(d),this.rttAdjustedThroughput$=new t(ip(o,d,e.rttPenaltyRequestSize)),this.throughput=new zl({initial:o,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:-1,label:'throughput'}),this.rtt=new zl({initial:d,emaAlphaSlow:e.emaAlphaSlow,emaAlphaFast:e.emaAlphaFast,changeThreshold:e.changeThreshold,fastDirection:1,label:'rtt'}),e.useBrowserEstimation){const t=()=>{const t=tp();t&&this.throughput.next(t);const e=ep();s(e)&&this.rtt.next(e)};Zl&&'onchange'in Zl&&this.subscription.add(a(Zl,'change').subscribe(t)),t()}this.subscription.add(this.throughput.smoothed$.subscribe((t=>{Xl('one_video_throughput',t.toFixed(0))}))),this.subscription.add(this.rtt.smoothed$.subscribe((t=>{Xl('one_video_rtt',t.toFixed(0))}))),this.subscription.add(this.throughput.debounced$.subscribe(this.throughput$)),this.subscription.add(this.rtt.debounced$.subscribe(this.rtt$)),this.subscription.add(y({throughput:this.throughput.smoothed$,rtt:this.rtt.smoothed$}).pipe(u((({throughput:t,rtt:i})=>ip(t,i,e.rttPenaltyRequestSize))),S((t=>{const i=this.rttAdjustedThroughput$.getValue()||0;return Math.abs(t-i)/i>=e.changeThreshold}))).subscribe(this.rttAdjustedThroughput$))}destroy(){this.subscription.unsubscribe()}trackXHR(t){let e=0,s=v();const r=new i;switch(this.subscription.add(r),t.readyState){case 4:break;case 3:case 2:r.add(a(t,'progress').pipe(f()).subscribe((t=>{e=t.loaded,s=v()})));break;case 1:case 0:r.add(a(t,'loadstart').subscribe((()=>{e=0,s=v()})))}r.add(a(t,'loadend').subscribe((i=>{if(200===t.status){const t=i.loaded,r=v(),a=t-e,n=r-s;this.addRawSpeed(a,n)}r.unsubscribe()})))}trackStream(t){const e=t.getReader();if(!e)return void t.cancel('Could not get reader');let i=0;const s=v();let r=0,a=v();const n=i=>{e.releaseLock(),t.cancel(`Throughput Estimator error: ${i}`).catch((()=>{}))},o=({done:t,value:d})=>O(this,void 0,void 0,(function*(){t?this.addRawSpeed(i,v()-s):d&&(i+=d.byteLength,r+=d.byteLength,r>=this.tuningConfig.streamMinSampleSize&&v()-a>=this.tuningConfig.streamMinSampleTime&&(this.addRawSpeed(r,v()-a),r=0,a=v()),yield null==e?void 0:e.read().then(o,n))}));null==e||e.read().then(o,n)}addRawSpeed(t,e){if(sp.sanityCheck(t,e)){const i=8*t/e;this.throughput.next(i)}}addRawThroughput(t){this.throughput.next(t)}addRawRtt(t){this.rtt.next(t)}static sanityCheck(t,e){const i=8*t/e;return!(!i||!isFinite(i))&&(!(i>1e6)&&(!(i<30)&&(!(t<10240)&&!(e<=20))))}static load(t){var e;const i=(t=>{var e,i;switch(Jl){case Ql.LOCAL_STORAGE:return null!==(e=localStorage.getItem(t))&&void 0!==e?e:void 0;case Ql.SESSION_STORAGE:return null!==(i=sessionStorage.getItem(t))&&void 0!==i?i:void 0;case Ql.RUNTIME:return Wl.get(t);default:n(Jl)}})(t);if(s(i))return null!==(e=parseInt(i,10))&&void 0!==e?e:void 0}}const rp=(t=(t=>t))=>({playbackState:e,seekPosition:a,playbackAbort$:n,looped$:d,position$:h})=>new p((c=>{let l;const p=e.transitionEnded$.pipe(S((t=>(t.from===P.PAUSED||t.from===P.STOPPED)&&t.to===P.PLAYING))),f=e.stateChangeEnded$.pipe(S((t=>t.from===P.PLAYING&&t.to===P.PAUSED))),m=a.stateChangeEnded$.pipe(S((t=>{var i,r;return s(t.to)&&(null!==(r=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==r?r:e.getState())===P.PLAYING}))),v=a.stateChangeEnded$.pipe(S((t=>{var i,s;return r(t.to)&&(null!==(s=null===(i=e.getTransition())||void 0===i?void 0:i.from)&&void 0!==s?s:e.getState())===P.PLAYING}))),g=o(p,v).pipe(u((()=>t(h.getValue())))),b=o(o(f,m,n).pipe(u((()=>t(h.getValue())))),d.pipe(u(t)));return(new i).add(g.subscribe((e=>{l=t(e)}))).add(b.subscribe((e=>{const i=t(e);if(r(l)||l===i)return;const s={start:l,end:i};l=void 0,c.next(s)})))})),ap=rp((t=>t)),np=rp((t=>Math.round(1e3*t)+Date.now())),op={[k.SCREEN]:{vod:[A.HLS,A.HLS_ONDEMAND,A.DASH_WEBM_VK,A.DASH_WEBM,A.DASH,A.DASH_SEP_VK,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS_JS,A.MPEG],live:[A.HLS_LIVE,A.DASH_LIVE,A.DASH_LIVE_WEBM]},[k.CHROMECAST]:{vod:[A.DASH_WEBM_VK,A.DASH_WEBM,A.DASH_SEP_VK,A.DASH_SEP,A.DASH_ONDEMAND,A.HLS,A.HLS_ONDEMAND,A.MPEG],live:[A.HLS_LIVE]}};class dp{constructor(s={}){if(this.subscription=new i,this.logger=new w,this.isPlaybackStarted=!1,this.desiredState={playbackState:new js(P.STOPPED),seekPosition:new js(void 0),volume:new js({volume:1,muted:!1}),videoTrack:new js(void 0),autoVideoTrackSwitching:new js(!0),autoVideoTrackLimits:new js({}),isLooped:new js(!1),externalTextTracks:new js([]),currentTextTrack:new js(void 0),textTrackCuesSettings:new js({})},this.info={playbackState$:new t(P.STOPPED),position$:new t(0),duration$:new t(1/0),muted$:new t(!1),volume$:new t(1),availableQualities$:new t([]),availableQualitiesFps$:new t({}),currentQuality$:new t(void 0),isAutoQualityEnabled$:new t(!0),autoQualityLimitingAvailable$:new t(!1),autoQualityLimits$:new t({}),currentBuffer$:new t(void 0),isBuffering$:new t(!0),isStalled$:new t(!1),isEnded$:new t(!1),isLooped$:new t(!1),isLive$:new t(void 0),liveTime$:new t(void 0),currentFormat$:new t(void 0),availableTextTracks$:new t([]),currentTextTrack$:new t(void 0),throughputEstimation$:new t(void 0),rttEstimation$:new t(void 0),videoBitrate$:new t(void 0),hostname$:new t(void 0),httpConnectionType$:new t(void 0),httpConnectionReused$:new t(void 0),chromecastState$:new t(_.NOT_AVAILABLE),chromecastDeviceName$:new t(void 0),intrinsicVideoSize$:new t(void 0)},this.events={started$:new e,startAttempt$:new e,willPause$:new e,willResume$:new e,willDestruct$:new e,watchCoverageRecord$:new e,watchCoverageLive$:new e,managedError$:new e,fatalError$:new e,ended$:new e,looped$:new e,seeked$:new e,willSeek$:new e,firstBytes$:new e,firstFrame$:new e,log$:new e},this.experimental={element$:new t(void 0),enableDebugTelemetry$:new t(!1),dumpTelemetry:Bs},this.initLogs(),this.tuning=(t=>{const e={};for(const i of Object.keys(I)){const s=I[i],r=t[i];Array.isArray(s)&&Array.isArray(r)?e[i]=r:e[i]='object'==typeof s&&'object'==typeof r?Object.assign(Object.assign({},s),r):null!=r?r:s}return e})(s),this.chromecastInitializer=new L({receiverApplicationId:s.chromecastReceiverId,isDisabled:s.disableChromecast,dependencies:{logger:this.logger}}),this.throughputEstimator=new sp(this.tuning.throughputEstimator),this.initChromecastSubscription(),this.initDesiredStateSubscriptions(),Proxy&&Reflect)return new Proxy(this,{get:(t,e,i)=>{const s=Reflect.get(t,e,i);return'function'!=typeof s?s:(...i)=>{try{return s.apply(t,i)}catch(t){const s=i.map((t=>JSON.stringify(t,((t,e)=>{const i=typeof e;return['number','string','boolean'].includes(i)?e:null===e?null:`<${i}>`})))),r=`Player.${String(e)}`,a=`Exception calling ${r} (${s.join(', ')})`;throw this.events.fatalError$.next({id:r,message:a,thrown:t}),t}}}})}initVideo(t){var e,i;return this.config=t,this.domContainer=(t=>{const e='string'==typeof t.container?document.getElementById(t.container):t.container;return l(e,`Wrong container or containerId {${t.container}}`),e})(t),this.chromecastInitializer.contentId=null===(e=t.meta)||void 0===e?void 0:e.videoId,this.providerContainer=new Yl({screenFormatsPriority:[...op[k.SCREEN].live,...op[k.SCREEN].vod],chromecastFormatsPriority:[...op[k.CHROMECAST].live,...op[k.CHROMECAST].vod],sources:t.sources,meta:null!==(i=t.meta)&&void 0!==i?i:{},container:this.domContainer,desiredState:this.desiredState,dependencies:{throughputEstimator:this.throughputEstimator,chromecastInitializer:this.chromecastInitializer,logger:this.logger},tuning:this.tuning}),this.initProviderContainerSubscription(this.providerContainer),this.initStartingVideoTrack(this.providerContainer),this.providerContainer.init(),this.initDebugTelemetry(),this}destroy(){var t;this.events.willDestruct$.next(),null===(t=this.providerContainer)||void 0===t||t.destroy(),this.throughputEstimator.destroy(),this.chromecastInitializer.destroy(),this.subscription.unsubscribe()}play(){const t=this.desiredState.playbackState;return t.getState()!==P.PLAYING&&t.startTransitionTo(P.PLAYING),this}pause(){const t=this.desiredState.playbackState;return t.getState()!==P.PAUSED&&t.startTransitionTo(P.PAUSED),this}stop(){const t=this.desiredState.playbackState;return t.getState()!==P.STOPPED&&t.startTransitionTo(P.STOPPED),this}seekTime(t){return this.events.willSeek$.next({from:this.getExactTime(),to:t}),this.desiredState.seekPosition.startTransitionTo(t),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()===_.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()===_.CONNECTED?this.chromecastInitializer.setMuted(t):this.desiredState.volume.startTransitionTo({volume:this.desiredState.volume.getState().volume,muted:t}),this}setQuality(t){l(this.providerContainer);const e=this.providerContainer.providerOutput.availableVideoTracks$.getValue();e.length||(this.explicitInitialQuality=t);const i=e.find((e=>e.quality===t));return i&&this.desiredState.videoTrack.startTransitionTo(i.id),this}setAutoQuality(t){return this.desiredState.autoVideoTrackSwitching.startTransitionTo(t),this}setAutoQualityLimits(t){return this.desiredState.autoVideoTrackLimits.setState(t),this}setExternalTextTracks(t){return this.desiredState.externalTextTracks.startTransitionTo(t.map((t=>Object.assign({type:'external'},t)))),this}selectTextTrack(t){var e;return(void 0===t||(null===(e=this.providerContainer)||void 0===e?void 0:e.providerOutput.availableTextTracks$.getValue().find((e=>e.id===t))))&&this.desiredState.currentTextTrack.startTransitionTo(t),this}setTextTrackCueSettings(t){return this.desiredState.textTrackCuesSettings.startTransitionTo(t),this}setLooped(t){return this.desiredState.isLooped.startTransitionTo(t),this}toggleChromecast(){this.chromecastInitializer.toggleConnection()}getExactTime(){var t;l(this.providerContainer);const e=this.providerContainer.providerOutput.element$.getValue();if(r(e))return this.info.position$.getValue();const i=this.desiredState.seekPosition.getTransition(),a=null!==(t=null==i?void 0:i.to)&&void 0!==t?t:null==i?void 0:i.from;return s(a)?a:e.currentTime}getAllLogs(){return this.logger.getAllLogs()}initDesiredStateSubscriptions(){this.subscription.add(o(this.desiredState.playbackState.stateChangeStarted$,this.desiredState.playbackState.forceChanged$).pipe(u((t=>t.to))).subscribe(this.info.playbackState$)).add(this.desiredState.isLooped.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isLooped$)).add(this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.isAutoQualityEnabled$)).add(this.desiredState.autoVideoTrackLimits.stateChangeEnded$.pipe(u((t=>t.to))).subscribe(this.info.autoQualityLimits$));const t=new i;this.subscription.add(t),this.subscription.add(this.desiredState.playbackState.stateChangeStarted$.pipe(S((t=>t.to===P.PLAYING))).subscribe((()=>{t.unsubscribe(),t.add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((t=>t.to===P.PLAYING||t.to===P.PAUSED)),m(0),f()).subscribe((t=>{const e=t.to===P.PLAYING,i=this.info.muted$.getValue(),s=e?i?D.SuccessWithoutSound:D.SuccessWithSound:D.Failed;this.events.startAttempt$.next(s)})))}))),this.subscription.add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((t=>t.to===P.PLAYING)),m(0)).subscribe((()=>{if(!this.isPlaybackStarted){const t=this.info.muted$.getValue();this.isPlaybackStarted=!0,this.events.started$.next(t)}}))).add(this.desiredState.playbackState.stateChangeStarted$.subscribe((t=>{switch(t.to){case P.PAUSED:this.events.willPause$.next();break;case P.PLAYING:this.isPlaybackStarted&&this.events.willResume$.next()}})))}initProviderContainerSubscription(e){this.subscription.add(e.providerOutput.willSeekEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition(),e=null==t?void 0:t.to;s(e)&&(this.desiredState.seekPosition.setState(e),this.desiredState.seekPosition.startTransitionTo(void 0))}))).add(e.providerOutput.seekedEvent$.subscribe((()=>{const t=this.desiredState.seekPosition.getTransition();s(null==t?void 0:t.to)||this.desiredState.seekPosition.setState(void 0),this.events.seeked$.next()}))).add(e.current$.pipe(u((t=>t.type))).subscribe(this.info.currentFormat$)).add(e.current$.pipe(u((t=>t.destination)),c()).subscribe((()=>{this.isPlaybackStarted=!1}))).add(e.providerOutput.availableVideoTracks$.pipe(u((t=>t.map((({quality:t})=>t)).sort(((t,e)=>Cs(t)?1:Cs(e)?-1:Is(e,t)?1:-1))))).subscribe(this.info.availableQualities$)).add(e.providerOutput.availableVideoTracks$.subscribe((t=>{const e={};for(const i of t)i.fps&&(e[i.quality]=i.fps);this.info.availableQualitiesFps$.next(e)}))).add(e.providerOutput.currentVideoTrack$.subscribe((t=>{this.info.currentQuality$.next(null==t?void 0:t.quality),this.info.videoBitrate$.next(null==t?void 0:t.bitrate);const i=e.providerOutput.element$.getValue();i&&this.info.intrinsicVideoSize$.next({width:i.videoWidth,height:i.videoHeight})}))).add(e.providerOutput.hostname$.pipe(c()).subscribe(this.info.hostname$)).add(e.providerOutput.httpConnectionType$.pipe(c()).subscribe(this.info.httpConnectionType$)).add(e.providerOutput.httpConnectionReused$.pipe(c()).subscribe(this.info.httpConnectionReused$)).add(e.providerOutput.currentTextTrack$.subscribe(this.info.currentTextTrack$)).add(e.providerOutput.availableTextTracks$.subscribe(this.info.availableTextTracks$)).add(e.providerOutput.autoVideoTrackLimitingAvailable$.subscribe(this.info.autoQualityLimitingAvailable$)).add(e.providerOutput.currentBuffer$.subscribe(this.info.currentBuffer$)).add(e.providerOutput.duration$.subscribe(this.info.duration$)).add(e.providerOutput.isBuffering$.subscribe(this.info.isBuffering$)).add(e.providerOutput.isLive$.subscribe(this.info.isLive$)).add(e.providerOutput.liveTime$.subscribe(this.info.liveTime$)).add(e.providerOutput.volume$.pipe(u((t=>t.muted)),c()).subscribe(this.info.muted$)).add(e.providerOutput.volume$.pipe(u((t=>t.volume)),c()).subscribe(this.info.volume$)).add((({seekPosition:t,position$:e})=>o(t.stateChangeStarted$.pipe(u((t=>t.to)),S(s)),e.pipe(S((()=>r(t.getState())&&r(t.getTransition()))))))({seekPosition:this.desiredState.seekPosition,position$:e.providerOutput.position$}).subscribe(this.info.position$)).add(o(e.providerOutput.endedEvent$.pipe(T(!0)),e.providerOutput.seekedEvent$.pipe(T(!1))).pipe(c()).subscribe(this.info.isEnded$)).add(e.providerOutput.endedEvent$.subscribe(this.events.ended$)).add(e.providerOutput.loopedEvent$.subscribe(this.events.looped$)).add(e.providerError$.subscribe(this.events.managedError$)).add(e.noAvailableProvidersError$.pipe(u((t=>({id:'NoProviders',message:'No suitable providers or all providers failed'})))).subscribe(this.events.fatalError$)).add(e.providerOutput.element$.subscribe(this.experimental.element$)).add(e.providerOutput.firstBytesEvent$.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 n=new t(!1);this.subscription.add(e.providerOutput.seekedEvent$.subscribe((()=>n.next(!1)))).add(e.providerOutput.willSeekEvent$.subscribe((()=>n.next(!0))));const d=new t(!0);this.subscription.add(e.current$.subscribe((()=>d.next(!0)))).add(this.desiredState.playbackState.stateChangeEnded$.pipe(S((({to:t})=>t===P.PLAYING)),f()).subscribe((()=>d.next(!1))));let h=0;const p=o(e.providerOutput.isBuffering$,n,d).pipe(u((()=>{const t=e.providerOutput.isBuffering$.getValue(),i=n.getValue()||d.getValue();return t&&!i})),c());this.subscription.add(p.subscribe((t=>{t?h=window.setTimeout((()=>this.info.isStalled$.next(!0)),this.tuning.stallIgnoreThreshold):(window.clearTimeout(h),this.info.isStalled$.next(!1))})));const m=new i;this.subscription.add(m);const v=o(a(window,'beforeunload'),this.events.willDestruct$,e.current$.pipe(S((t=>Boolean(null==t?void 0:t.provider)))));e.providerOutput.isLive$.pipe(c()).subscribe((t=>{switch(l(this.providerContainer),m.unsubscribe(),t){case!0:m.add(np({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,playbackAbort$:v,looped$:this.events.looped$,position$:this.providerContainer.providerOutput.position$}).subscribe(this.events.watchCoverageLive$));break;case!1:m.add(ap({seekPosition:this.desiredState.seekPosition,playbackState:this.desiredState.playbackState,looped$:this.events.looped$,playbackAbort$:v,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(u((t=>null==t?void 0:t.castDevice.friendlyName))).subscribe(this.info.chromecastDeviceName$)),this.subscription.add(this.chromecastInitializer.errorEvent$.subscribe(this.events.managedError$))}initStartingVideoTrack(t){const e=new i;this.subscription.add(e),this.subscription.add(t.current$.pipe(c(((t,e)=>t.provider===e.provider))).subscribe((()=>{e.unsubscribe(),e.add(t.providerOutput.availableVideoTracks$.pipe(S((t=>t.length>0)),f()).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=Hs(t,{container:this.domContainer.getBoundingClientRect(),throughput:this.throughputEstimator.throughput$.getValue(),tuning:this.tuning.autoTrackSelection,limits:this.desiredState.autoVideoTrackLimits.getState(),forwardBufferHealth:0})),this.desiredState.videoTrack.startTransitionTo(e.id),this.info.currentQuality$.next(e.quality),this.info.videoBitrate$.next(e.bitrate)}initLogs(){this.subscription.add(o(this.desiredState.videoTrack.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'quality',type:'start'})))),this.desiredState.videoTrack.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'quality',type:'end'})))),this.desiredState.autoVideoTrackSwitching.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'start'})))),this.desiredState.autoVideoTrackSwitching.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'autoQualityEnabled',type:'end'})))),this.desiredState.seekPosition.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'seekPosition',type:'start'})))),this.desiredState.seekPosition.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'seekPosition',type:'end'})))),this.desiredState.playbackState.stateChangeStarted$.pipe(u((t=>({transition:t,entity:'playbackState',type:'start'})))),this.desiredState.playbackState.stateChangeEnded$.pipe(u((t=>({transition:t,entity:'playbackState',type:'end'}))))).pipe(u((t=>({component:'desiredState',message:`[${t.entity} change] ${t.type}: ${JSON.stringify(t.transition)}`})))).subscribe(this.logger.log)),this.subscription.add(this.logger.log$.subscribe(this.events.log$))}initDebugTelemetry(){var t;const e=null===(t=this.providerContainer)||void 0===t?void 0:t.providerOutput;l(this.providerContainer),l(e),Ms={},this.experimental.enableDebugTelemetry$.next(this.tuning.enableTelemetryAtStart),[this.experimental.enableDebugTelemetry$.subscribe((t=>{Ns=t})),this.providerContainer.current$.subscribe((({type:t})=>Us('provider',t))),e.duration$.subscribe((t=>Us('duration',t))),e.availableVideoTracks$.pipe(S((t=>!!t.length)),f()).subscribe((t=>Us('tracks',t))),this.events.fatalError$.subscribe(new Vs('fatalError')),this.events.managedError$.subscribe(new Vs('managedError')),e.position$.subscribe(new Vs('position')),e.currentVideoTrack$.pipe(u((t=>null==t?void 0:t.quality))).subscribe(new Vs('quality')),e.currentBuffer$.subscribe(new Vs('buffer')),e.isBuffering$.subscribe(new Vs('isBuffering'))].forEach((t=>this.subscription.add(t))),Us('codecs',Object.keys(Ll).filter((t=>Ll[t])))}}const up='@vkontakte/videoplayer-core@2.0.47';export{_ as ChromecastState,R as HttpConnectionType,P as PlaybackState,dp as Player,up as SDK_VERSION,D as StartStatus,A as VideoFormat,ks as VideoQuality};
|